There are methods in Java which want to execute the task assigned without relinquishing control to other thread. In that case they have to block the current thread in case the condition that fulfil their task is not satisfied.
A very relevant example of blocking methods, which most of you would have encountered is read() method of the InputStream class. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
Then there is accept() method of the ServerSocket class. This method listens for a connection to be made to this socket and accepts it and blocks until a connection is made.
Since this post is more about blocking methods from the Java multi-threading perspective so let's have some example from there.
- wait() method - Which will block the current thread until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
- sleep() method - Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
- join() method - Where the current thread is blocked until all the other threads finish.
- BlockingQueue and BlockingDeque interfaces - Starting Java 5 with the introduction of java.util.concurrent
package blocking data structures which implements these two interfaces
have been added. Some of the examples are
In these data structures put() and take() method are there -
- put(E e) - Inserts the specified element into this queue, which will block if the space is full.
- take() - Retrieves and removes element from the queue, waiting if necessary until an element becomes available.
Drawback of blocking methods
Though it is essential to block threads in order to have some synchronization on the execution order or the access on shared object but at the same time blocking threads may lead to suspension of multiple threads even waiting forever if not handled properly posing a serious threat to scalability and performance.
As example - If a thread holding the lock is waiting for some resource like I/O or delayed due to some other fault then other waiting threads will not make any progress.
Non-Blocking Data Structures
Java 5 has added many data structures in concurrency package that use non-blocking algorithm like atomic variables i.e. AtomicInteger, ConcurrentLinkedQueue or reduce the probability of blocking by using techniques like lock striping as used in ConcurrentHashMap.
Java NIO's non-blocking mode in which an I/O operation will never block and may transfer fewer bytes than were requested or possibly no bytes at all from the Channel.
That's all for this topic Blocking methods in Java Concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!
You may also like -