Wednesday, 29 July 2015

How to iterate a Hash map of arraylists of String in Java?

This program is about how to iterate a HashMap that contains arraylists of String.

In the code- In the method getMap() I have created 3 lists and stored them in the HashMap.
Though there are several ways to iterate over a HashMap, but here I have used the for-each loop for iterating the created hash map. Every Map.Entry object will be a key-value pair where value will be the array list stored with the given key. That's the list I am getting by using listEntry.getValue().
In the second for-each loop iterating over the list, retrieved using listEntry.getValue() and then printing the values that are in the list.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapLoop {

    public static void main(String[] args) {
        MapLoop mapLoop = new MapLoop();
        Map<String, List<String>> cityMap = mapLoop.getMap();
        int i = 0;
        // iterating over a map
        for(Map.Entry<String, List<String>> listEntry : cityMap.entrySet()){
            System.out.println("Iterating list number - " + ++i);
            // iterating over a list
            for(String cityName : listEntry.getValue()){
                System.out.println("City - " + cityName);
            }
        }
    }
    
    /**
     * A method to create a list and store it in a Map
     * @return
     */
    private Map<String, List<String>> getMap(){
        Map<String, List<String>> cityMap = new HashMap<String, List<String>>();
        // First List
        List<String> temp = new ArrayList<String>();  
        temp.add("Delhi");
        temp.add("Mumbai");
        // Putting first list in the map
        cityMap.put("1", temp);
        // Second List
        temp = new ArrayList<String>();  
        temp.add("Hyderabad");
        temp.add("Bangalore");
        // Putting second list in the map
        cityMap.put("2", temp);
        // Third List
        temp = new ArrayList<String>();
        temp.add("Kolkata");
        temp.add("Chennai");
        // Putting third list in the map
        cityMap.put("3", temp);
        return cityMap;
    }
}
Output
Iterating list number - 1
City - Delhi
City - Mumbai
Iterating list number - 2
City - Hyderabad
City - Bangalore
Iterating list number - 3
City - Kolkata
City - Chennai

That's all for this topic How to iterate a Hash map of arraylists of String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashMap internally works in Java
  2. How to loop/iterate an arraylist in Java
  3. How to loop through a map in Java
  4. Count total number of times each character appears in a String
  5. How to sort arraylist of custom objects in Java

You may also like -

>>>Go to Java Programs page

Tuesday, 28 July 2015

ThreadLocal Class in Java

In Java there is a class called ThreadLocal which provides another way of thread-safety apart from synchronization. Usually when we have multiple threads sharing an object we need to synchronize the critical section of the code in order to make it thread safe.

ThreadLocal class provides thread-local variables where each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Since each and every thread has its own copy of the object so explicit synchronization is not needed to provide thread safety.

One interesting point about ThreadLocal variable is the global access. Any thread local variable is global to the thread. It can be accessed anywhere from the thread. If, from a thread several methods residing in different classes are called, thread local variable will be visible to all those methods. There is no need to pass the thread local variable as a parameter.

At the same time any thread local variable is local to a thread. If there are 10 threads spawned all the 10 threads will have their own thread local variable. One thread can not access/modify other thread's Thread Local variables.

Thread safety using synchronization

Let's see it with the help of an example.

Since SimpleDateFormat is not thread safe so in multi-threaded environment it needs to be synchronized like this

public class DateFormatDemo {
    private DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    public Date convertStringToDate(String dateString) throws ParseException {
    Date result;
    synchronized(df) {
       result = df.parse(dateString);
    }
    return result;
    }  
}

We can do the same thing using ThreadLocal by storing separate instance of SimpleDateFormat for each thread. We'll do it a little later first let's see how thread local variable is created and what all methods are provided by ThreadLocal class.

Creating a thread local variable

private static final ThreadLocal<String> threadLocalVar = new ThreadLocal<String>();

Here I have created a ThreadLocal variable called threadLocalVar which will store a String value.

Setting and accessing the value

Once a thread local instance is created, its set method can be used to set a value -

threadLocalVar.set("This is a thread local variable");

get method is used to read the value, note that get method returns the value in the current thread's copy of this thread-local variable.

threadLocalVar.get();

Initial Value of a thread local variable

ThreadLocal class provides a method called initialValue() which can be used to provide initial value to a created ThreadLocal variable.

// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
    new ThreadLocal<Integer>() {
      @Override 
      protected Integer initialValue() {
         return nextId.getAndIncrement();
      }
};

Note that ThreadLocal class is modified in Java 8 and a new method withInitial is added to it with a general form -

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier)

Here Supplier is a functional interface with one method get() and using lambda expression implementation of this method can be provided. If we use withInitial method, what we did here -

private static final ThreadLocal<Integer> threadId =
    new ThreadLocal<Integer>() {
      @Override 
      protected Integer initialValue() {
         return nextId.getAndIncrement();
      }
};

Can be done like this -

 threadId = ThreadLocal.withInitial(()-> {return nextId.getAndIncrement();});

