Monday, February 6, 2012

What is blocking methods in Java and how do deal with it?

Blocking methods in Java are those method which block the executing thread until there operation finished. Famous
example of blocking method is InputStream read() method which blocks until all data from InputStream has been read
completely. Correct understanding of blocking methods are required if you are serious towards Java programming specially
in early days because if not used carefully blocking method can freeze GUIs, hung your program and become non responsive for longer duration of time. In this post we will see What is Blocking methods in Java, Examples of Blocking methods and Some best practices around blocking methods and how to use blocking methods in Java.

What is Blocking methods in Java

Example of blocking method in JavaAs I said Blocking methods are those which blocks the current executing thread from further operation until function returns. So if you have just one thread in your program e.g. main thread and you call any blocking method e.g. reading from InputStream, your program will be blocked until reading of file finished. Javadoc clearly mention whether an API call is blocking or not but most of  java IO methods are blocking. If you are doing GUI programming in Java using Swing than knowledge of blocking methods becomes even more important for you, because no body likes freezing or non responsive GUI. methods like invokeAndWait are blocking in nature and should be used only when you are performing some operation on which user should wait for result. In most simple terms blocking means your code in next line will not be executed because Thread which is executing blocking function is waiting for method to return. here is a code example which help you
to understand blocking calls:

public class BlcokingCallTest {

    public static void main(String args[]) throws FileNotFoundException, IOException  {
      System.out.println("Calling blocking method in Java");
      int input = System.in.read();
      System.out.println("Blocking method is finished");
    }  
}

In this code example after executing first print statement your program will be blocked and will not execute second print statement until you enter some characters in console and press enter because read() method blocks until some input is available for reading.

Examples of blocking methods in Java:

There are lots of blocking methods in Java API and good thing is that javadoc clearly informs about it and always mention whether a method call is blocking or not. In General methods related to reading or writing file, opening network connection, reading from Socket, updating GUI synchronously uses blocking call. here are some of most common methods in Java which are blocking in nature:

1) InputStream.read() which blocks until input data is available, an exception is thrown or end of Stream is detected.
2) ServerSocket.accept() which listens for incoming socket connection in Java and blocks until a connection is made.
3) InvokeAndWait() wait until code is executed from Event Dispatcher thread.


Disadvantages of blocking method:

Blocking methods poses significant threat to scalability of System. Imagine you are writing a client server application and you can only serve one client at a time because your code blocks. there is no way you can make use of that System and its not even using resources properly because you might have high speed CPU sitting idle waiting for something. Yes there are ways to mitigate blocking and using multiple threads for serving multiple clients is a classical solution of blocking call. Though most important aspect is design because a poorly designed system even if its multi-threaded can not scale beyond a point, if you are relying solely of number of Threads for scalability means it can not be more than few hundred or thousands since there is limit on number of thread JVM can support. Java5 addresses this issue by adding non blocking and asynchronous alternative of blocking IO calls and those utility can be used to write high performance
servers application in core Java.

Best practices while calling blocking method in Java:

Blocking methods are for a purpose or may be due to limitation of API but there are guidelines available in terms of common and best practices to deal with them. here I am listing some standard ways which I employ while using blocking method in Java

1) If you are writing GUI application may be in Swing never call blocking method in Event dispatcher thread or
in the event handler. for example if you are reading a file or opening a network connection when a button is clicked
don't do that on actionPerformed() method, instead just create another worker thread to do that job and return from
actionPerformed(). this will keep your GUI responsive, but again it depends upon design if the operation is something which requires user to wait than consider using invokeAndWait() for synchronous update.

2) Always let separate worker thread handles time consuming operations e.g. reading and writing to file, database or
socket.

3) Use timeout while calling blocking method. so if your blocking call doesn't return in specified time period, consider
aborting it and returning back but again this depends upon scenario. if you are using Executor Framework for managing
your worker threads, which is by the way recommended way than you can use Future object whose get() methods support timeout, but ensure that you properly terminate a blocking call.

4) Extension of first practices, don't call blocking methods on keyPressed() or paint() method which are supposed to
return as quickly as possible.

5) Use call-back functions to process result of a blocking call.

A word of caution:

Though multi-threading is a workaround of blocking method it poses its own risk like thread-safety and race condition.
Java 5 also provides better alternatives of blocking IO methods wrapped in java.nio package.

That's all on Blocking methods in Java and some of best practices to use while calling blocking functions. let's know
what is your experience while using blocking IO methods and what standard code practices you follow while using these
methods.


Important points:

1. If a Thread is blocked in a blocking method it remain in any of blocking state e.g. WAITING, BLOCKED or TIMED_WAITING.

2. Some of the blocking method throws checked InterrupptedException which indicates that they may allow cancel the task and return before completion like Thread.sleep() or BlockingQueue.put() or take() throws InterruptedException.

3. interupt() method of Thread class can be used to interuupt a thread blocked inside blocking operation, but this is mere
a request not guarantee and works most of the time.

Other Java tutorials you may like

1 comment :

Anonymous said...

Future.get() is another blocking method to add in your list. get() blocks until result is available to Future.

Post a Comment