The largest Interview Solution Library on the web


Interview Questions
« Previous | 0 | 1 | 2 | 3 | 4 | Next »

21.What is life cycle of Thread, explain thread states?

Thread states/ Thread life cycle is very basic question, before going deep into concepts we must understand Thread life cycle.
Thread have following states >
New
Runnable
Running
Waiting/blocked/sleeping
Terminated (Dead)
Thread states/ Thread life cycle in diagram >
Thread states in detail >
New : When instance of thread is created using new operator it is in new state, but the start() method has not been invoked on the thread yet, thread is not eligible to run yet.
Runnable : When start() method is called on thread it enters runnable state.
Running : Thread scheduler selects thread to go fromrunnable to running state. In running state Thread starts executing by entering run() method.
Waiting/blocked/sleeping : In this state a thread is not eligible to run.
>Thread is still alive, but currently it’s not eligible to run. In other words.
> How can Thread go from running to waiting state?
By calling wait()method thread go from running to waiting state. In waiting state it will wait for other threads to release object monitor/lock.
> How can Thread go from running to sleeping state?
By calling sleep() methodthread go from running to sleeping state. In sleeping state it will wait for sleep time to get over.
Terminated (Dead) : A thread is considered dead when its run() method completes.

22.Are you aware of 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.

23.What are daemon threads?

Daemon threads are low priority threads which runs intermittently in background for doing garbage collection.
12 Few salient features of daemon() threads>
Thread scheduler schedules these threads only when CPU is idle.
Daemon threads are service oriented threads, they serves all other threads.
These threads are created before user threads are created and die after all other user threads dies.
Priority of daemon threads is always 1 (i.e. MIN_PRIORITY).
User created threads are non daemon threads.
JVM can exit when only daemon threads exist in system.
we can use isDaemon() method to check whether thread is daemon thread or not.
we can use setDaemon(boolean on) method to make any user method a daemon thread.
If setDaemon(boolean on) is called on thread after calling start() method than IllegalThreadStateException is thrown.
You may like to see how daemon threads work, for that you can use VisualVM or jStack. I have provided Thread dumps over there which shows daemon threads which were intermittently running in background.
Some of the daemon threads which intermittently run in background are >
"RMI TCP Connection(3)-10.175.2.71" daemon"RMI TCP Connection(idle)" daemon"RMI Scheduler(0)" daemon"C2 CompilerThread1" daemon
"GC task thread#0 (ParallelGC)"

24.Why suspend() and resume() methods are deprecated?

Suspend() method is deadlock prone. If the target thread holds a lock on object when it is suspended, no thread can lock this object until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, it results in deadlock formation.
These deadlocksare generally called Frozen processes.
Suspend() method puts thread from running to waiting state. And thread can go from waiting to runnable state only when resume() method is called on thread. It is deprecated method.
Resume() method is only used with suspend() method that’s why it’s also deprecated method.

25.Why destroy() methods is deprecated?

This question is again going to check your in depth knowledge of thread methods i.e. destroy() method is deadlock prone. If the target thread holds a lock on object when it is destroyed, no thread can lock this object (Deadlock formed are similar to deadlock formed when suspend() and resume() methods are used improperly). It results in deadlock formation. These deadlocksare generally called Frozen processes.
Additionally you must know calling destroy() method on Threads throw runtimeException i.e. NoSuchMethodError. Destroy() method puts thread from running to dead state.

26.As stop() method is deprecated, How can we terminate or stop infinitely running thread in java?

This is very interesting question where interviewees thread basics basic will be tested. Interviewers tend to know user’s knowledge about main thread’s and thread invoked by main thread.
We will try to address the problem by creating new thread which will run infinitely until certain condition is satisfied and will be called by main Thread.
Infinitely running thread can be stopped using boolean variable.
Infinitely running thread can be stopped using interrupt() method.
Let’s understand Why stop() method is deprecated :
Stopping a thread with Thread.stop() causes it to release all of the monitors that it has locked. If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, which might lead to unpredictable behavior

27. what is significance of yield() method, what state does it put thread in?

