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.
Implementation:
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.
Example 1:
Java
| // Java Program to illsutare Blocking methods  // Importing all input output classesimportjava.io.*;  // ClassclassGFG {     // main driver method   publicstaticvoidmain(String args[]) throwsFileNotFoundException, IOException      {     // Print statement     System.out.println("GFG");       intresult;     result = System.in.read();     Â     // Print statement     System.out.println("Geeks for Geeks");     }   } | 
GFG Geeks for Geeks
Example 2:
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.
Java
| // Java Program to illsutare Blocking methods  // Importing all input output classesimportjava.io.*;// Importing concurrent CountDownLatch class// from java.util packageimportjava.util.concurrent.CountDownLatch;  // ClassclassGFG {      // Main driver method    publicstaticvoidmain(String args[])        throwsInterruptedException    {        // Let us create task that is going to wait        // for five threads before it starts        CountDownLatch latch = newCountDownLatch(4);          // Creating threads of Person type        // Custom parameter inputs        Person p1 = newPerson(1500, latch, "PERSON-1");        Person p2 = newPerson(2500, latch, "PERSON-2");        Person p3 = newPerson(3500, latch, "PERSON-3");        Person p4 = newPerson(4500, latch, "PERSON-4");        Person p5 = newPerson(5500, latch, "PERSON-5");          // Starting the thread        // using the start() method        p1.start();        p2.start();        p3.start();        p4.start();        p5.start();          // Waiting for the four threads        // using the latch.await() method        latch.await();          // Main thread has started        System.out.println(Thread.currentThread().getName()                           + " has finished his work");    }}  // Class 2// Helper class extending Thread class// To represent threads for which the main thread waitsclassPerson extendsThread {    // Member variables of this class    privateintdelay;    privateCountDownLatch latch;      // Method of this class    publicPerson(intdelay, CountDownLatch latch,                  String name)    {        // super refers to parent class        super(name);          // This keyword refers to current object itself        this.delay = delay;        this.latch = latch;    }      @Overridepublicvoidrun()    {        // Try block to check for exceptions        try{            Thread.sleep(delay);            latch.countDown();              // Print the current thread by getting its name            // using the getName() method            // of whose work is completed            System.out.println(                Thread.currentThread().getName()                + " has finished his work");        }          // Catch block to handle the exception        catch(InterruptedException e) {            // Print the line number where exception occurred            // using the printStackTrace() method            e.printStackTrace();        }    }} | 
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
Â


 
                                    