Now when we know what is a ThreadLocal class and how it can be used to create variables which are thread safe, let's see two use cases where it can be used.

  1. When we have a requirement to associate state with a thread (e.g., a user ID or Transaction ID). That usually happens with a web application that every request going to a servlet has a unique transactionID associated with it.

    Example code for this requirement

    // This class will provide a thread local variable which
    // will provide a unique ID for each thread
    class ThreadId {
        // Atomic integer containing the next thread ID to be assigned
        private static final AtomicInteger nextId = new AtomicInteger(0);
    
        // Thread local variable containing each thread's ID
        private static final ThreadLocal<Integer> threadId =
            ThreadLocal.<Integer>withInitial(()-> {return nextId.getAndIncrement();});
    
        // Returns the current thread's unique ID, assigning it if necessary
        public static int get() {
            return threadId.get();
        }
    }
    
    // In this class thread's run method is executed
    class MyClass implements Runnable{
          @Override
          public void run() {
            System.out.println("Thread " + Thread.currentThread().getName() + " Value - " +  ThreadId.get());
          }
    }
    
    public class ThreadLocalDemo {
        
        public static void main(String[] args) {
             MyClass mc1 = new MyClass();
             Thread thread1 = new Thread(mc1, "Thread-1");
             Thread thread2 = new Thread(mc1, "Thread-2");
             Thread thread3 = new Thread(mc1, "Thread-3");
             thread1.start();
             thread2.start();
             thread3.start();
        }
    
    }
    

    Output

    Thread Thread-1 Value - 0
    Thread Thread-2 Value - 1
    Thread Thread-3 Value - 2
    

    It can be seen how each thread has a unique ID.

  2. Another use case where ThreadLocal is useful is when we want to have a thread safe instance and we don't want to use synchronization as the performance cost with synchronization is more. One such case is when SimpleDateFormat is used. Since SimpleDateFormat is not thread safe so we have to provide mechanism to make it thread safe. We already saw in the beginning how we can synchronize it to achieve that. Now let's see an example how ThreadLocal can be used by storing separate instance of SimpleDateFormat for each thread.
    public class ThreadLocalDemo1 implements Runnable {
        // threadlocal variable is created
        private static final ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>(){
            @Override
            protected SimpleDateFormat initialValue(){
                System.out.println("Initializing SimpleDateFormat for - " + Thread.currentThread().getName() );
                return new SimpleDateFormat("dd/MM/yyyy");
            }
        };
                
        public static void main(String[] args) {
            ThreadLocalDemo1 td = new ThreadLocalDemo1();
            // Two threads are created
            Thread t1 = new Thread(td, "Thread-1");
            Thread t2 = new Thread(td, "Thread-2");
            t1.start();
            t2.start();
        }
    
        @Override
        public void run() {
            System.out.println("Thread run execution started for " + Thread.currentThread().getName());
            System.out.println("Date formatter pattern is  " + dateFormat.get().toPattern());
            System.out.println("Formatted date is " + dateFormat.get().format(new Date()));
        } 
    
    }
    

    Output

    Thread run execution started for Thread-2
    Thread run execution started for Thread-1
    Initializing SimpleDateFormat for - Thread-2
    Initializing SimpleDateFormat for - Thread-1
    Date formatter pattern is  dd/MM/yyyy
    Date formatter pattern is  dd/MM/yyyy
    Formatted date is 26/07/2015
    Formatted date is 26/07/2015
    

    If you notice here SimpleDateFormat instance is created and initialized for each thread.

Points to note

  1. Thread Local provided another alternative to thread safety, apart from synchronization.
  2. With thread local each and every thread has its own thread local variable. One thread cannot access/modify other thread's Thread Local variables.
  3. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.

That's all for this topic Thread Local Class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference between yield and sleep
  2. What if run() method called directly instead of start() method
  3. Can we start the same thread twice in Java
  4. Race condition in Java multi-threading
  5. Synchronization in Java multithreading
  6. Java Multi-threading interview questions

You may also like -

Monday, 27 July 2015

Deadlock in Java multithreading

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. To describe it in a simple manner let's assume there are two threads Thread-1 and Thread-2 and two objects obj1 and obj2. Thread-1 already holds a lock on obj1 and for further processing it needs a lock on obj2. At the same time Thread-2 holds a lock on obj2 and wants a lock on obj1. In that kind of scenario both threads will be waiting for each other forever to release lock they are already holding thus creating a deadlock.

deadlock in java

Deadlock in Java

Deadlock in a multi-threading environment may happen in case

  • One synchronized method is called from another synchronized method.
  • If there are nested synchronized blocks.
Let’s see example code for these scenarios –

Calling one synchronized method from other

public class DeadLockDemo {
 
 private final String name;
 
 public DeadLockDemo(String name){
  this.name = name;
 }
 public String getName() {
  return this.name;
        }
  
 public synchronized void call(DeadLockDemo caller){
  System.out.println(this.getName() + " has asked to call me " + caller.getName());
  try {
   // Introducing some delay
   Thread.sleep(100);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  //System.out.println("" + Thread.currentThread().getName() );
  caller.callMe(this);
 }
 
 
 public synchronized void callMe(DeadLockDemo caller){
  System.out.println(this.getName() + " has called me " + caller.getName());
 }
 
 public static void main(String[] args) {
     DeadLockDemo caller1 = new DeadLockDemo("caller-1");
     DeadLockDemo caller2 = new DeadLockDemo("caller-2");
     // Thread 1   
     new Thread(new Runnable() {
                public void run() { caller1.call(caller2); }
            }).start();
     //Thread 2  
            new Thread(new Runnable() {
                public void run() { caller2.call(caller1); }
            }).start();

 }

}

Output

caller-1 has asked to call me caller-2
caller-2 has asked to call me caller-1

This code will result in a deadlock for the two created threads, if you are executing this program you'll have to stop the program forcefully.
Here we are creating 2 objects of class DeadLockDemo caller1 and caller2. Then call() method is called with those objects in to separate threads. As you already know that if you are using synchronized instance methods then the thread will have exclusive lock one per instance.
So both threads will enter the call() method one using the lock of caller1 object and another using the lock of caller2 object. Within call() method there is another call to a synchronized method callMe(), notice that the thread which has lock on object caller1 will have to get a lock on object caller2 to call this method. Whereas the thread which has lock on object caller2 will have to get a lock on object caller1 to call this method. But the lock on object caller1 and caller2 are already held by respective threads causing the threads to wait for each other to release those locks. This will lead to a deadlock and callMe() method will never be called.

nested synchronized block

class Test{
    private final String name;
    public Test(String name){
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
}

class ThreadA implements Runnable{
    private Test test1;
    private Test test2;
    ThreadA(Test test1, Test test2){
        this.test1 = test1;
        this.test2 = test2;
    }
    @Override
    public void run() {
        synchronized(test1){
            System.out.println("" + test1.getName());
            synchronized(test2){
                System.out.println("Reached here");
            }
        }
        
    }
    
}

class ThreadB implements Runnable{

    private Test test1;
    private Test test2;
    ThreadB(Test test1, Test test2){
        this.test1 = test1;
        this.test2 = test2;
    }
    @Override
    public void run() {
        synchronized(test2){
            System.out.println("" + test2.getName());
            synchronized(test1){
                System.out.println("Reached here");
            }
        }   
    }
}
public class DeadLockDemo1{

    public static void main(String[] args) {
        Test test1 = new Test("Test-1");
        Test test2 = new Test("Test-2");
        Thread t1 = new Thread(new ThreadA(test1, test2));
        Thread t2 = new Thread(new ThreadB(test1, test2));
        t1.start();
        
        t2.start();
    }
}

Output

Test-1
Test-2

As can be seen from the output that both the threads are locked while trying to acquire lock of another object. So "Reached here" never get printed. Thread t1 will start execution of run method in ThreadA and acquire lock on object test1 and then try to acquire lock on object test2. Meanwhile Thread t2 will start execution of run method in ThreadB and acquire lock on object test2 and then try to acquire lock on object test1. So both threads are trying to acquire a lock which is already held by another thread. Thus causing a deadlock.

How to avoid deadlocks

  • Avoiding inconsistent lock ordering - Code given in example 2 shows how, order in which locks are acquired can result in deadlock. Fortunately this kind of deadlock is easy to avoid. If we change the order in such a way that each method acquires both of the locks in the same order, two or more threads executing these methods may not cause deadlock.
    class ThreadA implements Runnable{
        private Test test1;
        private Test test2;
        ThreadA(Test test1, Test test2){
            this.test1 = test1;
            this.test2 = test2;
        }
        @Override
        public void run() {
            synchronized(test1){
                System.out.println("" + test1.getName());
                synchronized(test2){
                    System.out.println("Reached here");
                }
            }
            
        }
        
    }
    
    class ThreadB implements Runnable{
    
        private Test test1;
        private Test test2;
        ThreadB(Test test1, Test test2){
            this.test1 = test1;
            this.test2 = test2;
        }
        @Override
        public void run() {
            synchronized(test1){
                System.out.println("" + test2.getName());
                synchronized(test2){
                    System.out.println("Reached here");
                }
            }   
        }
    }
    

    If you notice in both the threads, order in which locks are acquired, is same now.

  • Try to use synchronized blocks - It is always advisable to use synchronized blocks rather than synchronizing the whole method. Using synchronized block will result in the scope of synchronization reduced which means lock will be held for less time.In example 1 if we use synchronized block rather than synchronizing the whole call() method we may avoid the deadlock.

That's all for this topic Deadlock in Java multi-threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Thread states in Java multithreading
  2. What if run() method called directly instead of start() method
  3. Synchronization in Java multithreading
  4. Thread priorities in Java multithreading
  5. Race condition in Java multi-threading
  6. Java Multi-threading interview questions

You may also like -

Wednesday, 22 July 2015

Creating PDF from XML using Apache FOP

In this post I'll talk about how to create PDF files from XML using Apache FOP.

What is Apache FOP

Apache™ FOP (Formatting Objects Processor) is a print formatter driven by XSL formatting objects (XSL-FO) and an output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output.
FOP uses the standard XSL-FO file format as input, lays the content out into pages, then renders it to the requested output.
Read more about it here - https://xmlgraphics.apache.org/fop/

Steps for creating a PDF from XML

To produce a PDF file from a XML file, first step is that we need an XSLT stylesheet that converts the XML to XSL-FO. Created XSL-FO file is also an XML file which contains formatted objects.
The second step will be done by FOP when it reads the generated XSL-FO document and formats it to a PDF document.

How to get Apache FOP

Get the FOP download from here.
https://xmlgraphics.apache.org/fop/download.html

I have used fop-2.0 for this example code.
Needed jars (found in the lib and build directory in the fop download) -

  • Commons-io
  • Commons-logging
  • Xml-apis
  • Xmlgraphics-commons
  • Fop
  • Batik-all
  • Avalon-framework

Example code

XML I used for creating PDF
<?xml version="1.0"?>

<employees>
<companyname>ABC Inc.</companyname>
 <employee>
  <id>101</id>
  <name>Ram</name>
  <designation>Manager</designation>
 </employee>

 <employee>
  <id>102</id>
  <name>Prabhu</name>
  <designation>Executive</designation>
 </employee>

 <employee>
  <id>103</id>
  <name>John</name>
  <designation>Executive</designation>
 </employee>
</employees>

Stylesheet Used

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:fo="http://www.w3.org/1999/XSL/Format" exclude-result-prefixes="fo">
<xsl:template match="employees">
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
      <fo:layout-master-set>
        <fo:simple-page-master master-name="simpleA4" page-height="29.7cm" page-width="21cm" margin-top="2cm" margin-bottom="2cm" margin-left="2cm" margin-right="2cm">
          <fo:region-body/>
        </fo:simple-page-master>
      </fo:layout-master-set>
      <fo:page-sequence master-reference="simpleA4">
        <fo:flow flow-name="xsl-region-body">
          <fo:block font-size="16pt" font-weight="bold" space-after="5mm">Company Name: <xsl:value-of select="companyname"/>
          </fo:block>
          <fo:block font-size="10pt">
          <fo:table table-layout="fixed" width="100%" border-collapse="separate">    
            <fo:table-column column-width="4cm"/>
            <fo:table-column column-width="4cm"/>
            <fo:table-column column-width="5cm"/>
            <fo:table-body>
              <xsl:apply-templates select="employee"/>
            </fo:table-body>
          </fo:table>
          </fo:block>
        </fo:flow>
      </fo:page-sequence>
     </fo:root>
</xsl:template>
<xsl:template match="employee">
    <fo:table-row>   
     <xsl:if test="designation = 'Manager'">
            <xsl:attribute name="font-weight">bold</xsl:attribute>
      </xsl:if>
      <fo:table-cell>
        <fo:block>
          <xsl:value-of select="id"/>
        </fo:block>
      </fo:table-cell>
     
      <fo:table-cell>
        <fo:block>
          <xsl:value-of select="name"/>
        </fo:block>
      </fo:table-cell>   
      <fo:table-cell>
        <fo:block>
      <xsl:value-of select="designation"/>
        </fo:block>
      </fo:table-cell>
    </fo:table-row>
  </xsl:template>
</xsl:stylesheet>

If you see the XSL, first I am looking for the employees element to get the company Name and also there some formatting is done like how many columns are needed and what should be the width. Then I am looking for the employee element and printing the values, also some logic is there to print the field values in bold if the designation is manager.

Copying the output of PDF I got, that will make it easy to understand the XSL.

PDF from XML using Apache FOP

Java code

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;

public class FOPPdfDemo {

    public static void main(String[] args) {
        FOPPdfDemo fOPPdfDemo = new FOPPdfDemo();
        try {
            fOPPdfDemo.convertToPDF();
        } catch (FOPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    /**
     * Method that will convert the given XML to PDF 
     * @throws IOException
     * @throws FOPException
     * @throws TransformerException
     */
    public void convertToPDF()  throws IOException, FOPException, TransformerException {
        // the XSL FO file
        File xsltFile = new File("F:\\Temp\\template.xsl");
        // the XML file which provides the input
        StreamSource xmlSource = new StreamSource(new File("F:\\Temp\\Employees.xml"));
        // create an instance of fop factory
        FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
        // a user agent is needed for transformation
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        // Setup output
        OutputStream out;
        out = new java.io.FileOutputStream("F:\\Temp\\employee.pdf");
    
        try {
            // Construct fop with desired output format
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

            // Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));

            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Start XSLT transformation and FOP processing
            // That's where the XML is first transformed to XSL-FO and then 
            // PDF is created
            transformer.transform(xmlSource, res);
        } finally {
            out.close();
        }
    }
    
    /**
     * This method will convert the given XML to XSL-FO
     * @throws IOException
     * @throws FOPException
     * @throws TransformerException
     */
    public void convertToFO()  throws IOException, FOPException, TransformerException {
        // the XSL FO file
        File xsltFile = new File("F:\\Temp\\template.xsl");
        
        
        /*TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(new StreamSource("F:\\Temp\\template.xsl"));*/
        
        // the XML file which provides the input
        StreamSource xmlSource = new StreamSource(new File("F:\\Temp\\Employees.xml"));
        
        // a user agent is needed for transformation
        /*FOUserAgent foUserAgent = fopFactory.newFOUserAgent();*/
        // Setup output
        OutputStream out;
        
        out = new java.io.FileOutputStream("F:\\Temp\\temp.fo");
    
        try {
            // Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));

            // Resulting SAX events (the generated FO) must be piped through to FOP
            //Result res = new SAXResult(fop.getDefaultHandler());

            Result res = new StreamResult(out);

            //Start XSLT transformation and FOP processing
            transformer.transform(xmlSource, res);


            // Start XSLT transformation and FOP processing
            // That's where the XML is first transformed to XSL-FO and then 
            // PDF is created
            transformer.transform(xmlSource, res);
        } finally {
            out.close();
        }
    }

}

In the code there are two methods convertToPDF() and convertToFO(), convertToPDF() method is used to convert XML to PDF. convertToFO() method will create the XSL-FO from the XML using the XSLT. If you want to see the created FO which in turn is used to create PDF please call this method.

In case of web application if you want to provide PDF as a download add following lines with in the convertToPDF() method-

//Prepare response
response.setContentType("application/pdf");
response.setContentLength(out.size());

//Send content to Browser
response.getOutputStream().write(out.toByteArray());
response.getOutputStream().flush();

That's all for this topic Creating PDF from XML using Apache FOP. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to convert a file to byte array
  2. How to read file from the last line in Java
  3. How to add double quotes to a String
  4. Print odd-even numbers using threads and semaphore
  5. Unzipping files in Java

You may also like -

>>>Go to Java Programs page

Friday, 17 July 2015

How to read input from console in Java?

Here I am giving three ways to read input from console -

  • First way uses the InputStreamReader wrapped in a BufferedReader.
  • Second way uses the Scanner class from Java 5.
  • Third way uses the System.console which was introduced in Java 6.

In order to make it clear I am also providing a short description of the classes or fields used which is mainly taken from the java doc.

  1. System.in - in is a field in a System class. in is the "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
  2. InputStreamReader - An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. For top efficiency, consider wrapping an InputStreamReader within a BufferedReader.
  3. BufferedReader - Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
  4. Scanner - A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. nextLine() method of the Scanner class advances this scanner past the current line and returns the input that was skipped.
  5. console method - console method in System class whose general form is -
    public static Console console()
    Returns the unique Console object associated with the current Java virtual machine, if any.

A word of caution, if running the code from eclipse System.Console will throw null pointer exception.

Please follow this discussion to know more about this exception -
http://stackoverflow.com/questions/104254/java-io-console-support-in-eclipse-ide
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class ReadFromConsole {

    public static void main(String[] args) {
        // Using InputStreamReader
        System.out.println("Please enter user name : ");            
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s;
        try {            
            s = bufferRead.readLine();
            System.out.println(s);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        // Using Scanner 
        System.out.println("Please enter user name : ");
        Scanner scanIn = new Scanner(System.in);
        String scanInput = scanIn.nextLine();
        System.out.println(scanInput);
        scanIn.close();  
        
        //Using System.console()
        String username = System.console().readLine("Please enter user name : ");   
        System.out.println("You entered : " + username); 
    }
}

As already mentioned, if used from eclipse the console method will give the following error.
Console.readLine will give error if used from eclipse.

Exception in thread "main" java.lang.NullPointerException
 at org.netjs.examples.ReadFromConsole.main(ReadFromConsole.java:31)

That's all for this topic How to read input from console. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading file in Java using BufferedReader
  2. How to read file from the last line in Java
  3. How to find last modified date of a file in Java
  4. Zipping files in Java
  5. Reading delimited file in Java using Scanner

You may also like -

>>>Go to Java Programs page

Thursday, 16 July 2015

Difference between sleep and wait - Java Multi-threading

Difference between sleep and wait is a popular Java multi-threading interview question. It is another confusing question just like Difference between yield and sleep because functionality wise both sleep and wait look quite similar. When sleep method is called with a specified time currently executing thread goes in a TIMED_WAITING state. Same way when wait method is called on an object the thread currently holding the lock on that object goes in a waiting state (or TIMED_WAITING state depending upon which of the three wait methods is being called). Since both methods when called put the currently executing thread in a waiting state then what exactly is the difference between these two methods. So let's try to find out the differences.

  1. The very first difference is that sleep is defined as a static method in Thread class and operates on the currently executing thread. Whereas wait() method is in Object class and operates on the thread which is currently holding the lock on the object on which the wait method is called.
  2. Since wait method is supposed to release the lock on an object so it has to be called from a synchronized context (with in a synchronized method or synchronized block). If not called from a synchronized context will result in a IllegalMonitorStateException being thrown. With sleep method there is no such mandatory condition it doesn't need to be called from a synchronized context.
  3. Wait method will release the lock it holds on an object before going to waiting state which gives another thread a chance to enter the synchronized block. Sleep method if called from a synchronized block or method will not release the lock so another won't get a chance to enter the synchronized block. (See an example to show it here - Difference between yield and sleep)
  4. When wait() method is called upon an object the thread which is currently holding the lock on that object goes to waiting state and it changes state to runnable only when the notify or notifyAll method is called by some thread on the same object.
    There are overloaded wait() methods too
       public final void wait(long timeout) throws InterruptedException
       
    And
      public final void wait(long timeout, int nanos) throws InterruptedException
    
    which causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
    In case of sleep method thread changes state to runnable after the specified time is elapsed. As example Thread.sleep(4000); will make the currently executing thread to sleep for 4 seconds and when the specified time has elapsed thread is ready to run again. This sleep period can be terminated by interrupts.

An example of interrupt

 public class InterruptDemo extends Thread {
    @Override
    public void run(){  
        try {
            Thread.sleep(4000);
        } catch (InterruptedException Iexp) {
            System.out.println("Thread Interrupted exception "+ Iexp); 
        }
         
        System.out.println("thread after interruption...");  
    }  
    public static void main(String[] args) {        
        InterruptDemo thread1 = new InterruptDemo();
        thread1.start();
        thread1.interrupt();
    }
}

That's all for this topic Difference between sleep and wait. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Can we start the same thread twice in Java
  2. What if run() method called directly instead of start() method
  3. Synchronization in Java multithreading
  4. Race condition in Java multi-threading
  5. Deadlock in Java multi-threading
  6. Java Multi-threading interview questions

You may also like -

finalize method in Java

There may be a situation when an object will need to perform some action just before it is getting garbage collected. For example if an object is holding some non-java resources like file handle then it is better to make sure that these resources are closed before an object is destroyed because simply reclaiming the memory used by an object would not guarantee that the resources it held would be reclaimed.
For that purpose Java provides a mechanism called finalization through finalize() method. In finalize method we can provide the actions to release the resources before the object is destroyed.

When is finalize() method called

As we know that in Java object memory deallocation happens automatically through garbage collection. In Java, garbage collector is run by the run time environment periodically and it looks for the objects for which there are no existing references. finalize method for an object is executed just before it is garbage collected. But here lies the caveat According to Java language specification - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.6 The Java programming language does not specify how soon a finalizer will be invoked that's one reason why we should not rely solely on finalize() method to release resources.

According to Joshua Bloch in his book Effective Java, Item 7: Avoid Finalizers
"The promptness with which finalizers are executed is primarily a function of the garbage collection algorithm, which varies widely from JVM implementation to JVM implementation. The behavior of a program that depends on the promptness of finalizer execution may likewise vary. It is entirely possible that such a program will run perfectly on the JVM on which you test it and then fail miserably on the JVM favored by your most important customer."

General form of finalize method

finalize method is provided as a protected method in the Object class.

protected void finalize() throws Throwable

Just as a reminder the protected access modifier provides the access as - Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
Since all the classes have Object class as the super class either directly or indirectly so this method would be accessible to each and every class anyway so it makes sense to keep the access as protected.

How to use finalize method

The finalize method of class Object performs no special action; it simply returns normally. Any class which needs some functionality to be provided in finalize() method has to override this definition and provide the functionality. According to Java docs - The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded.

How to properly write a finalize() method

Like constructor chaining in Java there is no finalizer chaining so super class finalize method would not be called automatically. As example If there is class A which provides a finalize method, if Class A is extended by class B and class B overrides the finalize method then only Class B's finalize method will be called. Class A's finalize method would not be called automatically. Thus we need to explicitly call it using super -

protected void finalize() throws Throwable {
     try {
         // clean up
     } finally {
         super.finalize(); // call parent class’ finalize
     }
}

Example code for finalize method

Here is a simple example where I have created an object then set that object reference as null. Also called System.gc() to run garbage collector. Note you may not get the output in some of the runs as System.gc() is also more of a suggestion to the virtual machine to reclaim memory from unused objects it may not run as soon as System.gc() is called and the program may terminate not at all calling the finalize method.

public class FinalizeDemo {
    int i;
    FinalizeDemo(int num){
        this.i = num;
    }
    public static void main(String[] args) {
        // creating object
        FinalizeDemo finalizeDemo = new FinalizeDemo(10);
        Temp temp = new Temp();
        // setting object reference as null so it is 
        // eligible for garabge collection
        finalizeDemo = null;
        temp.doCalcualtion();
        // setting object reference as null so it is 
        // eligible for garabge collection
        temp = null;
        // Calling System.gc() to run garbage collector
        System.gc();        
    }
    
    @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("finalize method called for FinalizeDemo");
        }finally{        
            super.finalize();
        }
    }
    
}

class Temp{    
    public void doCalcualtion(){
        int i = 5;
        System.out.println("value of i is " + i);
    }
    @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("finalize method called for Temp");
        }finally{
            super.finalize();
        }
    }
}

Output

value of i is 5
finalize method called for Temp
finalize method called for FinalizeDemo

Though I have used System.gc here to some how make sure that finalize() method is indeed called but don't rely on it. To quote Joshua Bloch again "Don't be seduced by the methods System.gc and System.runFinalization. They may increase the odds of finalizers getting executed, but they don't guarantee it. The only methods that claim to guarantee finalization are System.runFinalizersOnExit and its evil twin, Runtime.runFinalizersOnExit. These methods are fatally flawed and have been deprecated."

When we can use finalize method

Though there are other better alternatives to clean up resources like a finally block or try-with-resources(ARM) available from Java 7. But to make sure, just as an extra safety measure, that resources are indeed closed before the object is destroyed finalize() method may be used. But be forewarned it does comes with a hit on performance.

Finalize method and exception handling

Any exception thrown by the finalize method while finalize method is executing causes the finalization of this object to be halted, but is otherwise ignored.

Points to Note

  1. Every class inherits the finalize() method from java.lang.Object.
  2. The finalize method is called by the garbage collector when it determines no more references to the object exist
  3. The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.
  4. If overridding finalize() it is a good programming practice to use a try-catch-finally statement and to always call super.finalize() as there is no concept of finalizer chaining.
  5. The finalize method is never invoked more than once by a Java virtual machine for any given object.

That's all for this topic finalize method in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. finally block in Java
  2. final in Java
  3. final Vs finally Vs finalize
  4. Constructor chaining in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Monday, 13 July 2015

Difference between yield and sleep - Java Multi-threading

Difference between yield and sleep is one question asked quite frequently in interviews. As both of the methods are related to pausing the currently executing thread so it does create some confusion. So let's see the difference between these 2 methods to have clarity over the usage.

Please keep in mind that both yield and sleep are static methods of the Thread class. When called both of these methods will work on the currently executing thread, not on any particular thread. As example if there are three threads running T1, T2 and T3. Calling Thread.sleep() or Thread.yield() will work on whichever thread is currently executing. You can't say T1.sleep() or T3.yield() to put T1 thread to sleep or T3 thread to yield.

Yield - A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint. The executing thread is suspended and the CPU is given to some other runnable thread. This thread will wait until the CPU becomes available again.Technically, in process scheduler's terminology, the executing thread is put back into the ready queue of the processor and waits for its next turn .
According to JavaDOC - http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#yield--
It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

Yield example

In this example code three threads are spawned. In the run method there is a loop which runs 3 times printing value of variable i. Currently executing thread is asked to yield when value of i is 1, that gives another thread to start execution.

public class YieldDemo {