yield() is a native method it’s implementation in java 6 has been changed as compared to its implementation java 5. As method is native it’s implementation is provided by JVM.
In java 5, yield() method internally used to call sleep() method giving all the other threads of same or higher priority to execute before yielded thread by leaving allocated CPU for time gap of 15 millisec.
But java 6, calling yield() method gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor. The thread scheduler is free to ignore this hint. So, sometimes even after using yield() method, you may not notice any difference in output.
salient features of yield() method >
Definition : yield() method when called on thread gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor.The thread scheduler is free to ignore this hint.
Thread state : when yield() method is called on thread it goes from running to runnable state, not in waiting state. Thread is eligible to run but not running and could be picked by scheduler at anytime.
Waiting time : yield() method stops thread for unpredictable time.
Static method : yield()is a static method, hence calling Thread.yield() causes currently executing thread to yield.
Native method : implementation of yield() method is provided by JVM.
Let’s see definition of yield() method as given in java.lang.Thread -
public static native void yield();
synchronized block : thread need not to to acquire object lock before calling yield()method i.e. yield() method can be called from outside synchronized block

28.What is significance of sleep() method in detail, what statedoes it put thread in ?

sleep() is a native method, it’s implementation is provided by JVM.
10 salient features of sleep() method >
Definition : sleep() methods causes current thread to sleep for specified number of milliseconds (i.e. time passed in sleep method as parameter). Ex- Thread.sleep(10) causes currently executing thread to sleep for 10 millisec.
Thread state : when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.
Exception : sleep() method must catch or throw compile time exception i.e. InterruptedException.
Waiting time : sleep() method have got few options.
sleep(long millis) - Causes the currently executing thread to sleep for the specified number of milliseconds
public static native void sleep(long millis) throws InterruptedException;
sleep(long millis, int nanos) - Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
public static native void sleep(long millis,int nanos) throws InterruptedException;
static method : sleep()is a static method, causes the currently executing thread to sleep for the specified number of milliseconds.
Belongs to which class :sleep() method belongs to java.lang.Thread class.
synchronized block : thread need not to to acquire object lock before calling sleep()method i.e. sleep() method can be called from outside synchronized block.

29.Difference between wait() and sleep() ?

Should be called from synchronized block :wait() method is always called from synchronized block i.e. wait() method needs to lock object monitor before object on which it is called. But sleep() method can be called from outside synchronized block i.e. sleep() method doesn’t need any object monitor.
IllegalMonitorStateException : if wait() method is called without acquiring object lock than IllegalMonitorStateException is thrown at runtime, but sleep() methodnever throws such exception.
Belongs to which class : wait() method belongs to java.lang.Object class but sleep() method belongs to java.lang.Thread class.
Called on object or thread : wait() method is called on objects but sleep() method is called on Threads not objects.
Thread state : when wait() method is called on object, thread that holded object’s monitor goes from running to waiting state and can return to runnable state only when notify() or notifyAll()method is called on that object. And later thread scheduler schedules that thread to go from from runnable to running state.
when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.
When called from synchronized block :when wait() method is called thread leaves the object lock. But sleep()method when called from synchronized block or method thread doesn’t leaves object lock.

30.Differences and similarities between yield() and sleep()?

Differences yield() and sleep() :
Definition : yield() method when called on thread gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor.The thread scheduler is free to ignore this hint. sleep() methods causes current thread to sleep for specified number of milliseconds (i.e. time passed in sleep method as parameter). Ex- Thread.sleep(10) causes currently executing thread to sleep for 10 millisec.
Thread state : when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up. when yield() method is called on thread it goes from running to runnable state, not in waiting state. Thread is eligible to run but not running and could be picked by scheduler at anytime.
Exception : yield() method need not to catch or throw any exception. But sleep() method must catch or throw compile time exception i.e. InterruptedException.
Waiting time : yield() method stops thread for unpredictable time, that depends on thread scheduler. But sleep() method have got few options.
sleep(long millis) - Causes the currently executing thread to sleep for the specified number of milliseconds
sleep(long millis, int nanos) - Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
similarity between yield() and sleep():
> yield() and sleep() method belongs to java.lang.Thread class.
> yield() and sleep() method can be called from outside synchronized block.
> yield() and sleep() method are called on Threads not objects.

31.Mention some guidelines to write thread safe code, most important point we must take care of in multithreading programs?

In multithreading environment it’s important very important to write thread safe code, thread unsafe code can cause a major threat to your application. I have posted many articles regarding thread safety. So overall this will be revision of what we have learned so far i.e. writing thread safe healthy code and avoiding any kind of deadlocks.
If method is exposed in multithreading environment and it’s not synchronized (thread unsafe) than it might lead us to race condition, we must try to use synchronized block and synchronized methods. Multiple threads may exist on same object but only one thread of that object can enter synchronized method at a time, though threads on different object can enter same method at same time.
Even static variables are not thread safe, they are used in static methods and if static methods are not synchronized then thread on same or different object can enter method concurrently. Multiple threads may exist on same or different objects of class but only one thread can enter static synchronized method at a time, we must consider making static methods as synchronized.
If possible, try to use volatile variables. If a field is declared volatile all threads see a consistent value for the variable. Volatile variables at times can be used as alternate to synchronized methods as well.
Final variables are thread safe because once assigned some reference of object they cannot point to reference of other object.
s is pointing to String object.
public class MyClass {
final String s=new String("a");
void method(){
s="b"; //compilation error, s cannot point to new reference.
}
}
If final is holding some primitive value it cannot point to other value.
public class MyClass {
final inti=0;
void method(){
i=0; //compilation error, i cannot point to new value.
}
}
Usage of local variables : If possible try to use local variables, local variables are thread safe, because every thread has its own stack, i.e. every thread has its own local variables and its pushes all the local variables on stack.
public class MyClass {
void method(){
inti=0; //Local variable, is thread safe.
}
}
11 Using thread safe collections : Rather than using ArrayList we must Vector and in place of using HashMap we must use ConcurrentHashMap or HashTable.
12 We must use VisualVM or jstack to detect problems such as deadlocks and time taken by threads to complete in multi threading programs.
13 Using ThreadLocal:ThreadLocal is a class which provides thread-local variables. Every thread has its own ThreadLocal value that makes ThreadLocal value threadsafe as well.
14 Rather than StringBuffer try using immutable classes such as String. Any change to String produces new String.

32.How thread can enter waiting, sleeping and blocked state and how can they go to runnable state ?

This is very prominently asked question in interview which will test your knowledge about thread states. And it’s very important for developers to have in depth knowledge of this thread state transition. I will try to explain this thread state transition by framing few sub questions. I hope reading sub questions will be quite interesting.
> How can Thread go from running to waiting state ?
By calling wait()method thread go from running to waiting state. In waiting state it will wait for other threads to release object monitor/lock.
> How can Thread return from waiting to runnable state ?
Once notify() or notifyAll()method is called object monitor/lock becomes available and thread can again return to runnable state.
> How can Thread go from running to sleeping state ?
By calling sleep() methodthread go from running to sleeping state. In sleeping state it will wait for sleep time to get over.
> How can Thread return from sleeping to runnable state ?
Once specified sleep time is up thread can again return to runnable state.
Suspend() method can be used to put thread in waiting state and resume() method is the only way which could put thread in runnable state.
Thread also may go from running to waiting state if it is waiting for some I/O operation to take place. Once input is available thread may return to running state.
>When threads are in running state, yield()method can make thread to go in Runnable state.

33.Difference between notify() and notifyAll() methods, can you write a code to prove your point?

Goodness. Theoretically you must have heard or you must be aware of differences between notify() and notifyAll().But have you created program to achieve it? If not let’s do it.
First, I will like give you a brief description of what notify() and notifyAll() methods do.
notify()- Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is random and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.
public final native void notify();
notifyAll()- Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.
The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.
public final native void notifyAll();
Now it’s time to write down a program to prove the point.

34.Does thread leaves object lock when sleep() method is called?

When sleep() method is called Thread does not leaves object lock and goes from running to waiting state. Thread waits for sleep time to over and once sleep time is up it goes from waiting to runnable state.

35.Does thread leaves object lock when wait() method is called?

When wait() method is called Thread leaves the object lock and goes from running to waiting state. Thread waits for other threads on same object to call notify() or notifyAll() and once any of notify() or notifyAll() is called it goes from waiting to runnable state and again acquires object lock.

36. What will happen if we don’t override run method?

This question will test your basic knowledge how start and run methods work internally in Thread Api.
When we call start() method on thread, it internally calls run() method with newly created thread. So, if we don’t override run() method newly created thread won’t be called and nothing will happen.
class MyThread extends Thread {
//don't override run() method
}
publicclass DontOverrideRun {
publicstaticvoid main(String[] args) {
System.out.println("main has started.");
MyThread thread1=new MyThread();
thread1.start();
System.out.println("main has ended.");
}
}
/*OUTPUT
main has started.
main has ended.
*/
As we saw in output, we didn’t override run() method that’s why on calling start() method nothing happened.

37.What will happen if we override start method?

This question will again test your basic core java knowledge how overriding works at runtime, what what will be called at runtime and how start and run methods work internally in Thread Api.
When we call start() method on thread, it internally calls run() method with newly created thread. So, if we override start() method, run() method will not be called until we write code for calling run() method.
class MyThread extends Thread {
@Override
publicvoid run() {
System.out.println("in run() method");
}
@Override
publicvoid start(){
System.out.println("In start() method");
}
}
publicclass OverrideStartMethod {
publicstaticvoid main(String[] args) {
System.out.println("main has started.");
MyThread thread1=new MyThread();
thread1.start();
System.out.println("main has ended.");
}
}
/*OUTPUT
main has started.
In start() method
main has ended.
*/
If we note output. we have overridden start method and didn’t called run() method from it, so, run() method wasn’t call

38.Can we acquire lock on class? What are ways in which you can acquire lock on class?

Yes, we can acquire lock on class’s class object in 2 ways to acquire lock on class.
Thread can acquire lock on class’s class object by-
Entering synchronized block or
Let’s say there is one class MyClass. Now we can create synchronization block, and parameter passed with synchronization tells which class has to be synchronized. In below code, we have synchronized MyClass
synchronized (MyClass.class) {
//thread has acquired lock on MyClass’s class object.
}
by entering static synchronized methods.
public staticsynchronizedvoid method1() {
//thread has acquired lock on MyRunnable’s class object.
}
As soon as thread entered Synchronization method, thread acquired lock on class’s class object.
Thread will leave lock when it exits static synchronized method.

39.Difference between object lock and class lock?

It is very important question from multithreading point of view. We must understand difference between object lock and class lock to answer interview, ocjp answers correctly.
Object lock

  • Thread can acquire object lock by- Entering synchronized block or
  • by entering synchronized methods.
  • Multiple threads may exist on same object but only one thread of that object can enter synchronized method at a time.
  • Threads on different object can enter same method at same time.
  • Multiple objects of class may exist and every object has it’s own lock.
  • First let’s acquire object lock by entering synchronized block.
Example- Let’s say there is one class MyClassand we have created it’s object and reference to that object is myClass. Now we can create synchronization block, and parameter passed with synchronization tells which object has to be synchronized. In below code, we have synchronized object reference by myClass.
MyClass myClass=newMyclass();
synchronized (myClass) {
}
As soon thread entered Synchronization block, thread acquired object lock on object referenced by myClass (by acquiring object’s monitor.)
Thread will leave lock when it exits synchronized block.
publicsynchronizedvoid method1() { }
As soon as thread entered Synchronization method, thread acquired object lock.
Thread will leave lock when it exits synchronized method.
Class lock
  • Thread can acquire lock on class’s class object by- Entering synchronized block or
  • by entering static synchronized methods.
  • Multiple threads may exist on same or different objects of class but only one thread can enter static synchronized method at a time.
  • Multiple objects of class may exist but there is always one class’s class object lock available.
  • First let’s acquire lock on class’s class object by entering synchronized block.
Example- Let’s say there is one class MyClass. Now we can create synchronization block, and parameter passed with synchronization tells which class has to be synchronized. In below code, we have synchronized MyClass
synchronized (MyClass.class) {
}
As soon as thread entered Synchronization block, thread acquired MyClass’s class object. Thread will leave lock when it exits synchronized block.
public staticsynchronizedvoid method1() {}
As soon as thread entered static Synchronization method, thread acquired lock on class’s class object.
Thread will leave lock when it exits synchronized method.
Let’s me give you some tricky situation based question,

40.Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time?

No, here when Thread-1 is in synchronized method1() it must be holding lock on object’s monitor and will release lock on object’s monitor only when it exits synchronized method1(). So, Thread-2 will have to waitfor Thread-1 to release lock on object’s monitor so that it could enter synchronized method2().
Likewise, Thread-2 even cannot enter synchronized method1() which is being executed by Thread-1. Thread-2 will have to wait for Thread-1 to release lock on object’s monitor so that it could enter synchronized method1(). Now, let’s see a program to prove our point.

« Previous | 0 | 1 | 2 | 3 | 4 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com