Q36. What is a ThreadLocal?

Ans: ThreadLocal as name suggests, they are local to each thread. It cannot be shared across thread. So whatever read and write happens to ThreadLocal object it will be visible to only same local thread.

Q36. How you will use ThreadLocal?

Ans: ThreadLocal instance can be created as below.

private ThreadLocal threadLocal = new ThreadLocal();

We can set the value in threadLocal as below.

threadLocal.set("Value");

You read the value stored in a ThreadLocal like this:

String threadValue = (String) threadLocal.get();

Q37.  What is thread signaling?

Ans : Thread signaling is a way by which thread can communicate with each other. For thread signaling threads will use a common objects lets say “CommonObjects”. And thread will call “wait()” ,”notify()” or “notifyAll()” method to communicate with each other.

Q38. Signaling methods are defined in which class?

Ans: As mentioned above all methods “wait()” ,”notify()” or “notifyAll()” are defined on Object level. Hence, every objects will have these methods. And also mentioned all thread must be using common object to get signal from each other. So thread will call these methods on common objects.

Q39. What is the use of “wait()” ,”notify()” or “notifyAll()” ?

Ans : Suppose we have two three threads ThreadA, ThreadB and ThreadC. All needs to execute below code block (this is not complete code)

synchronized write(){

counter=counter+1;

this.notify();

}

synchronized read(){

            this.wait()

return counter;

}

 

Now ThreadA is executing write() method and ThreadB are executing read() method. To entering in synchronized block each thread has first take a lock on common objects (that is this object, in this case). Let’s assume ThreadB get a lock and to read the counter value, and ThreadA is waiting for getting lock on this object to enter write() method. As soon as ThreadB reaches to this.wait() it will release the lock and wait for notifications from other thread to return counter value. Now, ThreadA can get a lock and start writing counter value and once done it will notify() waiting thread (in this case ThreadB) and release the lock. As soon as thread get notification it will process and return the updated counter value.

Q40. Is it necessary to have wait() and notify() calls to be in synchronized block?

Ans: Yes, wait(), notify() and notifyAll() can be called from synchronized block only. They must have a lock on common object. Than only they can call these methods.