Multi Threading Java Interview Questions – Set 08

What is the difference between sleep(), suspend() and wait()

Thread.sleep() takes the current thread to a “Not Runnable” state for specified amount of time. The thread holds the monitors it has acquired. For example, if a thread is running a synchronized block or method and sleep method is called then no other thread will be able to enter this block or method. The sleeping thread can wake up when some other thread calls t.interrupt on it. Note that sleep is a static method, that means it always affects the current thread (the one executing sleep method). A common mistake is trying to call t2.sleep() where t2 is a different thread; even then, it is the current thread that will sleep, not the t2 thread. thread.suspend() is deprecated method. Its possible to send other threads into suspended state by making a suspend method call. In suspended state a thread keeps all its monitors and can not be interrupted. This may cause deadlocks therefore it has been deprecated. object.wait() call also takes the current thread into a “Not Runnable” state, just like sleep(), but with a slight change. Wait method is invoked on a lock object, not thread.

Here is the sequence of operations you can think:

  • A thread T1 is already running a synchronized block with a lock on object – lets say “lockObject”
  • Another thread T2 comes to execute the synchronized block and find that its already acquired.
  • Now T2 calls lockObject.wait() method for waiting on lock to be release by T1 thread.
  • T1 thread finishes all its synchronized block work.
  • T1 thread calls lockObject.notifyAll() to notify all waiting threads that its done using the lock.
  • Since T2 thread is first in the queue of waiting it acquires the lock and starts processing.

What is the difference between yield and sleeping? What is the difference between the methods sleep( ) and wait( )

When a task invokes yield( ), it changes from running state to runnable state.

When a task invokes sleep ( ), it changes from running state to waiting/sleeping state.

The method wait(1000), causes the current thread to sleep up to one second. A thread could sleep less than 1 second if it receives the notify( ) or notifyAll( ) method call.

The call to sleep(1000) causes the current thread to sleep for 1 second.

Can we synchronize the run method? If yes then what will be the behavior

Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object.

What is synchronization in respect to multi-threading in Java

With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program.

How to find a deadlock has occurred in Java? How to detect a Deadlock in Java

Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.

  • findMonitorDeadlockedThreads() – This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor.
  • findDeadlockedThreads() – It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.

Write a multi-threaded Java program in which, one thread generates odd numbers and write to a pipe and the second thread generates even numbers and write to another pipe, and a third thread receives the numbers from both the pipes and evaluates if the sum is multiples of 5

In Unix, a pipe (“|”) operator helps you to redirect output from one command to another.

PipedReader and PipedWriterclasses in java.io package helps you to do the same.

It helps you to redirect the read input into writer seamlessly.

In Unix, two different processes on different address spaces can communicate using pipe, but in java two threads on the JVM can communicate using Piped ByteStream/CharacterStream within the same process

(i.e same address space)

Here is the code snippet. The Writer threads responsible for writing odd and even numbers to the respective pipes.

package multithreading;

import java.io.IOException;

import java.io.PipedWriter;

public class NumberWriter extends Thread {

private PipedWriter writer;

private int maxNumber;

private boolean isEvenNumber;

public NumberWriter(PipedWriter writer, int maxNumber, boolean isEvenNumber) {

this.writer = writer;

this.maxNumber = maxNumber;

this.isEvenNumber = isEvenNumber;

}

public void run() {

int i = 1;

while (i <= maxNumber) {

try {

if (isEvenNumber && (i % 2) == 0) {

writer.write(i);

} else if (!isEvenNumber && i%2 != 0) {

writer.write(i);

}

++i;

} catch (IOException e) {

e.printStackTrace();

}

}

}

public static void main(String[] args) {

final int MAX_NUM = 10;

PipedWriter oddNumberWriter = new PipedWriter();

PipedWriter evenNumberWriter = new PipedWriter();

NumberWriter oddGen = new NumberWriter(oddNumberWriter, MAX_NUM, false);

NumberWriter evenGen = new NumberWriter(evenNumberWriter, MAX_NUM, true);

NumberReceiver receiver = new NumberReceiver(oddNumberWriter, evenNumberWriter);

oddGen.start();

evenGen.start();

receiver.start();

}

}

The receiver thread that listens to both odd and even number pipes and computes the sum. If the sum is a multiple of 5, it prints the numbers and the sum.

package multithreading;

import java.io.IOException;

import java.io.PipedReader;

import java.io.PipedWriter;

public class NumberReceiver extends Thread {

private PipedReader oddReader;

private PipedReader evenReader;

public NumberReceiver(PipedWriter oddWriter, PipedWriter evenWriter) {

try {

this.oddReader = new PipedReader(oddWriter);

this.evenReader = new PipedReader(evenWriter);

} catch (IOException e) {

e.printStackTrace();

}

}

public void run() {

int odd =0, even=0;

try {

while (odd != -1) {

odd = oddReader.read();

even = evenReader.read();

if ((odd + even) % 5 == 0) {

System.out.println(“match found ” + odd + ” + ” + even + ” = ” + (odd + even));

}

}

} catch (IOException e) {

System.exit(1);

}

}

}

The output will be something like:

match found 7 + 8 = 15

Can we synchronize the constructor of a Java Class

As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish

What is immutable object? How does it help in writing concurrent application

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer. Immutable objects greatly simplify your multi threaded program, since they are

  • Simple to construct, test, and use.
  • Automatically thread-safe and have no synchronization issues.

To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

What happens when I make a static method as synchronized

Synchronized static methods have a lock on the class “Class”, so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access “same synchronized instance methods” at same time for different instances.

Can you give some examples of thread racing conditions you had experienced

  • Declaring variables in JSP pages are not thread-safe. The declared variables in JSP pages end-up as instance variables in the converted Servlets. <%! Calendar c = Calendar.getInstance(); %>
  • Decalring instance variables in Servlets is not thread safe, as Servlets are inherently multi-threaded and gets accessed by multiple-threads. Same is true for the Actionclasses in the struts framework.
  • Some of the Java standard library classes likeSimpleDateFormat is not thread-safe. Always check the API to see if a particular class is thread-safe. If a particular class or library is not therad-safe, you could do one of three things.

Provide your own wrapper class that decorates the third-party library with proper synchronization.

This is a typical use of the decorator design pattern.

Use an alternative library, which is thread-safe if available.

For example, Joda Time Library.

Use it in a thread-safe manner.

For example, you could use the SimpleDateFormat class as shown below within a ThreadLocal class.

Each thread will have its own instance of the SimpleDateFormat object.

public class DateFormatTest

{

//          anonymous inner class. Each thread will have its own copy

private final static ThreadLocal<SimpleDateFormat> shortDateFormat

=  new ThreadLocal<SimpleDateFormat>()

{

protected SimpleDateFormat initialValue()

{

return new SimpleDateFormat(“dd/MM/yyyy”);

}

};

public Date convert(String strDate)throws ParseException

{

//          get the SimpleDateFormat instance for this thread and parse the date string

Date d = shortDateFormat.get().parse(strDate);

return d;

}

}

  • The one that is very popular with the interviewers is writing the singleton classes that are not thread-safe.