Tuesday, 2 August 2011

How to write asynchronously executing code in Java

Performance critical system should try to use asynchronously executing code as much as possible for side-lined operations like entry to database for audit logging etc. 

1) Worker Threads: The main thread should continue whatever it is doing, and the task of making the database entry ( or anyother time consuming operation) should be left to a different worker thread.

2) Blocking Queue: The Operation of inserting records to database should be added in a queue or pipe which can then be picked by worker threads. Blocking queue will prevent the worker thread from continuously monitoring the Queue for new task. If Queue is empty then the worker threads will go in wait state.

3) Thread Pool of Worker Threads: For better efficiency thread pool should be used, because it saves the cost of creating and removing worker threads.

Java’s concurrent API provides ExecutorService class which represents an asynchronous execution mechanism which is capable of executing tasks in the background.


To test this code, you can make worker thread sleep for sometime and while the worker thread is sleeping, the execution of main thread should continue.

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.submit(new Runnable(){
         public void run() {
                  licDao.executeQuery("SQL query");
                            }});

To test this code, you can make the worker thread sleep for some time and see if the main thread has moved on.