Archive

Archive for February, 2010

CDI Power Constructs for JEE-6: @Inject, @Qualifier, @Produces, @Disposes and @Named

February 8th, 2010 Shrihari No comments

In pre-JEE 5 era, tiered architectures boasted of having loosely coupled layers and a predefined flows for the request-response were outlined, designed, implemented and tested. Core JEE patterns evolved which defined breadths of request processing and response throwbacks, for variety of scenarios.
A thick layered architecture would have a view controlled by controller command, which invoked a facade and chain of command passed on to DAO or EntityBean which manipulated the model. Various configuration idiosyncrasies had to be carefully set and presented in the final deployment.

Enter JEE 6 – the era of configuration free, and annotation driven wiring of components. The JSR-299 (Contexts and Dependency Injection for Java) improvises over JSR-330 (Dependency Injection for Java) and brings the power of Inversion of Controller to enterprise container. Five annotation constructs : @Inject, @Qualifier, @Produces, @Disposes and @Named provide the basic building blocks for getting a thin loosely coupled layered modular structure to the view, hiding the boilerplate code one had to write before JEE 6. Lets briefly look at these annotations and how do they fit in with regard to a shopping cart example:

@Qualifier
We use @Qualifier for defining different bean types. In JEE 6 context, @Qualifier is used to define independent functional flows. In case of shopping cart example, it could denote the shopping cart access manager as shown below:

@Qualifier
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ShoppingCart {}

@Produces
The annotation @Produces is used to instantiate a bean type, specifically on an . If a bean type is a qualified (i.e.) annotated with @Qualifier, the @Produces with be followed by the custom qualifier interface. In the shopping cart example above, if we need to define a factory method to return a manager instance to be available under a managed bean, we could defines as below:

public @Produces @ShoppingCart ShoppingCartManager getShoppingCart() {
      return new ShoppingCartManagerImpl();
 }

where ShoppingCartManager defines methods to query and add items to the cart as below:

public abstract class ShoppingCartManager{
    @PersistenceContext EntityManager em;

     public abstract List<Items> getAllItems();
     public abstract void addItem(Item item);
     ...
 }

@Disposes
A @Dispose annotation is used in exact opposite semantics of @Produces. If you want release some held resources by the manager, or destroy the session specific shopping cart in this example, you could use it on the method.

public void clearShoppingItem(@Disposes @ShoppingCart ShoppingCartManager cart) {
      cart.clearItems();
      cart = null;
 }

@Inject
@Inject provides the ability to define the dependency injection at the point of usage, qualified or unqualified. If a bean type has been qualified, the appropriate Qualifier is as well used.

@Inject @ShoppingCart ShoppingCartManager manager;

@Named
@Named annotation helps the component to be used in the presentation or view layer using EL, supported by Camelcase variable naming convention. So in the shopping cart example, using #{items} would query the accessor method to retreive the shopping cart items

@Inject @ShoppingCart ShoppingCartManager manager;

@Named
public List<Item> getItems() {
      return manager.getAllItems();
 }

Using these constructs, one can implement complex workflows, without configuration hassles, and maintaining high cohesion and loose coupling.

Categories: jee-light Tags: ,

Controlling Thread Execution using CyclicBarriers in Java

February 3rd, 2010 Shrihari No comments

Barriers are threading concepts which define checkpoints within the thread-execution semantics which aid in controlling a group of threads to proceed after all threads in the group has arrived at that checkpoint.  Java’s java.util.concurrent package defines a CyclicBarrier class which is aptly used for such as scenario. It is prefixed with cyclic to denote that we can reuse it any number of times in case of repeatable checkpoints.

We will see how this specific class could be used for the two different scenarios.

1)Single post-barrier action thread.
Single Post Barrier Action
In this scenario you could create a CyclicBarrier with number of threads and a reference to action thread so that it gets invoked post-barrier. Lets look at an example for deriving an average throughput time taken for compute intensive modules whose start and end times are captured. So the example fits the barrier scenario where by the pre-barrier thread computes the difference between the start and end time and post-barrier action thread computes the average out of the accumulated differences.

public class SingleActionPostBarrier
{ private int numberOfThreads = 1;
  private int responseTimes[];

  public SingleActionPostBarrier(int threadCount)
  {  numberOfThreads = threadCount;
     responseTimes = new int[threadCount];
  }

  public void doRun()
  { CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, new ComputeAverage());
    ExecutorService execservice = Executors.newFixedThreadPool(numberOfThreads);
    for (int i = 0; i < numberOfThreads; i++)
    {   execservice.execute(new Runnable()
        {   public void run()
            {  long start = System.currentTimeMillis();
               //invoke the process centric action method..
               long end = System.currentTimeMillis();
               responseTimes[i] = (end-start)/1000;

               try
               { barrier.await();
               }catch(BarrierBrokenException bbe)
	       {
	       }catch(InterruptedException inex)
	       {}
	     }
         }
     }//end of for-loop
  }

  class ComputeAverage implements Runnable
  {    public void run()
       { int sum = 0;
         for(int diff:responseTimes)
         {  sum += diff;
         }
         if (sum!=0) System.out.println("Average Response Time :"+(sum/responseTimes.length));
       }
  }
}

2) Multiple post-barrier action thread.
Multiple Post Barrier Action
From the previous example, lets tweak it and say we need to repeat the same profile computation but for a different action workflow and capture in another responseTimes array. The end result is compute the difference in profile times for these actions for multi threaded behavior and deduce a sorted list. The following snippet would explain it

public class MultiActionPostBarrier
{ private int numberOfThreads = 1;
  private int responseTimes[];
  private int responseTimesForAnotherAction[];

  public SingleActionPostBarrier(int threadCount)
  {  numberOfThreads = threadCount;
     responseTimes = new int[threadCount];
     responseTimesForAnotherAction = new int[threadCount];
  }

  public void doRun()
  { CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, new SortDiffResponse());
    ExecutorService execservice = Executors.newFixedThreadPool(numberOfThreads);
    for (int i = 0; i < numberOfThreads; i++)
    {   execservice.execute(new Runnable()
        {   public void run()
            {  long start = System.currentTimeMillis();
               //invoke the process centric action method..
               long end = System.currentTimeMillis();
               responseTimes[i] = (end-start)/1000;

               try
               { barrier.await();
               }catch(BarrierBrokenException bbe)
	       {
	       }catch(InterruptedException inex)
	       {}

               start = System.currentTimeMillis();
               //invoke the process centric action method..
               end = System.currentTimeMillis();
               responseTimesForAnotherAction[i] = (end-start)/1000;

		// compute the difference
	       responseTimes[i] = responseTimes[i] - responseTimesForAnotherAction[i];
               try
               { barrier.await();
               }catch(BarrierBrokenException bbe)
	       {
	       }catch(InterruptedException inex)
	       {}
	     }
         }
     }//end of for-loop
  }

  class SortDiffResponse implements Runnable
  {    public void run()
       { Arrays.sort(responseTimes);
         for(int diff:responseTimes)
         {  System.out.println(responseTimes[i]);
         }
       }
  }
}

Using CyclicBarriers one could reuse the barrier checkpoint for complex thread behaviors. Please refer to dzone article for an interesting read on the same,.

Categories: jee-light Tags:

Wooah! Back after two months

February 2nd, 2010 Shrihari No comments

Took a break from technical blogging! Am back and will make it my habit to blog regularly ! Keep visiting and learning! And drop your most valuable and priceless comments!

Categories: jee-light Tags: