Tuesday, November 23, 2010

Thread Interview Questions

Question : How wil you Define a Thread ?
Answer : 1) By Extending the Thread class.
               2) By Implementing the Runnable Interface.


A Runnable Interface defines a type of class that can be run by a thread.


Question : What is the difference between the below code snip-t?
  Code snippet  :
                          class MyThread extends Thread {
                       public void run() {
                                System.out.println("Important job running in MyThread");
                        }

                        public void run(String s) {
                              System.out.println("String in run is " + s);
                      }

                  }

In above code even though we write two run methods run() and run(String s) ,the
method run(String s) will be ignored by the thread class.

unless you call it yourself.

The Thread class expects a run() method with no argument and it will execute this
method for you in separate call stack after the thread has been created.
The Thread class wont call the run(String s) and even if u call yourself the thread 
class it wont execute this in a new thread with separate call stack. It is just like a 
normal method.


Question : Advantage of defining a thread by implementing the Runnable interface?
Answer Implementing the Runnable interface gives you a way to extend from
 any class you like, but still define behavior that will be run by a separate thread.
 It looks like this:
Note : Every thread of Execution begins as an instance of Thread class,Regardless 
whether you run() method is in the Thread subclass or in a Runnable Implementation.


Question : What is run() method ?
Answer : run() method is the job for the thread to execute.


Note : By defining a thread using the Runnable interface, we separating the thread 
and JOB of that thread, because thread specific code will be in the thread class and the thread job will be in run() method(which lies in the class that implements the runnable interface).


Question : What is the meaning of the below code ?
Answer : line no  10  : public class MyRunnable implements Runnable{
                line no  20 : public static void main(String[] args) {
                line no  30 :  MyRunnable r = new MyRunnable();
                line no  40 : Thread t = new Thread(r);
        }
in line-no : 30 we are instantiating Runnable class,  and in Line 40 , passing your
 runnable to thread.
If you create a thread using a non argument constructor, the thread will call it's own
run() method, when it's time to start working.But in line 40 we are telling to new thread
that use my own run method.(job) instead of run() method in thread class when it's 
time to start working, the runnable you are passing to thread constructor is called the
target or  target Runnable.
Note : Passing the same runnable target to different threads means, assigning same job to different threads.


Question : What are the other constructors in a thread class ?
Answer : 1)  Thread()  
               2) Thread(Runnable target)
               3) Thread(Runnable target,String name)
               4) Thread(String name)


Question : When the new stack will allocate for a thread ?
Answer : A new Stack for thread allocated only when the start() method has been
 invoked on that thread.


Question : Where the memory for thread will get allocated?
Answer: Inside the JVM, each thread is awarded a Java stack, which contains data 
no other thread can access.Including the local variables, parameters and return values
of each method the thread has invoked.


Question : What is new state of a thread ?
Answer : A Thread is created but not yet started means start() method of thread is not 
yet called.


Question : What is thread alive ?
Answer : A thread is alive once the Start() method is called on that thread.


Question : How long the thread will be alive?
Answer : Until it completes it's execution i.e.. till finishes it's run(job) method.


Question : How to assign a job to the thread ?
Ans : By the The runnable target to the Thread class constructor.
                                  or
         By extending the thread class.


Question : What happens when you call the start() method on thread ?
Answer :   1)  A new thread of execution starts ( with new call stack)
                 2)  The thread moves from the new state to runnable state.
                 3)  When the thread gets the chance to execute it's target run() method
                      will get called.


Question : Can i start the completed (or) dead thread again ?
Answer :   we cannot start the thread once it is dead (by finished executing the
                  run() method) however we can call other methods on that except the
                 start() method.


Note : One Thread cannot put another thread in sleep.
Note : The Default priority of the thread is 5 .
Note : A thread gets the priority of the thread which created this created.


Question : What is yield() method will do ?
Answer : So while yield() might—and often does—make a running thread give
 up its slot to another runnable thread of the same priority, there's no guarantee.
A yield() won't ever cause a thread to go to the waiting/sleeping/ blocking state. 
At most, a yield() will cause a thread to go from running to runnable, but
again, it might have no effect at all.


Question : Is volatile variable is synchronized ?
Answer : Yes, volatile is the Synchronized variable.


Question : When should i use the Volatile Variable ?
Ans: We can declare a variable as volatile, when that variable accessed/modified
by a multiple threads independently, and asynchronously.


