In java blocking methods are those methods which blocks the executing thread until their operation finished. In most simple way blocking means your code in next line will not be executed because the current thread which is executing blocking method is waiting for some return from that method.
Most of java IO methods are blocking methods and read() method from InputStream class is one the most famous example of blocking method, which blocks until all input data from InputStream has been read completely. This method blocks until input data is available, an exception is thrown or the end of the stream is detected.
There are many blocking methods present in java APIs and javadoc clearly mention whether a method call is blocking or not. In most of the case methods related to reading or writing file, reading from socket, opening network connection, updating GUI synchronously uses blocking call.
Below are some of the most common methods in java which are blocking in nature:
- InputStream.read() – This method blocks until data is available, end of stream is detected or an exception is thrown.
- ServerSocket.accept() – This method listen for incoming socket connection and blocks until a connection is made.
- SwingUtilities.invokeAndWait(Runnable r) – This method wait until all pending AWT events get processed and run() method completes.
Other examples of blocking method in java are: wait(), sleep(), join() from multi-threading, put(E e) and take() method from Queue interface are also blocking in nature.