Wednesday, December 22, 2010

Configuring Struts with Spring

There are 2 ways in which Spring features can be injected in Struts. The common point in all the 2 strategies is that we need to register a Struts plug-in that is aware of the Spring application context. Add the following code to your struts-config.xml to register the plug-in:

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/training-servlet.xml,/WEB-INF/…"/>
</plug-in>

ContextLoaderPlugIn loads a Spring application context (a WebApplication-
Context, to be specific), using the context configuration files listed (commaseparated)
in its contextConfigLocation property.

  • Extending the ActionSupport class instead of Action class




public class ListCourseAction extends ActionSupport {
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {

ApplicationContext context = getWebApplicationContext();
CourseService courseService = (CourseService) context.getBean("courseService");
Set allCourses = courseService.getAllCourses();
request.setAttribute("courses", allCourses);
return mapping.findForward("courseList");
}
}
The ActionSupport class extends the Action class and has the added method of getWebApplicationContext() which will return the current applicationContext with the help of which we can get the beans.

  • Using the DelegatingActionProxy

The struts action mapping in the struts-config needs to have the DelegatingActionProxy as the class attribute value

<action path="/listCourses"
type="org.springframework.web.struts.DelegatingActionProxy"/>

and the equivalent mapping in the spring config should be

<bean name="/listCourses"
class="com.springinaction.training.struts.ListCourseAction">
<property name="courseService">
<ref bean="courseService"/>
</property>
</bean>

Tuesday, December 21, 2010

Advantages of Spring MVC over Struts

1. Spring provides a very clean division between controllers, JavaBean models, and views.

2. Spring’s MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.

3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

4. Spring MVC is truly view-agnostic. You don’t get pushed to use JSP if you don’t want to; you can use Velocity,XLST or other view technologies. If you want to use a custom view mechanism – for example, your own templating language – you can easily implement the Spring View interface to integrate it.

5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

8. No ActionForms. Bind directly to domain objects

9. More testable code (validation has no dependency on Servlet API)

10. Struts imposes dependencies on your Controllers (they must extend a Struts class), Spring doesn’t force you to do this although there are convenience Controller implementations that you can choose to extend.

11. Spring has a well defined interface to business layer

12. Spring offers better integration with view technologies other than JSP (Velocity / XSLT / FreeMarker / XL etc.)

Monday, December 13, 2010

Use of design Patterns in Java API

http://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns

http://www.briandupreez.net/search/label/Patterns

http://www.oodesign.com/

Sunday, December 12, 2010

Is this Thread Safe II

Is the given code thread safe?


public class Test {
private static int count = 0;
private static final Object lock= new Object();
public synchronized void foo() {
count++;
}
}


Though at first it looks thread safe but it is not as the counter is a static field and to provide atomicity we need to hold a lock on the class object. So there 4 ways of doing it

1) To make the method static


public static synchronized void incrementCount() {
count++;
}


2) To take lock on the Class object explicitly


public void incrementCount() {
synchronize (Test.class) {
count++;
}
}


3) To take a lock on another static Object


private static final Object countLock = new Object();

public void incrementCount() {
synchronize (countLock) {
count++;
}
}


4) Use the new AtomicInteger object from the java.util.concurrent.atomic package


private final static AtomicInteger count = new AtomicInteger(0);

public void foo() {
count.incrementAndGet();
}

Saturday, December 11, 2010

JIT compiler

sources JIT Source

IT compilers alter the role of the VM a little by directly compiling Java bytecode into native platform code, thereby relieving the VM of its need to manually call underlying native system services. The purpose of JIT compilers, however, isn't to allow the VM to relax. By compiling bytecodes into native code, execution speed can be greatly improved because the native code can be executed directly on the underlying platform.

When JIT compiler is installed, instead of the VM calling the underlying native operating system, it calls the JIT compiler. The JIT compiler in turn generates native code that can be passed on to the native operating system for execution. The primary benefit of this arrangement is that the JIT compiler is completely transparent to everything except the VM.

Stage 1:

JIT compiler maintains a internal table called as V-Table (Virtual Table) that has pointer to the methods in a Class. In case of derived classes only the Derived method are taken into consideration. When a JIT compiler is first loaded, the VM pulls a little trick with the V-table to make sure that methods are compiled into native code rather than executed. What happens is that each bytecode address in the V-table is replaced with the address of the JIT compiler itself.

Stage 2:

When the VM calls a method through the address in the V-table, the JIT compiler is executed instead. The JIT compiler steps in and compiles the Java bytecode into native code and then patches the native code address back to the V-table. From now on, each call to the method results in a call to the native version. Methods are compiled only when they are called. The first time a method is called, it is compiled; subsequent calls result in the native code being executed.

Stage 3:

For Backward compatilibily purposes, VM actually maintains two V-Tables. One for Native Code and the other for original Bytecode, so that when methods needs to be executed with JIT compiler off, then they are executed from V-table having Methods in Bytecode

Improvement in Performance:

Because the AWT is already written in native code, programs that rely heavily on the AWT don't reap the same performance gains as programs that depend on pure Java bytecode. A heavily graphical program that makes great use of the AWT may see performance gains by an order of only two or three.

On the other hand, a heavily processing-intensive Java program that uses lots of floating-point math may see performance gains closer to an order of fifteen. This happens because native Pentium code on a Windows machine is very efficient with floating-point math. Of course, other platforms may differ in this regard.

When to enable JIT compiler

if 80% of the execution time is dependent on 20% of the code,this is very good scenario to use JIT. Its going to reduce the execution time by 30%

Thursday, December 9, 2010

How to map to a database view in Hibernate

There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level.


<class name="Summary">
<subselect>
select item.name, max(bid.amount), count(*)
from item
join bid on bid.item_id = item.id
group by item.name
</subselect>
<synchronize table="item"/>
<synchronize table="bid"/>
<id name="name"/>
...
</class>

Declare the tables to synchronize this entity with, ensuring that auto-flush happens correctly and that queries against the derived entity do not return stale data. The is available both as an attribute and a nested mapping element.

Monday, December 6, 2010

Setting the InitialContext across major Application Servers

Weblogic

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7001");

InitialContext context = new InitialContxt(env);

Websphere

env.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
env.put(Context.PROVIDER_URL,"iiop://localhost:900");

JBoss

env.put(InitialContext.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
env.put(InitialContext.PROVIDER_URL,"jnp://localhost:1099");

Sunday, December 5, 2010

IS this Thread Safe

I found this question in one of the forums so thought of sharing it

In the class below, is method getIt() thread safe and why?

public class X {
private long myVar;
public void setIt(long var){
myVar = var;
}
public long getIt() {
return myVar;
}
}

We all know that it is not thread safe as its possible that two concurrent threads may try to update and access the myVar at the same time. But an alternate answer i found was this

"It's not thread-safe because the instance variable is a 64-bit primitive. Read-only operations on instance-level primitives are atomic for 32-bit variables. But atomicity is not guaranteed for 64-bit variables because the JVM spec allows implementations to use two 32-bit read operations to access a 64-bit value. If a thread is in the process of reading the two 32-bit words of myVar, an interrupting thread could write to the high or low word of myVar before the first thread successfully reads both. This would result in a corrupt return value from getIt()."