Question : Explain the difference between the waiting state and blocked state?
Waiting State : A thread can enter to the Waiting state by calling the wait()
method (or) by calling the join() method. A Waiting thread can be activated
by any other thread by using the notify(),notify-all()method. Merely the waiting
thread is waiting for a call from another thread, (or) for any thread to finish it's job. 
When a Thread went into waiting state, it relinquishes all it's current locks.


Blocked State: A thread can enter into this state by calling wait() method. Here 
thread waits for a signal/semaphore/monitor to come out from wait state.
When a Thread enters into block state it relinquishes all it's current locks.


Explain scenario where a Thread enters into Waiting state and blocking state?
Ans: When thread acquires lock on a object, it releases all it's monitors or locks 
to enter into the waiting state. And if any other thread notify this thread by calling 
the notify().notifyall() method. Then this thread try to acquire all the locks (or)
monitors it previously released. If other thread acquires this monitor (or) lock 
already then this thread will put in Blocked state.


Note: A thread which is in blocked state will move directly to running state
after acquired lock or signal received like semaphore/signal/monitor.
But, a waiting state thread notified by other thread by notify and notifyall then
this thread will move to ReadytoRun() state,instead of running method.


Question : When a Thread enters into dead state from blocked state()?
Ans: When a thread blocked for I/O socket if that socket is closed by another thread.
then this thread will move to dead State.
Question : Where the Yielding thread will go?
Ans: A yielding thread will go to Ready-to-run Method.
Question :  What is sleeping state()?
Ans: When a thread enters into Sleeping state it wont release all the locks it currently 
hold and once after the elapsed time is over it moves to ready-to-run state().
Question : What is blocked-on-Synchronization State?
Ans : A thread may move to this thread, while it is waiting for lock on an Object.
It enters into ready-to-run() state once it got the object's lock.


Question : Explain the thread Synchronization concept with an Example ?
Answer
Below are the two methods synchronized on the instances they are called on.
--------------------------------------------------------------------------------------------

public synchronized void log1(String msg1,String msg2){
System.out.println(" >>> "+Thread.currentThread().getName());
System.out.println(" Message 1  "+msg1);
System.out.println(" Message 1  "+msg2);
try{
Thread.sleep(5*60*1000);
}catch(Exception e){
e.printStackTrace();
}
}
----------------------------------------------------------------------------------------------

public void log2(String msg1,String msg2){
synchronized(this){
System.out.println(" >>> "+Thread.currentThread().getName());
System.out.println(" Message2  "+msg1);
System.out.println(" Message2  "+msg2);
}
}
-----------------------------------------------------------------------------------------------

Observation :


Now create two threads and pass the same instance to the both threads.
then if one thread executing one synchronized block, another thread can't able
to execute another synchronized block.Because both blocks having the 
lock on the instances they are called on.


IF you call two threads with different instance then two threads can execute 
parallel...
Below is the Complete Java Code :
....................... ...................... . . . . . . . . . . .. . .. . . . . .. . .....................................

package newPackage;
public class LogClass {


public synchronized void log1(String msg1,String msg2){
System.out.println(" >>> "+Thread.currentThread().getName());
System.out.println(" Message 1  "+msg1);
System.out.println(" Message 1  "+msg2);
try{
Thread.sleep(5*60*1000);
}catch(Exception e){
e.printStackTrace();
}
}

public void log2(String msg1,String msg2){
synchronized(this){
System.out.println(" >>> "+Thread.currentThread().getName());
System.out.println(" Message2  "+msg1);
System.out.println(" Message2  "+msg2);
}
}
}
-------------------------------------------------------------------------------------------
package newPackage;
public class Another extends Thread{
protected LogClass logObject = null;
public void run(){
if(Thread.currentThread().getName().equals("ThreadA")){
logObject.log1("sekhar","Kiran");
}
if(Thread.currentThread().getName().equals("ThreadB")){
logObject.log2("Ravi","Pandu");
}
}
public  Another(LogClass a) {
this.logObject = a;
}
}
-------------------------------------------------------------------------------------------
package newPackage;

public class CreateThread {

public static void main(String[] args) {
LogClass a = new LogClass();
Thread threadA = new Another(a);
Thread threadB = new Another(a);
threadA.setName("ThreadA");
threadB.setName("ThreadB");
threadA.start();
threadB.start();
}
}
Good link :
http://tutorials.jenkov.com/java-concurrency/synchronized.html

Question : Tell me something about the volatile variable?

point 1 : The value of the variable never be cached thread -locally.All reads and writes will go
Straightly to main memory.
Point 2 : A variable need to declared as volatile, where it value modified by several threads
Asynchronously.
Point 3 : Access to this variable is synchronized itself.

No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...