41.Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in static synchronized method1(), can Thread-2 enter static synchronized method2() at same time?
No, here when Thread-1 is in static synchronized method1() it must be holding lock on class class’s object and will release lock on class’s classobject only when it exits static synchronized method1(). So, Thread-2 will have to wait for Thread-1 to release lock on class’s classobject so that it could enter static synchronized method2().
Likewise, Thread-2 even cannot enter static synchronized method1() which is being executed by Thread-1. Thread-2 will have to wait for Thread-1 to release lock on class’s classobject so that it could enter static synchronized method1(). Now, let’s see a program to prove our point.
42.Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in synchronized method1(), can Thread-2 enter static synchronized method2() at same time?
here when Thread-1 is in synchronized method1() it must be holding lock on object’s monitor and Thread-2 can enter static synchronized method2() by acquiring lock on class’s class object. Now, let’s see a program to prove our point.
43.Suppose you have thread and it is in synchronized method and now can thread enter other synchronized method from that method?
Yes, here when thread is in synchronized method it must be holding lock on object’s monitor and using that lock thread can enter other synchronized method. Now, let’s see a program to prove our point.
44.Suppose you have thread and it is in static synchronized method and now can thread enter other static synchronized method from that method?
Yes, here when thread is in static synchronized method it must be holding lock on class’s class object and using that lock thread can enter other static synchronized method. Now, let’s see a program to prove our point.
45.Suppose you have thread and it is in static synchronized method and now can thread enter other non static synchronized method from that method?
Yes, here when thread is in static synchronized method it must be holding lock on class’s class object and when it enters synchronized method it will hold lock on object’s monitor as well.
So, now thread holds 2 locks (it’s also called nested synchronization)-
>first one on class’s class object.
>second one on object’s monitor (This lock will be released when thread exits non static method).Now, let’s see a program to prove our point.
46.Suppose you have thread and it is in synchronized method and now can thread enter other static synchronized method from that method?
Yes, here when thread is in synchronized method it must be holding lock on object’s monitor and when it enters static synchronized method it will hold lock on class’s class object as well.
So, now thread holds 2 locks (it’s also called nested synchronization)-
>first one on object’s monitor.
>second one on class’s class object.(This lock will be released when thread exits static method).Now, let’s see a program to prove our point.
47.Suppose you have 2 threads (Thread-1 on object1 and Thread-2 on object2). Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time?
Yes, here when Thread-1 is in synchronized method1() it must be holding lock on object1’s monitor. Thread-2 will acquire lock on object2’s monitor and enter synchronized method2().
Likewise, Thread-2 even enter synchronized method1() as well which is being executed by Thread-1 (because threads are created on different objects). Now, let’s see a program to prove our point.
48.Suppose you have 2 threads (Thread-1 on object1 and Thread-2 on object2). Thread-1 is in static synchronized method1(), can Thread-2 enter static synchronized method2() at same time?
No, it might confuse you a bit that threads are created on different objects. But, not to forgot that multiple objects may exist but there is always one class’s class object lock available.
Here, when Thread-1 is in static synchronized method1() it must be holding lock on class class’s object and will release lock on class’s classobject only when it exits static synchronized method1(). So, Thread-2 will have to wait for Thread-1 to release lock on class’s classobject so that it could enter static synchronized method2().
Likewise, Thread-2 even cannot enter static synchronized method1() which is being executed by Thread-1. Thread-2 will have to wait for Thread-1 to release lock on class’s classobject so that it could enter static synchronized method1(). Now, let’s see a program to prove our point.
49.Difference between wait() and wait(long timeout), What are thread states when these method are called?
wait()
When wait() method is called on object, it causes causes the current thread to wait until another thread invokes the notify() or notifyAll() method for this object.
When wait() is called on object - Thread enters from running to waiting state.
It waits for some other thread to call notify so that it could enter runnable state.
wait(long timeout)
wait(long timeout) - Causes the current thread to wait until either another thread invokes the notify() or notifyAll() methods for this object, or a specified timeout time has elapsed.
When wait(1000) is called on object - Thread enters from running to waiting state. Than even if notify() or notifyAll() is not called after timeout time has elapsed thread will go from waiting to runnable state.
50.How can you implement your own Thread Pool in java?
What is ThreadPool?
ThreadPool is a pool of threads which reuses a fixed number of threads to execute tasks.
At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.
ThreadPool implementation internally uses LinkedBlockingQueue for adding and removing tasks.
In this post i will be using LinkedBlockingQueue provide by java Api, you can refer this post for implementing ThreadPool using custom LinkedBlockingQueue.
Need/Advantage of ThreadPool?
Instead of creating new thread every time for executing tasks, we can create ThreadPool which reuses a fixed number of threads for executing tasks.
As threads are reused, performance of our application improves drastically.
How ThreadPool works?
We will instantiate ThreadPool, in ThreadPool’s constructor nThreads number of threads are created and started.
ThreadPool threadPool=new ThreadPool(2);
Here 2 threads will be created and started in ThreadPool.
Then, threads will enter run() method of ThreadPoolsThread class and will call take() method on taskQueue.
If tasks are available thread will execute task by entering run() method of task (As tasks executed always implements Runnable).
publicvoid run() {
. . .
while (true) {
. . .
Runnable runnable = taskQueue.take();
runnable.run();
. . .
}
. . .
}
Else waits for tasks to become available.
When tasks are added?
When execute() method of ThreadPool is called, it internally calls put() method on taskQueue to add tasks.
taskQueue.put(task);
Once tasks are available all waiting threads are notified that task is available.
51.What is significance of using ThreadLocal?
This question will test your command in multi threading, can you really create some perfect multithreading application or not. ThreadLocal is a class which provides thread-local variables.
What is ThreadLocal ?
ThreadLocal is a class which provides thread-local variables. Every thread has its own ThreadLocal value that makes ThreadLocal value threadsafe as well.
For how long Thread holds ThreadLocal value?
Thread holds ThreadLocal value till it hasn’t entered dead state.
Can one thread see other thread’s ThreadLocal value?
No, thread can see only it’s ThreadLocal value.
Are ThreadLocal variables thread safe. Why?
Yes, ThreadLocal variables are thread safe. As every thread has its own ThreadLocal value and one thread can’t see other threads ThreadLocal value.
Application of ThreadLocal?
ThreadLocal are used by many web frameworks for maintaining some context (may be session or request) related value.
In any single threaded application, same thread is assigned for every request made to same action, so ThreadLocal values will be available in next request as well.
In multi threaded application, different thread is assigned for every request made to same action, so ThreadLocal values will be different for every request.
When threads have started at different time they might like to store time at which they have started. So, thread’s start time can be stored in ThreadLocal.
Creating ThreadLocal >
private ThreadLocal<String> threadLocal = new ThreadLocal<String>();
We will create instance of ThreadLocal. ThreadLocal is a generic class, i will be using String to demonstrate threadLocal.
All threads will see same instance of ThreadLocal, but a thread will be able to see value which was set by it only.
How thread set value of ThreadLocal >
threadLocal.set( new Date().toString());
Thread set value of ThreadLocal by calling set(“”) method on threadLocal.
How thread get value of ThreadLocal >
threadLocal.get()
Thread get value of ThreadLocal by calling get() method on threadLocal.
See here for detailed explanation of threadLocal.
52.What is busy spin?
What is busy spin?
When one thread loops continuously waiting for another thread to signal.
Performance point of view - Busy spin is very bad from performance point of view, because one thread keeps on looping continuously ( and consumes CPU) waiting for another thread to signal.
Solution to busy spin -
We must use sleep() or wait() and notify() method. Using wait() is better option.
Why using wait() and notify() is much better option to solve busy spin?
Because in case when we use sleep() method, thread will wake up again and again after specified sleep time until boolean variable is true. But, in case of wait() thread will wake up only when when notified by calling notify() or notifyAll(), hence end up consuming CPU in best possible manner.
Program - Consumer Producer problem with busy spin >
Consumer thread continuously execute (busy spin) in while loop tillproductionInProcess is true. Once producer thread has ended it will make boolean variable productionInProcess false and busy spin will be over.
while(productionInProcess){
System.out.println("BUSY SPIN - Consumer waiting for production to get over");
}
53.Can a constructor be synchronized?
No, constructor cannot be synchronized. Because constructor is used for instantiating object, when we are in constructor object is under creation. So, until object is not instantiated it does not need any synchronization.
Enclosing constructor in synchronized block will generate compilation error.
Using synchronized in constructor definition will also show compilation error.
COMPILATION ERROR = Illegal modifier for the constructor in type ConstructorSynchronizeTest; only public, protected & private are permitted
Though we can use synchronized block inside constructor.
Read More about : Constructor in java cannot be synchronized
54.Can you find whether thread holds lock on object or not?
holdsLock(object) method can be used to find out whether current thread holds the lock on monitor of specified object.
holdsLock(object) method returns true if the current thread holds the lock on monitor of specified object.
55.What do you mean by thread starvation?
When thread does not enough CPU for its execution Thread starvation happens.
Thread starvation may happen in following scenarios >
Low priority threads gets less CPU (time for execution) as compared to high priority threads. Lower priority thread may starve away waiting to get enough CPU to perform calculations.
In deadlock two threads waits for each other to release lock holded by them on resources. There both Threads starves away to get CPU.
Thread might be waiting indefinitely for lock on object’s monitor (by calling wait() method), because no other thread is calling notify()/notifAll() method on object. In that case, Thread starves away to get CPU.
Thread might be waiting indefinitely for lock on object’s monitor (by calling wait() method), but notify() may be repeatedly awakening some other threads. In that case also Thread starves away to get CPU.
56.What is addShutdownHook method in java?
addShutdownHook method in java >
addShutdownHook method registers a new virtual-machine shutdown hook.
A shutdown hook is a initialized but unstarted thread.
When JVM starts its shutdown it will start all registered shutdown hooks in some unspecified order and let them run concurrently.
When JVM (Java virtual machine) shuts down >
When the last non-daemon thread finishes, or
when the System.exit is called.
Once JVM’s shutdown has begunnew shutdown hook cannot be registered neither previously-registered hook can be de-registered. Any attempt made to do any of these operations causes an IllegalStateException.
For more detail with program read : Threads addShutdownHook method in java
57.How you can handle uncaught runtime exception generated in run method?
We can use setDefaultUncaughtExceptionHandler method which can handle uncaught unchecked(runtime) exception generated in run() method.
What is setDefaultUncaughtExceptionHandler method?
setDefaultUncaughtExceptionHandler method sets the default handler which is called when a thread terminates due to an uncaught unchecked(runtime) exception.
setDefaultUncaughtExceptionHandler method features >
setDefaultUncaughtExceptionHandler method sets the default handler which is called when a thread terminates due to an uncaught unchecked(runtime) exception.
setDefaultUncaughtExceptionHandler is a static method method, so we can directly call Thread.setDefaultUncaughtExceptionHandler to set the default handler to handle uncaught unchecked(runtime) exception.
It avoids abrupt termination of thread caused by uncaught runtime exceptions.
Defining setDefaultUncaughtExceptionHandler method >
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
publicvoid uncaughtException(Thread thread, Throwable throwable) {
System.out.println(thread.getName() + " has thrown " + throwable);
}
});
58.What is ThreadGroup in java, What is default priority of newly created threadGroup, mention some important ThreadGroup methods ?
When program starts JVM creates a ThreadGroup named main. Unless specified, all newly created threads become members of the main thread group.
ThreadGroup is initialized with default priority of 10.
ThreadGroup important methods >
getName()
name of ThreadGroup.
activeGroupCount()
count of active groups in ThreadGroup.
activeCount()
count of active threads in ThreadGroup.
list()
list() method has prints ThreadGroups information
getMaxPriority()
Method returns the maximum priority of ThreadGroup.
setMaxPriority(int pri)
Sets the maximum priority of ThreadGroup.
59.What are thread priorities?
Thread Priority range is from 1 to 10.
Where 1 is minimum priority and 10 is maximum priority.
Thread class provides variables of final static int type for setting thread priority.
/* The minimum priority that a thread can have. */
publicfinalstaticintMIN_PRIORITY= 1;
/* The default priority that is assigned to a thread. */
publicfinalstaticintNORM_PRIORITY= 5;
/* The maximum priority that a thread can have. */
publicfinalstaticintMAX_PRIORITY= 10;
Thread with MAX_PRIORITY is likely to get more CPU as compared to low priority threads. But occasionally low priority thread might get more CPU. Because thread scheduler schedules thread on discretion of implementation and thread behaviour is totally unpredictable.
Thread with MIN_PRIORITY is likely to get less CPU as compared to high priority threads. But occasionally high priority thread might less CPU. Because thread scheduler schedules thread on discretion of implementation and thread behaviour is totally unpredictable.
setPriority()method is used for Changing the priority of thread.
getPriority()method returns the thread’s priority.
Multithreading and Synchronization is considered as the typical chapter in java programming. In game development company, mulithreading related interview questions are asked mostly. A list of frequently asked java multithreading interview questions are given below.
60.What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
- Threads share the same address space.
- Thread is lightweight.
- Cost of communication between process is low.
|