Friday, September 15, 2023

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

Blocking methods in Java are those methods that block the executing thread until their operation is finished. A famous example of the blocking method is the InputStream read() method which blocks until all data from InputStream has been read completely. A correct understanding of blocking methods is required if you are serious about Java programming especially in the early days because if not used carefully blocking method can freeze GUIs, hung your program, and become non-responsive for a 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 are Blocking methods in Java?

As I said Blocking methods are those which block the currently executing thread from further operation until the 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 the reading of the file is finished. 

Javadoc clearly mentions whether an API call is blocking or not but most java IO methods are blocking

If you have been doing GUI programming in Java using Swing then knowledge of blocking methods becomes even more important for you, because nobody likes freezing or nonresponsive GUI. methods like invokeAndWait are blocking in nature and should be used only when you are performing some operation on which the user should wait for the result.

In most simple terms blocking means, your code in the next line will not be executed because the Thread which is executing the blocking function is waiting for the method to return. here is a code example that helps 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.

What are Blocking methods in Java?


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 a number of thread JVM can support. 

Java5 addresses this issue by adding non-blocking and asynchronous alternative of blocking IO calls and those utilities can be used to write high performance
servers application in core Java.


Best practices while calling a blocking method in Java

Example of blocking method in JavaBlocking methods are for a purpose or may be due to the 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 the blocking method in Java

1. If you are writing a GUI application that may be in Swing never call the blocking method in the 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 that requires the user to wait then consider using invokeAndWait() for the 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 the blocking method. so if your blocking call doesn't return in the specified time period, consider aborting it and returning back but again this depends upon the scenario. 

if you are using Executor Framework for managing your worker threads, which is, by the way, recommended way then 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 the 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 conditions. 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 the 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 remains in any of blocking state e.g. WAITING, BLOCKED or TIMED_WAITING.

2. Some of the blocking methods 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. interrupt() method of Thread class can be used to interrupt 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


And lastly,  which blocking method have you used so far? wait or await()? or anything else?

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