    public static void main(String[] args) {
        YieldClass yc = new YieldClass();
        Thread thread1 = new Thread(yc, "Thread1");
        Thread thread2 = new Thread(yc, "Thread2");
        Thread thread3 = new Thread(yc, "Thread3");
        thread1.start();
        thread2.start();
        thread3.start();
        
        try {
            thread1.join();
         
            thread2.join();
            thread3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Execution finished");

    }

}

class YieldClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Yielding thread : "+ 
                         Thread.currentThread().getName());
                     Thread.yield();
                }
          }   
    }  
}

Output

Executing run for Thread - Thread1
Executing run for Thread - Thread2
i 0Thread- Thread1
i 0Thread- Thread2
i 1Thread- Thread1
i 1Thread- Thread2
Yielding thread : Thread1
Yielding thread : Thread2
Executing run for Thread - Thread3
i 0Thread- Thread3
i 1Thread- Thread3
Yielding thread : Thread3
i 2Thread- Thread1
i 2Thread- Thread2
i 2Thread- Thread3
Execution finished

It can be seen from the output how Thread 1 and Thread 2 are interleaving and they both are printing value of i as 0 and 1. At that point yield method is called that gives a chance to Thread 3 to start its execution.

Sleep - Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

Sleep Example

public class SleepDemo {

    public static void main(String[] args) {
    
            SleepClass yc = new SleepClass();
            Thread thread1 = new Thread(yc, "Thread1");
            Thread thread2 = new Thread(yc, "Thread2");
            Thread thread3 = new Thread(yc, "Thread3");
            thread1.start();
            thread2.start();
            thread3.start();
            
            try {
                thread1.join();
             
                thread2.join();
                thread3.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Execution finished");

        }



}

class SleepClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
        //synchronized(this){
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Going to sleep thread : "+ 
                         Thread.currentThread().getName());
                     try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        //}
    
        
    }
    
}

Output

Executing run for Thread - Thread1
Executing run for Thread - Thread2
i 0Thread- Thread1
i 0Thread- Thread2
i 1Thread- Thread1
i 1Thread- Thread2
Going to sleep thread : Thread1
Going to sleep thread : Thread2
Executing run for Thread - Thread3
i 0Thread- Thread3
i 1Thread- Thread3
Going to sleep thread : Thread3
i 2Thread- Thread2
i 2Thread- Thread1
i 2Thread- Thread3
Execution finished

Based on these descriptions of sleep and yield the difference between these 2 methods is a thread which has yielded may become eligible to run again as soon as it has yielded if there is no other thread with the same or more priority. Where as in case of sleep the thread will definitely go to sleep for the specified time (unless it is interrupted) and in the meantime another thread (of less or more priority) can start its execution.

Another important point to note here is while invoking both yield and sleep methods, thread doesn't have to give up the locks it is holding if called from the synchronized context, as in the case with wait method.

Yield with synchronized example

Here I am using the same code as above just kept the for loop inside a synchronized block.

public class YieldDemo {
    public static void main(String[] args) {
        YieldClass yc = new YieldClass();
        Thread thread1 = new Thread(yc, "Thread1");
        Thread thread2 = new Thread(yc, "Thread2");
        Thread thread3 = new Thread(yc, "Thread3");
        thread1.start();
        thread2.start();
        thread3.start();
        
        try {
            thread1.join();
         
            thread2.join();
            thread3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Execution finished");

    }

}

class YieldClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
        synchronized(this){
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Yielding thread : "+ 
                         Thread.currentThread().getName());
                     Thread.yield();
                }
            }
        }  
    }
    
}

Output

Executing run for Thread - Thread1
Executing run for Thread - Thread2
i 0Thread- Thread1
i 1Thread- Thread1
Yielding thread : Thread1
Executing run for Thread - Thread3
i 2Thread- Thread1
i 0Thread- Thread3
i 1Thread- Thread3
Yielding thread : Thread3
i 2Thread- Thread3
i 0Thread- Thread2
i 1Thread- Thread2
Yielding thread : Thread2
i 2Thread- Thread2
Execution finished

It can be seen how "Executing run for Thread" message is printed for both Thread-1 and Thread-2 but only Thread-1 enters the synchronized block. Thread-1 yields after value of i becomes 1. But again Thread-1 is executed as it is the thread currently holding the lock. Only after it releases the lock another thread starts its execution.

Same example with sleep

public class SleepDemo {

    public static void main(String[] args) {
    
            SleepClass yc = new SleepClass();
            Thread thread1 = new Thread(yc, "Thread1");
            Thread thread2 = new Thread(yc, "Thread2");
            Thread thread3 = new Thread(yc, "Thread3");
            thread1.start();
            thread2.start();
            thread3.start();
            
            try {
                thread1.join();
             
                thread2.join();
                thread3.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Execution finished");

        }



}

class SleepClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
        synchronized(this){
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Going to sleep thread : "+ 
                         Thread.currentThread().getName());
                     try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    
        
    }
    
}

Output

Executing run for Thread - Thread1
i 0Thread- Thread1
i 1Thread- Thread1
Going to sleep thread : Thread1
Executing run for Thread - Thread3
Executing run for Thread - Thread2
i 2Thread- Thread1
i 0Thread- Thread2
i 1Thread- Thread2
Going to sleep thread : Thread2
i 2Thread- Thread2
i 0Thread- Thread3
i 1Thread- Thread3
Going to sleep thread : Thread3
i 2Thread- Thread3
Execution finished

That's all for this topic Difference between yield and sleep. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What if run() method called directly instead of start() method
  2. Can we start the same thread twice in Java
  3. Creating thread in Java
  4. Synchronization in Java multithreading
  5. Race condition in Java multi-threading
  6. Java Multi-threading interview questions

You may also like -

Thursday, 9 July 2015

Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?

Why wait(), notify() and notifyAll() must be called inside a synchronized method or block is a very frequently asked Java multi-threading question. It is very closely related to another multi-threading question Why wait(), notify() and notifyAll() methods are in Object class?

