Open In App

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:

  1. InvokeAndWait(): Wait for the Event Dispatcher thread to execute code.
  2. InputStream.read(): It blocks until input data is available, throws an exception, or detects the end of the stream.
  3. ServerSocket.accept(): Listen to inbound Java socket connection and blocks until a connection has been made.
  4. 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:



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 Program to illsutare Blocking methods
 
// Importing all input output classes
import java.io.*;
 
// Class
class GFG {
 
   // main driver method
   public static void main(String args[]) throws FileNotFoundException, IOException 
 
   {
     // Print statement
     System.out.println("GFG");
 
     int result;
     result = System.in.read();
      
     // Print statement
     System.out.println("Geeks for Geeks");
 
   
 
}

Output
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 Program to illsutare Blocking methods
 
// Importing all input output classes
import java.io.*;
// Importing concurrent CountDownLatch class
// from java.util package
import java.util.concurrent.CountDownLatch;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String args[])
        throws InterruptedException
    {
        // Let us create task that is going to wait
        // for five threads before it starts
        CountDownLatch latch = new CountDownLatch(4);
 
        // Creating threads of Person type
        // Custom parameter inputs
        Person p1 = new Person(1500, latch, "PERSON-1");
        Person p2 = new Person(2500, latch, "PERSON-2");
        Person p3 = new Person(3500, latch, "PERSON-3");
        Person p4 = new Person(4500, latch, "PERSON-4");
        Person p5 = new Person(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 waits
class Person extends Thread {
    // Member variables of this class
    private int delay;
    private CountDownLatch latch;
 
    // Method of this class
    public Person(int delay, CountDownLatch latch,
                  String name)
    {
        // super refers to parent class
        super(name);
 
        // This keyword refers to current object itself
        this.delay = delay;
        this.latch = latch;
    }
 
    @Override public void run()
    {
        // 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();
        }
    }
}

Output
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

 


Article Tags :