Pages

April 01, 2016

Part 5: Java Thread Interview Questions & Answers (UncaughtExceptionHandler, Synchronization, Context-Switching)


What happens when an exception occurs in a thread?
If an exception is not caught thread will die, else if an uncaught exception handler is registered then it will get a callback.

What is the use of Thread.UncaughtExceptionHandler interface?
Thread.UncaughtExceptionHandler is an interface, defined as a nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.

Checked exceptions must be specified in the throws clause of a method or caught inside them. Whereas, Unchecked exceptions don’t have to be specified or caught.

When a checked exception is thrown inside the run() method of a Thread object, we have to catch and treat it accordingly, because the run() method doesn’t accept a throws clause. But when an unchecked exception is thrown inside the run() method of a Thread object, the default behaviour is to write the stack trace in the console (or log it inside the error log file) and exit the program.

However, with UncaughtExceptionHandler interface, Java provides us with a mechanism to catch and treat the unchecked exceptions thrown in a Thread object to avoid the program's ending abruptly.

But, how does this work? 

When a thread is about to terminate due to an uncaught exception, the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments. 

If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.



What is the use of synchronized keyword?
Synchronized keyword provides a lock on the object and thus prevents race conditions and can be applied to static/non-static methods or a block of code. 

Only one thread at a time can access synchronized methods and if multiple threads are trying to access the same method then other threads have to wait for the execution of the method by one thread.

What happens when I make a static method synchronized?
Synchronized static methods have a lock on the 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 of that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at the same time for different instances.

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 we make the run method synchronized then the lock on the 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 the same object.

Can we synchronize the constructor of a Java Class?
No, the constructor cannot be synchronized. Because a constructor is used for instantiating the object, when we are in a constructor, the object is under creation. So, until the object is not instantiated it does not need any synchronization.

The JVM ensures that only one thread can invoke a constructor call at a given point in time. That's why using the keyword 'synchronized' with a constructor is illegal in Java. However, we can use synchronized blocks inside a constructor.

If we are trying to put a synchronized keyword before a constructor, the compiler says "Error: modifier synchronized not allowed here".

What happens if a thread throws an Exception inside a synchronized block?
The thread will release the lock because no matter how you exit a synchronized block, either normally by finishing execution or abruptly because of exception, the thread releases the lock it acquired while entering that synchronized block.

Is it safe to call a synchronized method from another synchronized method?
Yes. When you call the synchronized method, you will get a lock on this object and when you call another synchronized method of the same class, it is safe to execute as it already has a lock on this object.

What is a busy spin in a multi-threaded environment? or What is Busy Spinning?
It is one of the interesting multithreading questions for senior Java programmers.

Busy spinning is a waiting strategy, in which one thread repeatedly checks to see if a condition is true instead of calling the wait or sleep method and releasing the CPU. It simply eats up the computer cycle because one thread keeps on looping continuously waiting for another thread to signal.

By not releasing the CPU or suspending the thread, our thread retains all the cached data and instructions, which may be lost if the thread is suspended and resumed back in a different core of the CPU.

e.g:
while(isAllowedToProcess){
  System.out.println("waiting!! waiting!!");
}


What is context-switching in multi-threading?
When the CPU switches from executing one thread to another, the CPU needs to save local data, program pointers, etc. This is done so that the CPU state can be restored and the Thread execution can be resumed from the same point at a later point in time. This process is called context switching.

During the context switch, the CPU loads data and the program pointer of the next thread that will be executed. While a new process is running in the system, the previous process must wait in a ready queue. Once the new process is completed, the execution of the old process starts. 

Context switching is always an overhead. As the CPU has to allocate memory for the thread stack and CPU time for context switches, it is a resource and CPU-intensive process.

What is the difference between a thread context switch and a process context switch?
Thread switching is a type of context switching from one thread to another thread in the same process.  Process switching is a type of context switching where we switch one process with another process.

TCS helps the CPU to handle multiple threads simultaneously. PCS involves loading the states of the new program for its execution.

TCS is very efficient and is quite cheap since it involves switching out only identities and resources such as the program counter, registers, and stack pointers. TCS does not involve switching memory address spaces. But PCS involves switching off all the process resources with those needed by a new process. This means we need to switch the memory address space, which includes memory addresses, page tables, and kernel resources, caches in the processor. That's why TCS is a bit faster and cheaper and PCS is relatively slower and costlier.

In the case of TCS processor’s cache and Translational Lookaside Buffer preserves their state. In PCS the processor’s cache and TLB get flushed.

If you enjoy our content and want to support us, please consider donating via gpay, phonepay or paytm on +91 9920600280. Also, I’d appreciate it if you’d buy me a coffee☕ 


Keep learning and growing!
-K Himaanshu Shuklaa..

No comments:

Post a Comment