There are few points we should be aware of before going into the reasons for why wait(), notify() and notifyAll() must be called inside a synchronized method or block.

  1. Every object created in Java has one associated monitor (mutually exclusive lock). Only one thread can own a monitor at any given time.
  2. For achieving synchronization in Java this monitor is used. When any thread enters a synchronized method/block it acquires the lock on the specified object. When any thread acquires a lock it is said to have entered the monitor. All other threads which need to execute the same shared piece of code (locked monitor) will be suspended until the thread which initially acquired the lock releases it.
  3. wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to waiting state.
  4. notify method Wakes up a single thread that is waiting on this object's monitor.
  5. notifyAll method wakes up all the threads that called wait( ) on the same object.

Any method or a block of code, if not qualified with the keyword synchronized can be executed by more than one thread at any given time as object's monitor(lock) is not in the picture. Where as when a method is synchronized (or there is a synchronized block) only a single thread who has acquired the object's monitor can access the code.

I hope you would have got the picture by now. Since wait method is about thread releasing the object's lock and go to sleep where as notify/notifyAll methods are about notifying the thread(s) waiting for the object's lock. So, wait(), notify() and notifyAll() methods (as mentioned above) should be invoked on an object only when the current thread has already acquired the lock on an object.
Infact not doing so will result in java.lang.IllegalMonitorStateException.

As example suppose I have this code where I have commented the synchronized keyword and trying to call wait

