EJB 3.x : Lifecycle and Concurrency models (part 1)

Java EE component life cycle and concurrency related details might not be new for seasoned professionals, but it is something which can take time to sink in for beginners.


As far as EJBs are concerned, understanding their life cycle (and related concurrency scenarios) is extremely critical in order to ensure appropriate usage and solution design using EJBs. It’s easy to misuse them !



Bean Life Cycle


I’ll quickly cover Stateless and Stateful beans in this post and skip Lima Beans for the time being ;-)

  • Stateful Session Beans – life cycle + concurrency handling
  • Stateless beans – concurrency model only, since I had briefly covered the lifecycle in one of my previous posts.

What are the distinct states in the life cycle of a Stateful Session Bean?

  • Does Not Exist
  • Ready
  • Passivated

How do the states change? What triggers them?

Here is a quick tabular snap shot and a high level diagram. For more details, read on . . .


Stateless Session Bean Life Cycle State diagram

Note: DNE – Does Not Exist, R – Ready, P – Passivated, SFSB – Statelful Session Bean

State Transition Triggers Callbacks
DNE to R When a SFSB instance is first accessed via JNDI or DI @PostConstruct
R to DNE Container shuts down, client invokes method annotated with @Remove, the bean reaches idle time out threshold designated by DD or @StatefulTimeout @PreDestroy
R to P The EJB container passivates idle beans and removes them from active memory based on specific algorithms @PrePassivate
P to DNE The bean reaches idle time out threshold designated by DD or @StatefulTimeout Note: @PreDestroy annotated method is NOT invoked
P to R When the client invokes a SFSB instance after it is passivated but has not timed out yet @PostActivate

Note: If a SFSB throws an exception during request processing, its instance is destroyed i.e. it goes to a DNE state. The @PreDestroy annotated method is not invoked in this case

Now that we have some idea about the life cycle of a SFSB, let’s try to take a look at how do these beans behave under load i.e. when the application is used by multiple users at a time which translates into concurrent access of SFSB instances

Stateful Session Beans: Concurrency Management

Thread safety is one of the core features of EJBs. The point to be noted is that this thread safety is free of cost and does not need any concurrency related constructs to be coded in by the bean developer himself (there are a few exceptions). As far as SFSB are concerned, the EJB container ensures that only one thread can access a bean instance at a particular time.

In this example, we are trying to simulate concurrent access to a single instance of a SFSB by invoking a test Servlet via JMeter. The Servlet injects the bean via DI and calls a method on it. The SFSB method just uses a Thread.sleep() to pretend as if it’s executing something.

package com.abhirockzz.wordpress.ejb.lifecycle.stateful;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateful;

public class MyStatefulBean {

