Blocking Methods in Java
Blocking methods in java are the particular set of methods that block the thread until its operation is complete. So, they will have to block the current thread until the condition that fulfills their task is satisfied. Since, in nature, these methods are blocking so-called blocking methods. For example, the InputStream read() method blocks until all InputStream data has been completely read. Here are some of the most common Java blocking methods:
- InvokeAndWait(): Wait for the Event Dispatcher thread to execute code.
- InputStream.read(): It blocks until input data is available, throws an exception, or detects the end of the stream.
- ServerSocket.accept(): Listen to inbound Java socket connection and blocks until a connection has been made.
- CountDownLatch.await(): Cause the current thread to wait until the latch counts to zero unless the thread is interrupted.
There are several disadvantages of blocking methods:
- Blocking techniques pose a significant threat to system scalability. A classic blocking solution consists of ways to mitigate blocking, using multiple threads to serve multiple customers.
- Design is the most important aspect since even if a multi-threaded system cannot reach beyond a certain point, a poorly designed system can only support several hundred or thousands of threads because of the limited number of JVM threads.
Here in the below example, following the execution of the first print statement, the program will be blocked by a second print statement until some characters are entered in the console. Then click enter because read() blocks the method until some input is readable.
GFG Geeks for Geeks
Here in this example, CountDownLatch.await() is used when a thread needs to wait for other threads before starting its work. CountDown() method decreases count and wait() method blocks until count == 0.
PERSON-1 has finished his work PERSON-2 has finished his work PERSON-3 has finished his work PERSON-4 has finished his work main has finished his work PERSON-5 has finished his work
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.