while(true){
    //synchronized (sharedListObj) {
    // While condition as mandated to avoid spurious wakeup
    while(sharedListObj.size() >= 1){
        try {
            sharedListObj.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // Putting value in the list
    System.out.println("Adding to queue - " + Thread.currentThread().getName() + " " + ++i);
    sharedListObj.add(i);
    //sharedListObj.notify();    
    // To get out of while(true) loop
    if(i > 4) break;
    //}
}

This will throw exception -

Exception in thread "Producer" java.lang.IllegalMonitorStateException
 at java.lang.Object.wait(Native Method)
 at java.lang.Object.wait(Object.java:502)
 at org.netjs.examples.Producer.run(InterThreadDemo.java:20)
 at java.lang.Thread.run(Thread.java:745)

To summarize it, wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor. Object's lock is acquired by a thread only when it is executing in a synchronized context. So it makes sense to use wait() method, which asks thread to release the lock only in synchronized context.

Same way; when object's notify() or notifyAll() method is called, single thread (in case of notify) or all of the threads (in case of notifyAll), waiting for the object's lock change state to runnable and contend for the object's lock, and the thread that gets the lock starts execution. Here again, notify and notifyAll can inform other threads, that the object's lock can be acquired now, only if these methods are called from the synchronized object.

So these are the reasons why wait(), notify() and notifyAll() methods must be called inside a synchronized method or block. Please do share with me if you know any other reason for doing the same.


Related Topics

  1. Inter-thread communication using wait, notify and notifyAll
  2. Why wait(), notify() and notifyAll() methods are in Object class
  3. Can we start the same thread twice in Java
  4. Race condition in Java multi-threading
  5. Synchronization in Java multithreading
  6. Java Multi-threading interview questions

You may also like -

Tuesday, 7 July 2015

Why wait(), notify() and notifyAll() methods are in Object class and not in Thread class

Why wait(), notify() and notifyAll() methods are in Object class and not in Thread class is one of the multi-threading interview questions asked quite often.
Even if we leave the interviews aside it is important to know the concept of why anything is done in that way. So let's see the reasons behind putting the wait(), notify() and notifyAll() methods in Object class though these methods are used in multi-threading scenarios.

General form of wait(), notify() and notifyAll() in Object class

public final native void wait(long timeout) throws InterruptedException;
public final native void notify();
public final native void notifyAll();

There are 2 more overloaded wait methods

public final void wait() throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException;

Reasons for putting these methods in Object class

  1. First of all we have to know about what wait and notify do in order to be clear why they are in Object class.
    • wait - wait method tells the current thread to give up monitor and go to sleep.
    • notify - Wakes up a single thread that is waiting on this object's monitor.

    So you see wait() and notify() work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait and through notify (or notifyAll) thread which are waiting on the object's monitor are notified that thread can wake up. Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class. To reiterate threads wait on an Object's monitor(lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.

  2. wait, notify and notifyAll() are used for inter-thread communication. But threads themselves have no knowledge of each others status. It is the shared object among the threads that acts as a communicator among the threads. Threads lock an object, wait on an object and notify an object. When a wait method is called it checks which thread has the lock on the object and that is the thread which has to give up the lock. Same way notify() method when called looks for all the thread that are waiting to get hold of the Object's monitor and wakes one of the thread, notifyAll() wakes up all the thread that are waiting on an Object's monitor.
    So it is the shared object among the thread which allows them to communicate with each other and wait(), notify() and notifyAll() are the methods used for inter-thread communication.

So these are the reasons for having wait(), notify() and notifyAll() methods in Object class. Please do share with me if you know any other reason for doing the same.

That's all for this topic Why wait(), notify() and notifyAll() methods are in Object class and not in Thread class. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?
  2. What if run() method called directly instead of start() method
  3. Synchronization in Java multithreading
  4. isAlive() & join() methods in Java multithreading
  5. Print odd-even numbers using threads and wait-notify
  6. Java Multi-threading interview questions

You may also like -

Inter-thread communication using wait, notify and notifyAll - Java Multithreading

Java provides inter-thread communication using the following methods of the Object class.

  • wait()
  • notify()
  • notifyAll()

These methods are implemented as final method in the Object class thus available to all the classes, as Object class is the super class of all the classes in Java. Another important point about these methods is that they can only be called from a synchronized context, as these methods are about releasing the monitor and acquiring it again. Threads acquire monitor (lock) when entering a synchronized method (or block) so it makes sense to call them from synchronized context.

wait method

Wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to sleep, until another thread invokes the notify() or notifyAll() method for this object.

General form

public final void wait() throws InterruptedException

There are 2 more overloaded wait methods

public final void wait(long timeout) throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

public final void wait(long timeout, int nanos) throws InterruptedException

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Notify method

Wakes up a single thread that is waiting on this object's monitor. If more than one threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.

Note that the thread which comes out of waiting because of the notify() method will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread just changes to the runnable state and it is ready to be scheduled again. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

Once awakened thread(thread which has come out of waiting because of notify() method) has gained control of the object, all its synchronization claims on the object are restored to the situation as of the time that the wait method was invoked that is on return from the wait method, the synchronization state of the object and of thread is exactly as it was when the wait method was invoked.

notifyAll method

wakes up all the threads that called wait( ) on the same object. As explained in notify() any one of the threads will be granted access to the object.

Spurious wakeup

Once wait is called on an object the thread that is currently executing with in the synchronized context waits until notify or notfyAll method is called. But there is a possibility that a waiting thread resumes again even when notify() or notifyAll() are not called (this will rarely occur in practice). This is known as spurious wakeup.
To guard against it the recommendation is that call to wait() method should be with in a loop that checks the condition on which the thread is waiting.

synchronized (obj) {
    while (condition does not hold)
        obj.wait(timeout);
        ... // Perform action appropriate to condition
}

Read more about spurious wakeup in the wait method of the Java docs of Object class

http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

Producer-Consumer example using wait, notify

Let's see one of the oft mentioned example of producer and consumer implemented with two threads, where producer thread produces a number, puts it in a list and then consumer thread gets that number out of the list. Since a shared list is used between these two threads so to make sure that both threads work in tandem wait/notify mechanism is used for inter-thread communication.

class Producer implements Runnable{
    List<Integer> sharedListObj;
    Producer(List<Integer> sharedListObj){
        this.sharedListObj = sharedListObj;
    }
    @Override
    public void run() {
        int i = 0;
        while(true){
            synchronized (sharedListObj) {
                // While condition as mandated to avoid spurious wakeup
                while(sharedListObj.size() >= 1){
                    try {
                        sharedListObj.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                // Putting value in the list
                System.out.println("Adding to queue - " + Thread.currentThread().getName() + " " + ++i);
                sharedListObj.add(i);
                sharedListObj.notify();    
                // To get out of while(true) loop
                if(i > 4) break;
            }
        }
    }            
}

class Consumer implements Runnable{
    List<Integer> sharedListObj;
    Consumer(List<Integer> sharedListObj){
        this.sharedListObj = sharedListObj;
    }
    @Override
    public void run() {    
        while(true){
            synchronized (sharedListObj) {
                while(sharedListObj.size() < 1){
                    try {
                        sharedListObj.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                    
                }
                // Getting value from the list
                System.out.println("Getting from queue " + Thread.currentThread().getName() + " " + sharedListObj.get(0));
                // To get out of while(true) loop
                if(sharedListObj.get(0) == 5) break;
                sharedListObj.remove(0);
                sharedListObj.notify();        
                
            }
        }
    }
}


public class InterThreadDemo {
    public static void main(String[] args) {
        // This is the shared list shared between producer
        // and consumer
        List<Integer> sharedListObj = new ArrayList<Integer>();
        Thread t1 = new Thread(new Producer(sharedListObj), "Producer");
        Thread t2 = new Thread(new Consumer(sharedListObj), "Consumer");
        t1.start();
        t2.start();    
    }

}

Output

Adding to queue - Producer 1
Getting from queue Consumer 1
Adding to queue - Producer 2
Getting from queue Consumer 2
Adding to queue - Producer 3
Getting from queue Consumer 3
Adding to queue - Producer 4
Getting from queue Consumer 4
Adding to queue - Producer 5
Getting from queue Consumer 5

If wait/notify related code is commented though the access is synchronized nothing stops producer thread to keep producing numbers or consumer for keep on consuming numbers. Since I have used a list here and trying to get 0th element from the list it may even lead to ArrayIndexOutofBoundsException.

class Producer implements Runnable{
    List<Integer> sharedListObj;
    Producer(List<Integer> sharedListObj){
        this.sharedListObj = sharedListObj;
    }
    @Override
    public void run() {
        int i = 0;
        while(true){
            synchronized (sharedListObj) {
                // While condition as mandated to avoid spurious wakeup
                /*while(sharedListObj.size() >= 1){
                    try {
                        sharedListObj.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }*/
                // Putting value in the list
                System.out.println("Adding to queue - " + Thread.currentThread().getName() + " " + ++i);
                sharedListObj.add(i);
                //sharedListObj.notify();    
                // To get out of while(true) loop
                if(i > 4) break;
            }
        }
    }            
}

class Consumer implements Runnable{
    List<Integer> sharedListObj;
    Consumer(List<Integer> sharedListObj){
        this.sharedListObj = sharedListObj;
    }
    @Override
    public void run() {    
        while(true){
            synchronized (sharedListObj) {
                /*while(sharedListObj.size() < 1){
                    try {
                        sharedListObj.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                    
                }*/
                // Getting value from the list
                System.out.println("Getting from queue " + Thread.currentThread().getName() + " " + sharedListObj.get(0));
                // To get out of while(true) loop
                if(sharedListObj.get(0) == 5) break;
                sharedListObj.remove(0);
                //sharedListObj.notify();        
                
            }
        }
    }
}


public class InterThreadDemo {
    public static void main(String[] args) {
        // This is the shared list shared between producer
        // and consumer
        List<Integer> sharedListObj = new ArrayList<Integer>();
        Thread t1 = new Thread(new Producer(sharedListObj), "Producer");
        Thread t2 = new Thread(new Consumer(sharedListObj), "Consumer");
        t1.start();
        t2.start();    
    }

}

Output

Adding to queue - Producer 1
Adding to queue - Producer 2
Adding to queue - Producer 3
Adding to queue - Producer 4Exception in thread "Consumer" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Getting from queue Consumer 1
Getting from queue Consumer 2
Getting from queue Consumer 3
Getting from queue Consumer 4
Adding to queue - Producer 5

 at java.util.ArrayList.rangeCheck(ArrayList.java:653)
 at java.util.ArrayList.get(ArrayList.java:429)
 at org.netjs.examples.Consumer.run(InterThreadDemo.java:55)
 at java.lang.Thread.run(Thread.java:745)

It can be seen, how, in absence of proper inter-thread communication nothing stops producer thread from keep on producing numbers and when the consumer thread gets hold of the synchronized block code it keeps on consuming numbers.

That's all for this topic Inter-thread communication using wait, notify and notifyAll. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Why wait(), notify() and notifyAll() methods are in Object class
  2. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?
  3. Synchronization in Java multithreading
  4. Deadlock in Java multi-threading
  5. Can we start the same thread twice in Java
  6. Race condition in Java multi-threading
  7. Java Multi-threading interview questions

You may also like -