    public MyStatefulBean() {

    public void act() {
        System.out.println("Entered MyStatefulBean/act() on " + new Date().toString() + " . SFSB instance " + this.hashCode() + " Thread : " + Thread.currentThread().getName());
        try {
        } catch (InterruptedException ex) {
            Logger.getLogger(MyStatefulBean.class.getName()).log(Level.SEVERE, null, ex);

        System.out.println("Exit MyStatefulBean/act() on " + new Date().toString() + " . SFSB instance " + this.hashCode() + " Thread : " + Thread.currentThread().getName());




package com.abhirockzz.wordpress.ejb.lifecycle.stateful;

import java.io.IOException;
import java.util.Date;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "SFSBTestServlet", urlPatterns = {"/SFSBTestServlet"})
public class SFSBTestServlet extends HttpServlet {

    public SFSBTestServlet() {

    MyStatefulBean mySFSB;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Entered SFSBTestServlet/doGet() on " + new Date().toString() + " . Servlet instance " + this.hashCode() + " Thread : " + Thread.currentThread().getName());




HTTP GET request via JMeter



Concurrent request simulation via JMeter



  • Since a Servlet itself is not thread safe, multiple threads will in fact enter the doGet() method
  • A single instance of the SFSB (evident via the hashCode result) in being accessed concurrently (see the thread names in the logged statements)
  • Only one thread will be able to access the SFSB instance though – other threads wait for their turn while the SFSB method returns. This delay is noticeable via the log statements on the console



Console logs


What about Stateless Beans?

These beans are inherently thread safe. Why? It is because by default, the container makes sure that each new request is served by a new instance of the bean. Remember, that a client can obtain a reference to stateless bean in 3 possible ways – DI, JNDI or via a remote interface (RMI). In all these cases, it is the container (proxy) which intercepts the call – thus, even if multiple threads are seemingly accessing the same bean instance, its actually not the same one ;-)

package com.abhirockzz.wordpress.ejb.lifecycle.stateless;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;

public class MyStatelesslBean {

    public void act() {

        System.out.println("Entered MyStatelesslBean/act() on " + new Date().toString() + " . SLSB instance " + this.hashCode() + " Thread : " + Thread.currentThread().getName());
        try {
        } catch (InterruptedException ex) {
            Logger.getLogger(MyStatelesslBean.class.getName()).log(Level.SEVERE, null, ex);

        System.out.println("Exit MyStatelesslBean/act() on " + new Date().toString() + " . SLSB instance " + this.hashCode() + " Thread : " + Thread.currentThread().getName());


package com.abhirockzz.wordpress.ejb.lifecycle.stateless;

import java.io.IOException;
import java.util.Date;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "SLSBTestServlet", urlPatterns = {"/SLSBTestServlet"})
public class SLSBTestServlet extends HttpServlet {

    MyStatelesslBean slsb;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("Entered SLSBTestServlet/doGet() on " + new Date().toString() + " . Servlet instance " + this.hashCode() + " Thread : " + Thread.currentThread().getName());






  • Since a Servlet itself is not thread safe, multiple threads will in fact enter the doGet() method
  • Different instances of the SLSB (evident via the hashCode result) are being picked by the container to manage concurrent requests (see the thread names in the logged statements).
  • In spite of concurrent requests, each request thread is getting serviced by a new instance

Console logs


That’s all for now! I am planning to cover Singleton Session beans in a future post. Stay tuned . . . .

Thanks for reading! :-)


Posted in Java, Java EE | Tagged , , , , , , , | Leave a comment

Book Review: Java EE 7 Performance Tuning and Optimization

This is a review of the book Java EE 7 Performance Tuning and Optimization


What is this book about?

As the title clearly suggests, this book deals with Performance Tuning. It focuses on tuning, monitoring and optimizing the performance of Java EE applications in particular.

It starts off with basics of Performance Tuning and gives us an insight into the various kinds of performance related issues which one might face in the context of enterprise grade, distributed web (Java EE) applications. The book provides a quick fire tour of Java EE 7, familiarizes the reader with the basics of JVM (memory model, garbage collection. concurrency) and dives into the nitty-gritty of Performance Testing in Java.

The author guides us through some common performance issues and their symptoms along with a detailed insight of Java monitoring and profiling tools (in the JDK, IDEs etc). Topics like CPU, Memory and Thread Profiling have dedicated chapters and have been covered in great detail. The book delves into the topics of Tuning a Java EE application and its various facets (JVM, App Server, Web Server, the OS) along with a primer on Designing High performance Java EE applications. Last but not the least, the reader can dig into some Performance Tuning Tips (EJB, JPA, Servlets, JSF, Java SE) and apply the knowledge gained from the book in tuning a sample Java EE application hands-on!

Who has written this book?

The book has been authored by Osama Oransa. More about him here

What does the book cover?

The book is well organized and divided into twelve chapters. Let’s take a peek and see what each one has to offer.

Chapter 1 – Getting Started With Performance Tuning

This chapter introduces us to the world of Java EE performance tuning.

  • Classifies different types of performance related issues based on phases of discovery.
  • It goes on to differentiate typical application modes (standalone, thick and thin) along with a brief summary
  • Provides a quick peek into the all the components/layers of web applications and their properties which are critical from a performance standpoint – from the client end right down to the DB server

All in all, this lesson does a great job of getting things rolling and setting up the reader for what’s coming next. This is of great value for someone who is relatively new to the concept of Performance tuning and monitoring and allows her to get a decent head start.

Chapter 2 – Understanding Java Fundamentals

It lays a strong emphasis on strengthening the fundamentals associated with the Java Platform which are directly related to performance. Two primary topics which are covered are the JVM fundamentals and Java EE 7 (yes!)

  • Discussion of the JVM memory structure (as laid out by the JVM specification) and details around the Java HotSpot VM.
  • Exploration of the JVM Garbage Collector and its policies
  • Provides a brief overview of Java EE 7 – its specifications and features
  • Delves into some of the concurrency constructs available in Java EE – Async invocations, Singleton beans, non blocking I/O etc

Chapter 3- Getting Familiar with Performance Testing

Chapters 1 and 2 provided a good foundation and this chapter builds upon it. It deals with Performance Testing on a whole

  • It explores different facets of performance testing like types, components, tools, benchmarking etc along with an explanation of common testing terminologies and a discussion around performance testing in a Cloud environment.
  • The rest of the chapter deals with Apache JMeter and thoroughly covers web service, web application and database scripts with the help of succinct examples.

Chapter 4 – Monitoring Java Applications

This chapter deals with in depth coverage of the tools associated with performance monitoring and profiling in depth.

  • Starts off with an overview of the JDK monitoring and profiling tools landscape
  • It delves into details of these tools – memory map and heap analysis tools, JVisual VM and Oracle Java Mission Control
  • The NetBeans and Eclipse are covered as a part of the section which deals with IDE capabilities for JVM monitoring and profiling.
  • The chapter ends with a tour of JProfiler with a focus on the offline profiling mode.

Chapter 5 – Recognizing Common Performance Issues

This chapter builds on the performance issues overview provided in Chapter 1. It brings into focus, some of the frequently occurring performance issues and briefly looks at each of them

  • Explores Threading and deadlock related issues
  • Discusses performance issues which can be attributed to to memory (leakage), improper use of remote calls, database performance etc
  • The chapter also explores client side issues related to (JavaScript, CSS etc) and looks at some browser integrated dev tools (Chrome, IE, Firefox) which can help track such problems.

Chapter 6 – CPU Time Profiling

This chapter deals takes up one of the key aspects in Java profiling – CPU Time profiling

  • Discusses three profilers – NetBeans native profiler, the Java Mission Control and JProfiler
  • Explains how to interpret and make sense of the results obtained from the profiler tools
  • Delves into pin pointing and identification of performance issues (algorithm related, caching, threading etc) and provides a recipe/strategy for fixing them.

Chapter 7 – Thread Profiling

The deep dive into Java profiling continues. This time, the focus is one Thread profiling and its related nuances

  • As was the case with CPU Time profiling, the thread profiling options are explored with the help of NetBeans, Java Mission Control as well as JProfiler
  • Explains how to extract thread dumps with the help of JDK, application server and various profiler tools
  • Deals with interpretation of thread profiling results and analyzing thread dumps
  • Deep dive into exploration of threading related issues such as deadlock, blocked threads, unmanaged threads etc and builds on the recipe for fixing such issues (from the previous lesson)

Chapter 8 – Memory Profiling

This chapter marks the last section of the in-depth coverage of the types of profiling and deals with the all important area of memory profiling

  • How to use the NetBeans profiler and the JProfiler for memory profiling
  • Explains the process of heap dump extraction using a variety of tools such as jmap, JVisual VM, Eclipse MAT, JProfiler etc
  • Guides us through the process of heap dump analysis using visual tools as well as via he OQL (Object Query Language)
  • Analyses the potential issues emerging from memory related roots

Chapter 9 – Tuning an Application’s Environment

After all the discussion and exploration about potential performance related issues, related profiling tools and possible remediation, the focus now shifts to Tuning. This chapter deals with application environment tuning is specific which is divided into distinct categories

  • Detailed exploration of JVM tuning including both HotSpot and JRockit
  • Deep dive into application server tuning with GlassFish and Oracle Weblogic being the prime examples. Talks about tuning components such as EJB and Web containers, JDBC pools, thread pools etc
  • Exploration of HTTP server tuning with the help of Apache and Oracle HTTP server
  • Discusses tuning and optimization of operating system and hardware (capacity planning) related components

Chapter 10 – Designing High-performance Enterprise Applications

As the name clearly suggests, the chapter looks at the design aspects of enterprise applications. After having discussed different facets of performance tuning/monitoring/profiling, it makes sense to try and understand how to put certain best practices to practical use.

  • Explores different set of design decisions (app layer, security, framework etc) and their probable impact and introduces some common anti-patterns as well
  • Provides good insight/analysis of SOA and ROA based architectures and their performance aspects
  • Discusses the impact of data caching on performance in details and looks at topics like concurrency, data caching levels, how to assess caching performance etc
  • The chapter ends with an absorbing discussion on performance considerations from a Cloud deployment perspective

Chapter 11 – Performance Tuning Tips

This lesson provides general performance tuning tips, tricks and recipes for a variety of scenarios and use cases related to Java EE as well as SE

  • Deals with Java EE component specific performance secrets – EJB, JSF, JPA, web services etc
  • Explores general performance related topics from the Java SE space – I/O, Collections framework, synchronization etc and also peeks into the javap tool available in the JDK
  • The chapter ends with a discussion aobut database related performance tips ranging from choice of ORM library to executing bulk uploads in an optimized manner.

Chapter 12 – Tuning a Sample Application

This lesson is all about getting our hands dirty and applying the concepts learnt in the book in order to tune a real-world application

  • Introduces the sample application, and sets up an assessment plan
  • Guides us through the profiling process using previously described techniques such as CPU Time, memory profile etc
  • Deep dive into analysis of performance issues detected by the profiling process and resolution of each of those issues
  • Coverage of the testing process to assert performance improvements post issue resolutions



Performance Tuning is not an easy topic to discuss or write a book about. Although it is based upon reasoning and science, more often than not, it is triggered due to unprecedented scenarios.

  • The author covers a vast landscape in general – from depths of the Java Platform basics, JVM to app server tuning, Databases and straight on to the Cloud !
  • In general, the book is applicable to wide variety of audience, but the day-to-day/ traditional Java developers stand to reap maximum benefit out of this book
  • The sample application tuning exercise is a great addition to the book. Again, performance tuning is not an easy thing to discuss and convey and setting up a application for hands on practice needs is indeed priceless
  • Leverages sample code, examples and pictorial representations in an effective manner.


Note: While most of the aspects of the book are great, but there are certain areas in the book where the grammar and overall English could have been better. Personally, it did not prove to be a hindrance for me, but can be improved.


Where can you grab the book?

A book this versatile and multi-faceted should not be missed – especially when it deals with Performance Tuning !

Visit the PacktPub web site to get your copy!!

Happy Reading :-)

Posted in Books, Java, Java EE | Tagged , , , , , | Leave a comment

A closer look at Oracle IDM Auditing

Reporting is a vital functionality in any product which deals with sensitive information. Same applies to Identity & Access Management tools. Oracle IDM’s Auditing module acts as a foundation for its OOTB Reporting capabilities. Let’s take a quick look at Auditing engine and how it facilitates the Reporting functionality within OIM

The use case presented here is simple – change to a user record in OIM.

What are the sequence of events which get triggered from an Audit perspective?

This is best explained by a diagram. I came up with the figure below in an attempt to better articulate the process.



Although the diagram is self explanatory, a theoretical translation of the same is not going to harm us! :-)

  • The updated/created user record gets pushed into the USR table (stores the user information) – Its a normal process by which the information gets recorded in the OIM Database
  • The information is further propagated by the OIM Auditing engine (as a part of core back end server logic) and it initiates a transaction
  • The Audit Engine inserts a new entry in the AUD_JMS table as a part of the audit transaction completion. The AUD_JMS table is nothing but a staging table
  • The Issue Audit Messages scheduled job picks up the Audit messages in the AUD_JMS table and submits the key to the oimAuditQueue JMS queue.
  • The MDB corresponding to the queue initiates the Audit data processing – the data is seeded into the UPA table. This data is in the form of XML. These are snapshots of the user profile at the instant when the user record was actually modified/created. The UPA table also stores the delta (changes to the profile)
  • Finally, the Post processors of the Audit engine pick up the XML snapshots from the central UPA table and store them in specific audit tables (in a de-normalized format) like UPA_USR, UPA_USR_FIELDS, UPA_RESOURCE, UPA_UD_FORMS etc
  • These tables serve as the primary source of information for the Reporting module. If you have ever worked on the OIM Reporting module, I am sure you can relate to the Data Sources which you configure on your BI Publisher instance – these are for executing direct queries on the above mentioned Audit tables for its data.

That’s pretty much it ! This was not a coverage of the entire Audit module in OIM, but a preview of HOW the process is orchestrated on a high level.

Thanks for reading! :-)

Posted in Oracle Identity Governance, Oracle Identity Manager | Tagged , , , , , , , | Leave a comment

Java EE: Asynchronous constructs and capabilities



Java EE has a number of APIs and constructs to support Asynchronous execution. This is vital from a scalability and performance stand point.

Let us assume 2 modules which are interacting with each other. When moduleA (the sender) sends a message to moduleB (the receiver) in a Synchronous fashion, the communication takes place in the context of a Single thread i.e. the thread which initiated the communication from moduleA is blocked until moduleB responds back.

This was a generic statement but can be extended to the context of a simple Java methods interacting with each other – in this case, a synchronous call from methodA to methodB would execute in the same thread which would be blocked until methodB returns or throws an exception

Why do we need Asynchronous behavior in Java EE based applications?

We can further extrapolate this point to the Java EE world – be it inter server communication e.g. between web tier and EJB tier (servlets and EJBs) or a typical client server interaction – a browser interacting with a RESTful end point, Servlets etc – the server thread which responds to a client request always blocks until the server component responds back.

Here is where Asynchronous execution comes into play – if the server thread processing the client request can be released/suspended and the actual business logic is executed in a separate thread (different than that of the original one), performance and scalability can be improved immensely ! E.g. if a HTTP listener thread allocated to listen to client requests is released immediately, then it is free to attend to requests from other clients and the business logic can be executed in a separate container thread which can then return the response via appropriate methods such as java.util.concurrent.Future object or via call back handlers registered by the client. Think from an end user perspective – responsiveness matters a lot!

Dive In: Async constructs and APIs in Java EE

Let’s take a look at few of the Async related features (APIs) in Java EE. This is not an exhaustive list – but should be a good starting point.

Different Java EE specs have their typical ways and APIs to facilitate Async capabilities. Let’s explore the below Java EE specifications

  • JAX-RS 2.0 (Java EE 7)
  • Websocket 1.0 (Java EE 7)
  • Concurrency Utilities 1.0 (Java EE 7)
  • EJB 3.1 (Java EE 6)
  • Servlet 3.0 (Java EE 6)

Note: The code presented below is in a snippet form (for obvious reasons). The complete samples can be accessed here 


JAX-RS 2.0

Async processing of requests is a new feature in 2.0 edition of JAX-RS (new in Java EE 7). In order to execute an aysnc request using JAX-RS APIs, one needs to inject a reference to a javax.ws.rs.container.AsyncResponse interface in the JAX-RS resource method itself. This parameter puts the request execution in async mode and the method proceeds with its execution. The resume method on the AsynResponse object needs to be called from within a separate thread after the business logic execution is complete. One can leverage the Java EE concurrency utility features (discussed later) such as the javax.enterprise.concurrent.ManagedExecutorService in order to encapsulate the business logic as a Runnable object and submitting it to the container’s executor service which takes care of the rest. No need to spawn un-managed, isolated threads on your own


    public void asyncMethod(@Suspended AsyncResponse resp, @PathParam("id") String input) {

        System.out.println("Entered MyAsyncRESTResource/asyncMethod() executing in thread: "+ Thread.currentThread().getName());
                () -> {
                    System.out.println("Entered Async zone executing in thread: "+ Thread.currentThread().getName());
                    System.out.println("Simulating long running op via Thread sleep() started on "+ new Date().toString());
                    try {
                    } catch (InterruptedException ex) {
                        Logger.getLogger(MyAsyncRESTResource.class.getName()).log(Level.SEVERE, null, ex);
                    System.out.println("Completed Long running op on "+new Date().toString());
                    System.out.println("Exiting Async zone executing in thread: "+ Thread.currentThread().getName());

                    //creating a dummy instance of our model class (Student)

                    Student stud = new Student(input, "Abhishek", "Apr-08-1987");

        System.out.println("Exit MyAsyncRESTResource/asyncMethod() and returned thread "+Thread.currentThread().getName()+" back to thread pool");

The JAX-RS Client API also has asynchronous capabilities but they have not been discussed in the post. They are definitely worth a look!

Websocket 1.0

The Websocket API is a brand new addition to the Java EE arsenal (introduced in Java EE 7). It facilitates bi-directional (both server and client initiated) communication which is also full duplex in nature (either the client or server can send messages to each other at any time).

In order to send async messages using the Websocket API, one needs to use the getAsyncRemote method available on the javax.websocket.Session interface. Internally, this is nothing but an instance of the nested interface of the javax.websocket.RemoteEnpoint – javax.websocket.RemoteEnpoint.Async. Calling the regular sendXXX methods on this would result in the sending process being executed in a separate thread. This is particularly useful when you consider exchange of large messages or handling large numbers of websocket clients to whom the messages need to be sent. The method wither returns a java.util.concurrent.Future object or one can register a callback in the form of a javax.websocket.SendHandler interface implementation

  public void sendMsg(@Observes Stock stock) {
        System.out.println("Message receieved by MessageObserver --> "+ stock);
        System.out.println("peers.size() --> "+ peers.size());
        peers.stream().forEach((aPeer) -> {

                            aPeer.getAsyncRemote().sendText(stock.toString(), (result) -> {
                System.out.println("Message Sent? " + result.isOK());
                System.out.println("Thread : " + Thread.currentThread().getName());


Concurrency Utilities 1.0

The Java EE Concurrency Utilities is another great addition to Java EE 7. It provides a standard way of spawning threads – the good part is that these are container managed and not just isolated/orphan threads about which the container has no contextual information.

In general, the Concurrency Utilities 1.0 provide a few standard constructs for execution of asynchronous tasks in separate threads. These are as follows – javax.enterprise.concurrent.ManagedExecutorService and javax.enterprise.concurrent.ManagedScheduledExecutorService.

In order to start a new task in a separate thread, one can use the ManagedExecutorService interface to submit a Runnable. In addition to implementing the Runnable interface, a class can also implement the javax.enterprise.concurrent.ManagedTask interface and provide a  javax.enterprise.concurrent.ManagedTaskListener implementation in order to listen to life  cycle changes to the task submitted via the ManagedExecutorService

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("Enter AConcurrencyUtilsExample/doGet executing in thread "+ Thread.currentThread().getName());
        System.out.println("initiating task . . . ");
        mes.execute(new AManagedTask());
        System.out.println("Exit AConcurrencyUtilsExample/doGet and returning thread "+ Thread.currentThread().getName() +" back to pool");

Servlet 3.0

Asynchronous HTTP was introduced in Servlet 3.0 (part of Java EE 6) which basically provided the capability to execute the request in separate thread and suspend the original thread which handled the client invocation.

The key player here is the javax.servlet.AsyncContext interface. In order to initiate asynchronous processing, the startAsync method of the java.servlet.ServletRequest interface is called. In order to execute the core logic, a java.lang.Runnable object needs to be submitted to the start method of the AsyncContext interface. One can choose to attach a listener by implementing the javax.servlet.AsyncListener in order to receive callback notifications during specific times of the Async task execution


    public void doGet(HttpServletRequest req, HttpServletResponse resp) {

        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException ex) {
            Logger.getLogger(MyAsyncServlet.class.getName()).log(Level.SEVERE, null, ex);
        //System.out.println("entered doGet()");
        writer.println("ENTERING ... " + MyAsyncServlet.class.getSimpleName() + "/doGet()");
        writer.println("Executing in Thread: " + Thread.currentThread().getName());
        //step 1
        final AsyncContext asyncContext = req.startAsync();

        //step 2
        asyncContext.addListener(new CustomAsyncHandler(asyncContext));

        //step 3
                () -> {
                    PrintWriter logger = null;
                    try {
                        logger = asyncContext.getResponse().getWriter();
                    } catch (IOException ex) {
                        Logger.getLogger(MyAsyncServlet.class.getName()).log(Level.SEVERE, null, ex);

                    logger.println("Long running Aync task execution started : " + new Date().toString());

                    logger.println("Executing in Thread: " + Thread.currentThread().getName());
                    try {
                    } catch (InterruptedException e) {
                        Logger.getLogger(MyAsyncServlet.class.getName()).log(Level.SEVERE, null, e);

                    logger.println("Long task execution complete : " + new Date().toString());

                    logger.println("Calling complete() on AsyncContext");

                    //step 4

        writer.println("EXITING ... " + MyAsyncServlet.class.getSimpleName() + "/doGet() and returning initial thread back to the thread pool");


EJB 3.1

Typically, (prior to EJB 3.1) EJB Message Driven Beans were used to fulfill async related requirements. A MDB bean listens to messages sent to a javax.jms.Destination (a Queue or Topic) and executes the required business logic – this might be anything from sending an email to initiating an order processing task. The important thing to understand is that the client which sends the message to the Queue in the first place is unaware of the MDB (decoupled) and does not have to wait/remain blocked until the end of the job (email receipt or order processing confirmation)

EJB 3.1 (part of Java EE 6) introduced the javax.ejb.Asynchronous annotation. This can be placed on a EJB Session bean (Stateless, Stateful or Singleton) class (makes all the methods Asynchronous) or at the method level itself – in case fine grained control is needed. A method with the @Asynchronous annotation can either return void (fire and forget) or an instance of java.util.concurrent.Future if the async method result needs to be tracked – this can be done by calling the Future.get() – the thing to note is that the get method itself is blocking in nature

        public Future<String> asyncEJB2(){

        System.out.println("Entered MyAsyncEJB/asyncEJB2()");
       System.out.println("MyAsyncEJB/asyncEJB2() Executing in thread: "+ Thread.currentThread().getName());
        System.out.println("Pretending as if MyAsyncEJB/asyncEJB2() is doing something !");
        try {
        } catch (InterruptedException ex) {
            java.util.logging.Logger.getLogger(MyAsyncEJB.class.getName()).log(Level.SEVERE, null, ex);

        System.out.println("Exiting MyAsyncEJB/asyncEJB2()");
        return new AsyncResult("Finished Executing on "+ new Date().toString());



This was a rather brief preview of Java EE capabilities. These APIs and specifications are functionally rich and it is hard cover all of them via a blog post :-) I hope this piques your interest and gives you a starting point to explore further.

Cheers! :-)

Posted in Java, Java EE | Tagged , , , , , , , , , | Leave a comment

New in JAX-RS 2.0 – @BeanParam annotation

JAX-RS is awesome to say the least and one of my favorites! Why?

  • Feature rich
  • Intuitive (hence the learning curve is not as steep)
  • Easy-to-use and develop with
  • Has great RIs – Jersey, RestEasy etc

There are enough JAX-RS fans out there who can add to this! ;-)

JAX-RS 2.0 is the latest version of the JSR 311 specification and it was released along with Java EE 7.

Life without @BeanParam

Before JAX-RS 2.0, in order to pass/inject information from an HTTP request into JAX-RS resource implementation methods, one could

1. Include multiple method arguments annotated with @FormParam, @PathParam, @QueryParam etc





2. Or, have a model class backed by JAXB/JSON or a custom MessageBodyReader implementation for JAX-RS Provider to be able to unmarshall the HTTP message body to a Java object – read more about this in one of my previous posts






This means that something like a HTML5 based client would need to extract the FORM input, convert it into JSON or XML payload and then POST it over the wire.

Simplification in JAX-RS 2.0

This process has been simplified by introduction of the @BeanParam annotation. It helps inject custom value/domain/model objects into fields or method parameters of JAX-RS resource classes.

In case you want to refer to the code (pretty simple) or download the example/run it yourself, here is the GitHub link

All we need to do is, annotate the fields of the model (POJO) class with the injection annotations that already exist i.e. @PathParam, @QueryParam, @HeaderParam, @MatrixParam etc – basically any of the @xxxParam metadata types and



Make sure that we include the @BeanParam annotation while injecting a reference variable of this POJO (only on METHOD, PARAMETER or FIELD).


JAX-RS provider automatically constructs and injects an instance of your domain object which you can now use within your methods.

Just fill in the form information and POST it !





That’s it. . . Short and Sweet :-)

Keep Coding !

Posted in Java EE | Tagged , , , , , | Leave a comment

Oracle IDM R2 PS2 : Rich Diagnostics



feature-img2 feature-img1





Oracle IDM R2 PS2 provides some really efficient troubleshooting, monitoring and diagnostic features. This post will provide a quick overview of the same and delve into using one such feature to resolve a practical issue.

New Diagnostic Features: Overview

1. Orchestration diagnostics – The EM console can be used to drill down into the Orchestration related details of events within OIM

  •      A Dashboard to view recent operations and events
  • Info regarding ALL the event handlers attached to a particular operation – including  CUSTOM developed. No more digging into XMLs form MDS !
  • Powerful search features for all Operations (search by Operation Type, Operation ID etc)


2. Dynamic Monitoring Service (DMS) is an Oracle FMW component which enables performance tracking of various OIM modules and services such as scheduled tasks, event handlers, platform resources etc. One can export DMS metrics for detailed introspection as well

3. Reconciliation Profile validation

  •      Validate Recon profiles via MBeans via EM console – great for debugging issues
  •      Also provides reconciliation tables related indices which can help compare Database tuning as per documented mandates

A detailed explanation of each of these features is difficult to cover in a single post – skipping this for a future blog post (series). For now, let us explore a real world use case where such diagnostic capability can be used

I happened to come across a particular issue and resolved it with the help one of the many OIM PS2 diagnostic features. This one happened to be related to OIM Reconciliation Profiles.

The problem statement

  • Reconciliation job execution was not resulting in event creation.
  • The server console logs pointed to a SAX parsing exception.


Note: Whenever I see an XML parsing (SAX or DOM) exception in context of reconciliation, the brain invariably gravitates towards the Reconciliation Profile XML – yes. It’s a boon in general, but a curse because it has a tendency to get corrupted (because of no apparent reason).

The investigation

Time to use the new Reconciliation Profile validation diagnostic feature in PS2 (mentioned above) which enables us to validate and detect errors in the OIM Reconciliation Profile. It does so by exposing this service as an MBean. Sweet !! :-)

So how to go about this?

1. Log into EM console and take up the route shown in the snapshot below (yes, a picture is worth a thousand words and 10 minutes of writing something which can be easily portrayed via a visual medium!)


2. The next obvious step was to export the Recon profile XML itself in order to further drill down on matchingRule element (since there can be multiple such elements and the error indicates that one of them might be empty – hence the schema violation error resulting in a parsing error)

Exporting the recon profile XML via EM console

Note: This is not a diagnostic feature as such or a new functionality. This is present since OIM 11g R1 era

No need to execute manual processes – use the EM GUI to get the job done fast. Follow the snapshots



Finally – click on the Invoke button and you should have the profile exported to the location mentioned above

Note: If required, you can easily change/modify the XML and use the importMetadata operation of the same MBean to import with a single click (try it out)

The profile was exported in order to investigate it further. Let’s see what was the issue was



So, finally it is evident as to which matchingRule tag was empty.


Well, it all boiled down to a missing configuration in the Connector artifact – missing KEY field configuration for the child field (in the Process Definition).

Take away point

OIM is a feature rich product. Hence, things can get complicated at times and errors can get hard to debug. We saw how easy it was to drill down to the cause of the error and ultimately fix it

Why/How did this happen? That was not really the point of this post. In case you are inquisitive, looks like this is a bug in the connector ! ;-) That’s for a later post – maybe after further introspection


  • Include the KEY field config for child field in Process Definition
  • Recreate the Recon Profile
  • Validate the same via EM console (already explained)
  • Move on with your life ! ;-)

Remember – bugs/errors/issues are an opportunity for us to learn and doscover something new. Software can never be perfect in a single go. Be patient, try to diagnose, know your tools, know how to use them – if there are no tools, just build one and blog about it !! ;-)

Until then. . . Cheers ! ! !

Posted in Oracle Identity Governance, Oracle Identity Manager | Tagged , , , , , , , | Leave a comment

Jersey SSE capability in Glass Fish 4.0.1

jerseylogo    sse




Glass Fish bundles different Reference Implementations for various Java EE specifications e.g. Weld for CDI, Mojarra for JSF, Tyrus for WebSocket, Jersey for JAX-RS. Glass Fish 4.0.1 is in the pipeline and slated to cover updates for many of the components/modules which both include new features and bug fixes of course.

Server Sent Events feature in Jersey will be supported with Glass Fish 4.0.1. Let’s try and test out this feature

  1. Download the latest Glass Fish build from here

12. Unzip the contents of the ZIP installer and configure the same in your IDE ( I am using NetBeans ). Note: I am using using JDK 8. Remember to configure Glass Fish to use the same









3. Make sure you include the highlighted JARS ( below ) in your class path. These are available under GF_INSTALL/glassfish/modules





Now, the sample code for Jersey SSE feature demonstration. Its relatively simple.

There are three primary classes involved


It serves as a Producer of stream of events and is modeled as JAX-RS resource which emits events when invoked with a GET method. The returned event streams are abstracted in the form of org.glassfish.jersey.media.sse.EventOutput on to which a org.glassfish.jersey.media.sse.OutboundEvent object is written. The OutboundEvent consists of the actual event data.



This class serves as consumer of the events produced by the AResource.java class. This is a simple JAX-RS client which sends a GET request to the published JAX-RS resource, reads the org.glassfish.jersey.client.ChunkedInput and further extracts the actual event data from org.glassfish.jersey.media.sse.InboundEvent instance



As commonly the case with JAX-RS, this serves as bootstrap class


To test the SSE functionality from server ( producer ) to client ( consumer ), deploy your application and just access the Servlet on http://you_gfish_ip:port/JerseySSE/SSETest. You should see the following logs



About the FishCAT – Glass Fish Community Acceptance Testing program. Everyone is welcome to participate!

More on Jersey and Server Sent Events here.

This was a rather quick one.. Not bad ! Now you have time to go and do something more useful ;-)


Posted in Java, Java EE | Tagged , , , , , , , , | Leave a comment

Gearing up for JavaOne 2014 !

Hold that thought ! Yeah.. I wish I was presenting at Java One 2014 – but I am only worthy of doing that in my dreams right now ;-)

But nothing is stopping me from following Java One and tracking sessions/talks about my favorite topics. I am hoping Oracle would make the 2014 talks available online for mortals like us just like it did for the 2013 edition

I have already made my list of talks ( see below ) which I am going to pounce upon ( once they are available ) . . . Have You ? :-)

Lessons Learned from Real-World Deployments of Java EE 7 – Arun Gupta talks dissects live Java EE 7 applications and shares his thoughts and learnings

50 EJB 3 Best Practices in 50 Minutes – need I say more… ?

eBay, Connecting Buyers and Sellers Globally via JavaServer Faces

Applied Domain-Driven Design Blueprints for Java EE – Have you been following and learning from the Cargo Tracker Java EE application already? You are going to love this talk by Reza and Vijay

JPA Gotchas and Best Practices: Lessons from Overstock.com – nothing like listening to a ‘real’ world example

RESTful Microservices – Never heard of this one! It’s about leveraging Jersey 2.0 to achieve what you haven’t until now ;-)

Java API for JSON Binding: Introduction and Update – Potential Java EE 8 candidate and JAXB’s better half !

Is Your Code Parallel-Ready? – Love hacking on Java 8 Stream API? Yes.. this one is for you!

Java EE Game Changers – Tomitribe’s David Blevins will talk about the journey from J2EE to Java EE 7, provide insights into Java EE 8 candidates and much more!

Programming with Streams in Java 8 – I don’t think I need to comment

Unorthodox Enterprise Practices – Thoughts on Java EE design choices with live coding.. By one of my favorites.. Adam Bien :-)

Inside the CERT Oracle Secure Coding Standard for Java

RESTing on Your Laurels Will Get You Pwned – When the rest of the world in going ga-ga about REST, this talk will attempt to look at the dark side and empower us with skills to mitigate REST related vulnerabilities

Java EE 7 Batch Processing in the Real World – another live coding session using Java EE 7 standards !

Scaling a Mobile Startup Through the Cloud: A True Story – The folks at CodenameOne reveal their secrets

The Anatomy of a Secure Web Application Using Java – developing and deploying secure Java EE web application in the cloud.. now who does not want to do that ?!

Dirty Data: Why XML and JSON Don’t Cut It and What You Can Do About It – I haven’t thought beyond XML and JSON, but apparently some guys have and you must listen to them!

API Design Checklist – no comments needed

Java EE 7 and Spring 4: A Shootout — I have been waiting for this !

The Path to CDI 2.0 – Antoine, the CDI guy at Red Hat talks about . . of course. . CDI ! This includes discussion about 1.1/1.2 along with what’s coming up in CDI 2.0

Five Keys for Securing Java Web Apps – looks like I am repeating myself here.. but too much security can never be bad.. right?

Java EE 7 Recipes – Yeah! cooked up by Josh Juneau

There is still time . . .  Pick and gear up for your favorite tracks. More details on the official JavaOne website

Until then.. Happy Learning! :-)

Posted in Java | Tagged , , , , | Leave a comment

Packt Publishing celebrates 10 years with a special $10 offer !



It has been 10 years since Packt Publishing embarked on its mission to deliver effective learning and information services to IT professionals. In that time, it has published over 2000 titles and helped projects become household names, awarding over $400,000 through its Open Source Project Royalty Scheme.

To celebrate this huge milestone, Packt is offering all of its eBooks and Videos at just $10 each ! – this promotion covers every title and customers can stock up on as many copies as they like until July 5th.

If you’ve already tried a Packt title in the past, you’ll know this is a great opportunity to explore what’s new and maintain your personal and professional development. If you’re new to Packt, then now is the time to try their extensive range – Within their 2000+ titles range, you’ll find the knowledge you really need , whether that’s specific learning on an emerging technology or the key skills to keep you ahead of the competition in more established tech fields.

Hurry up . . . Don’t blame me for not reminding you about the July 5th time line because that’s when the offer ends ! ;-)

Cheers ! ! !

Posted in Books, Knowledge | Tagged , , , | Leave a comment