Pages

October 01, 2016

Part 8: Java Thread Interview Questions & Answers

What is Thread Group? Why it’s advised not to use it?
ThreadGroup is a class which was intended to provide information about a thread group. ThreadGroup API is weak and it doesn’t have any functionality that is not provided by Thread.

Two of the major features of Thread Group is to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. But Java 1.5 has added setUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add uncaught exception handler to the thread. So ThreadGroup is obsolete and hence not advised to use anymore.

What is Java Timer Class? How to schedule a task to run after specific interval?
java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.

java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MyThreadTimer extends TimerTask {

    @Override
    public void run() {
        System.out.println("**Inside rum(): Timer task started at:" + new Date());
        task();
        System.out.println("**Inside rum(): Timer task finished at:" + new Date());
    }

    private void task() {
        try {
            Thread.sleep(21000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        TimerTask timerTask = new MyThreadTimer();
        // running timer task as daemon thread
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(timerTask, 0, 10 * 1000);
        try {
            Thread.sleep(120000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        timer.cancel();
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

What is preemptive scheduling and time slicing?
In preemptive scheduling, the highest priority thread executes until it enters into the waiting or dead state.

In time slicing, a thread executes for a certain predefined time and then enters runnable pool. Than thread can enter running state when selected by thread scheduler.

What is the difference between livelock and deadlock in Java?
  • Both are similar, but the states of the threads/ processes involved in the live-lock change constantly with regard to one another, without any one progressing further.
  • We can say in livelock state of process change but no progress is made.
  • e.g Suppose two people meet in a narrow corridor. Both tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.
What is Semaphore in Java? (to read more about Semaphore click here)
It is a kind of synchronizer, which is added in Java 5. It can be used to limit the number of threads to access a certain resource.

What is Java Thread Dump?
  • A thread dump is a list of all the threads active in the JVM.
  • Thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. 
  • We can generate Thread dump by using Profiler, Kill -3 command, jstack tool, etc. jstack tool to generate thread dump of a program because it’s easy to use and comes with JDK installation. Since it’s a terminal-based tool, we can create a script to generate thread dump at regular intervals to analyze it later on.
What is Deadlock and how can we analyze and avoid it?
  • Deadlock is a programming situation where two or more threads are blocked forever.
  • To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.
  • We should avoid Nested locks. What is required should be locked, and we should also avoid waiting indefinitely are common ways to avoid deadlock situation.
Write a program to create a Deadlock in java?
public class DeadLockTest {
public static class SayHello{}
static SayHello hello1=new SayHello();
static SayHello hello2=new SayHello();
public static class Thread1 extends Thread{
@Override
public void run() {
synchronized(hello1)
{
System.out.println("***Thread1: got the lock of hello1");
try {
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("***Thread1: trying to get the lock of hello2");
synchronized (hello2) {
System.out.println("***Thread1: Yess! we got the lock of hello2");
}
}
}
}
public static class Thread2 extends Thread{
@Override
public void run() {
synchronized(hello2)
{
System.out.println("***Thread2: got the lock of hello2");
try {
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("***Thread2: trying to get the lock of hello1");
synchronized (hello1) {
System.out.println("***Thread2: Yess! we got the lock of hello1");
}
}
}
}
public static void main(String[] args) {
Thread1 thread1=new Thread1();
Thread2 thread2=new Thread2();
thread1.start();
thread2.start();
}
}

Output:
***Thread1: got the lock of hello1
***Thread2: got the lock of hello2
***Thread2: trying to get the lock of hello1
***Thread1: trying to get the lock of hello2

Difference between Object level locking vs Class level locking in java?
  • When you want to synchronize non static method or block so that it can be accessed by only one thread at a time for that instance, Object level locking is used. It is used if you want to protect non static data.
  • When you want to synchronize static method or block so that it can be accessed by only one thread for whole class Class level locking is used. If you have 10 instances of class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.

No comments:

Post a Comment