Thursday, June 18, 2015

101 Comprehensive Java Multi-Threading Interview Questions and Answers

Java Multi-Threading Interview Questions

1. What is concurrency in Java?

Two Hands working simultaneously

When we can execute multiple computations in parallel, we call this as concurrency. Dictionary definition goes like existing, happening, or done at the same time.

We can either use multiple cores on the same machine or use multiple machines to achieve this. Think of it like, either one person uses both hands or 2 person using one hand each for some work. Either ways we get 2 working hands.

2. What is a Thread?

Thread relates to running of a program. A Thread is a single chain of execution within a program.

Read More on Threads: What is a Thread?

Salient Features of a Thread

a) Thread is like a sub-process. Multiple thread paths can exist within a single process.

b) All threads share the same resources (memory, variables) within a process. This can result into conflict, hence needs to be handles carefully.

c) Apart from shared resources, each thread has its own stack space where it stores variables local to it.

d) One can argue that we can create multiple processes, then why is the need for multiple threads. You can read about it here. Multiple threads v/s Multiple processes.

3. What are the advantages of programs running with multiple threads?

It's quite straightforward an answer. What is advantages if we can use both hands simultaneously? We would able to finish ours tasks faster. Same is the case with multiple threads. They work in parallel and does not let single CPU to be idle. Also utilize multiple CPU's efficiently. In a single process, threads share the heap memory, Hence we do not need to allocate separate Heap for different Threads. 

4. Differentiate between Process and Thread?

Thread is like a sub-process. Multiple threads occur within a single process and share the Heap Memory. 

Process is a single program. It spawns a single Heap. Thread is like a light process and requires less resources than a Process as they share the resources within a Process.

5. Can a Process exist without a Thread?

No. Java program is executed with the main Thread. So a Process needs at least One Thread to execute.

6. What are the different ways we can create a Thread in Java?

There are couple of ways for creating a Thread in Java (actually there are more ways than that, but ultimately it boils down to these two ways). Either extend Class java.lang.Thread or implement Interface java.lang.Runnable. 

7. What are the methods inside Thread class to initiate the Thread?

There are two methods, start() and run(). 

start(): New Thread execution begins by start(). JVM in turn calls run() method.
run(): This should not be called directly if Thread Class is extended to create a Thread. This simply calls the run() method in the same thread and just executes the code in the same thread.

8. What do you understand by Daemon and User Threads?

When we write a code and create a Thread (either by extending Thread or implementing Runnable), it is called User Thread. When the all user Thread ends in a process, the JVM exits.

A thread running in background and does not stop JVM from exiting is called Daemon Thread. A classic example is the Garbage Collector, which is started by JRE and runs in the background.

9. Does Runnable Thread returns anything? What does Callable do?

Runnable and Callable are two Interfaces, which we implement to create a Task which is executed in a separate Thread. run() method in Runnable, does not return anything. call() method in Callable can return a Future object as result or even throw an Exception.  

10. Is there any way to access the current thread that we are working on?

Yes, There is a Thread.currentThread() method for that very reason. 

11. What are the different states of a Thread?

The States of a Thread in Java are as follows:

RUNNABLE: Thread executing in JVM (might not execute in OS, as OS might make it wait for the processor, say)

WAITING: Waiting ad infinitum for some other thread to perform some action. If current Thread callsObject.wait(), it is WAITING for some other thread to call Object.notify().

BLOCKED: Waiting to get monitor lock
  • Either waiting to enter synchronized block, or
  • In Waiting state of Current Thread, if some other thread calls Object.notify(), the Current Thread moves to BLOCKED state and fights for the monitor lock. If some other Thread gets the lock, current Thread goes back to WAITING state.)
  • Waiting for a specified time interval (Thread.sleep(TIMEOUT)) or
  • Waiting for some other Thread to call Object.notify() or for a specified time interval, whichever is shorter (Object.wait(TIMEOUT)).

12. How can we uniquely identify a Thread?

We have a char[] inside Thread class which stores name of the Thread. There is long Thread Id. They can be used to uniquely identify a Thread on the JVM.

13. What is Thread.sleep() used for?

Thread.sleep() is used for pausing the given Thread for a given time. Once the sleep time is over, Thread is scheduled and gets executed at next CPU cycle.

14. Why are Thread Groups used for?

Threads can be assigned to a given java.lang.ThreadGroup. The Threads assigned to a particular Thread Group can be made to behave similarly. They can be interrupted together. Their priority can be changed together.

A Thread can hold another ThreadGroup also and form tree like structure. However it has become obsolete overtime and should be avoided.

15. What does Thread Priority means?

Priority is defined as, the fact or condition of being regarded or treated as more important than others. Thread Class has an int member, priority. We can allocate a priority to a Thread from 1 to 10 (lower to higher priority). However which Thread will be executed first totally depends on Thread Scheduler of JVM. It can be that a higher priority Thread is the last one to be executed. Priorities are like an humble request to JVM. Whether it is accepted or rejected is totally JVM's prerogative.

16. What is Context Switching in Java?

One important concept to be understood before moving forward is Context Switching. When multiple processes share a single CPU, they fight for the CPU time. It is via context switching that each of them gets some CPU time slice. In very basic terms, one process should be switched out of CPU so that another process can run. Similar context switching can be understood at the JVM level for a single process which has many threads.

17. How does volatile variables helpful in Multi-threaded code?

Volatile variable guarantees to be in consistent state even without explicit synchronization. It promises that any write will happen before ant subsequent read. The read/write operation becomes atomic with volatile variables.

With the above definition in mind, we can visualize it's use in multi-threaded code, where consistence of shared variables is mandatory. Thus volatile variable can be used for share data (there are some limits to it). 

Read More: Volatile in Java

18. Explain Thread Scheduler/Thread Slicing.

This goes to the Operating System and you might have read it during OS course in College. Scheduler allocated CPU time-slices to Processes. Similarly Thread Scheduler allocated JVM time-slices to Threads. 

Time slicing is the process by which CPU time is allocated and divided among threads. The allocaion can be round robin, or based on priority of Thread etc.

19. Do you know how do Thread interacts among them?

Thread methods wait(), notify(), notify() are used to interact with each other about the status of the shared resource. 

20. What is Thread.join used for?

Thread join is used to pause the current Thread till the specified Thread (on which we call join) is over. If join all threads inside main, then main will be last thread to finish. 

21. What do we mean by Thread-Safety?

Thread-safe code means that the code will behave in a consistent manner when working with multiple threads. All read/writes will work as expected. A Class/Object can be thread-safe or not. Ex, Vector is thread-safe class. All methods take care that they don't interfere with each others working. Don't overlap and keeps the Vector values consistent.

22. Can we start a Thread twice?

No, A thread once started cannot be started again. If we try and invoke start() method twice, we get IllegalThreadStateException.

23. Can you write a Daemon Thread?

Daemon thread is a thread that runs in the background. It does not stop the JVM from terminating. We can write some sample code to mimic a daemon Thread as below. setDaemon(true) needs to be set.

24. Can we convert any user thread into daemon thread by setting setDaemon(true)?

No, once a thread is started, it cannot be converted to Daemon Thread. If we try and call setDaemon(true) on an already running Thread, we get IllegalThreadStateException.

25. Why are wait(), notify(), notifyAll() allocated to Object class and not in Thread class?

It is a common question in interviews. On the face of it, it seems to make more sense that wait(), notify() and notifyAll() are there in Thread. But they aren't. An Object is used as a monitor in Java, which can span across Threads. Threads need something to communicate with each other. Object monitor is that something. Now if you think, keeping these methods in Threads does not make that much sense.

26. Explain race condition in Java?

When different Threads race to get lock on the same Object, we call it Race condition. Suppose we want that Thread1 executes first and Thread2 executes after that. But when both Thread1 and Thread2 wants to get lock on the Monitor, and Thread2 gets lock first. This will result in an unexpected result as now Thread2 will be executed first and Thead1 after that.

27. Why are sleep() and yield() methods static?

Since these methods works on the current thread, hence there is no need to invoke them on other thread Objects from within another thread. Making them static means there is no scope of confusion in this regard. 

28. How does synchronized block/method fit with wait(), notify(), notifyAll(). Why is it mandatory to call these methods from inside synchronized?

When a Thread waits(), it waits on something. That something is the Monitor. That lock is taken by synchronized keyword. Then a Thread can wait() or notify() about the lock status of that Monitor. Hence we need to call them from inside synchronized block/method. If we don't do that code will throw IllegalMonitorStateException.

29. Have you encountered a situation when Exception has occurred in a Thread. Can you state your observation?

If the exception is not handled by try-catch inside the run() method, the thread will be stopped by JVM. So we need to handle the exceptions and write a good exception Handler. One such handler is UncaughtExceptionHandler, which can be registered with the Thread. In case of any Exception now, JVM knows to use the Handler registered.

30. Which one is better to use. Synchronized method or Synchronized block?

Synchronized Block is better as it takes the lock only for the short time and limited scope. Synchronized method() takes lock on the Object for the entire method execution.

31. What are the provisions in Java for thread-safe code?

We can use synchronization, atomic classes, volatile keyword, immutable classes, using Lock interface. Java also provides custom Thread safe classes also to be used.

32. Explain the concept of busy waiting.

Busy waiting, as the name suggests occurs when a Thread does some work while it keep occupying the processor. That active work is required to arrive at the decision if the Thread can relinquish the CPU. Check the sample code below:

33. How to prevent this waste of CPU time in busy wait?

It's quite simple. We can let Thread sleep for a give time instead of continuous check, as in the code below,

34. Explain ThreadLocal.

If we have some variables that are not thread-safe but we want to use them across Threads without synchronization, we can create a copy of those variables local to each thread and set()/get() them as required. They will be local to Thread and not shared across Threads. This way we can achieve thread-safety of objects which are expensive to create.

35. How will you share some data across Threads in Java?

To share data between two Threads, we use a shared Object. On Thread will store some data in that Object and the other Thread can read it And vice-versa. wait(), notify(), notifyAll() are used for this very purpose. Java has concurrent data-structures like Vectors/ConcurrentHashMap etc. for this very purpose.

36. How can we get Thread dump? 

Thread dump is a readable format of what is going inside the Process. It lists all the active threads of the JVM. Normally they are used to analyse deadlocks and other bottlenecks that are not quite evident by looking at the code. We can use jconsole, kill -3, jstack and other such tools.

37. Differentiate between notify() and notifyAll()?

Once Object.notify() is called, of all Threads that are WAITING on the same monitor object, one is awakened at random and is moved to BLOCKED state (Moved from waiting queue of object to entry queue of the object), where it tries to get the lock on monitor object. It has to fight with other Threads BLOCKED on the same Object. Once it gets the lock, it is scheduled to be executed by the CPU, again with no guarantees when.

If 10 Threads have called Object.wait() on the same object, Object.notifyAll(), awakens all 10 threads and move them in BLOCKED state where they fight with other BLOCKED Threads for the lock on the object  One of these 10 might get the lock (some other Thread which was BLOCKED to enter the  synchronized block, might just get the lock) and rest 9 go back to the WAITING state (in effect waiting Queue of the Object) till they get the next notify signal.

Read More: Object Wait()

38. What is Deadlock? How can we avoid it?

Deadlock occurs when two or more threads never progress. They are blocked till eternity. This happens when for example a cyclic locking occurs. Say,

  • Thread1 has lock on Object1 and wants lock on Object2. 
  • Thread2 has lock on Object2 and wants lock on Object1. 

Here both threads goes in a deadlock.

Below few situations when a deadlock can occur.

S No.
Mutual Exclusion
Resource can be accessed by only one thread a time.
Use optimistic locking rather than mutual exclusion
Held Resource
Thread trying to acquire resource already help by another Thread
Release all locks if Thread is not able to obtain all required Locks
Lack of Preemption
No way to release a resource if lock held for a long time by a Thread
Use timeout for an exclusive lock. This frees lock after given time.
Round wait
Two Threads waiting for each other to release the Lock on 2 different Objects.
Obtain exclusive locks in the same sequence across Threads.

Such deadlocks in a big code are really hard to identify and catch. We can take Thread dump and look for threads with BLOCKED state. Dig deep to find which resources that are waiting to get lock on. Then find the Thread which is holding the lock on that very Object. And the fix your code.

39. Is there any way to wake up a sleeping Thread?

Yes, we can interrupt() the thread that is sleeping. The thread will throw InterruptedException. So if we handle the InterruptedException in the run() function of the Thread, it can go on performing normally after that.

40. Explain FutureTask.

As per the javadoc, FutureTask is a cancellable  asynchronous computation. This provides implementation of Future, and methods to start/cancel/retrieve-result a computation. The FutureTask can be cancelled/re-started once computation is done. We can also query for the status of computation. FutureTask object can wrap a Callable/Runnable object. FutureTask can be submitted to an Executor since it implements Runnable.

41. Can Java guarantee that Thread relinquishes for the specified time by Thread sleep?

No. Thread.sleep can only guarantee that Thread will relinquish at least for the give time. Post that it depends on Scheduler when it schedules the Thread for execution. Hence it does guarantee and not be used for real time execution. 

42. How are Cyclic Barrier and CountDownLatch different?

CountDownLatch become unusable once count reaches zero. However CyclicBarrier can be reused even after barrier is broken.

Read More: Cyclic Barrier v/s CountDownLatch

43. Can we schedule a task to run after some time? 

Yes, Java provides java.util.Timer class for this very purpose. With Timer class, we can schedule a Thread for execution after some time. It can be  a one time execution or repeated execution at regular intervals. TimerTask Class (implements Runnable interface) can be extended to create the TimerTasks that can be scheduled using Timer class.

44. What does interrupted() and isInterrupted() stands for?

They both test if the current Thread has been interrupted. They both return true if the Thread has been interrupted; false otherwise.

They differ in the sense that static method interrupted() clears the interrupted status. Non-static method isinterrupted(), do no such thing. If a thread is interrupted and interrupted() is called two times one after the another, if first call returns true, 2nd call will return false. With isInterrupted(), it will be true both times.

45. What is a ThreadPool in Java?

Thread Pool manages pool of threads which are used to process some task. A queue inside Thread Pool holds tasks that are to be executed. A pool of Threads execute the Runnable Tasks from the queue one by one.

46. Do we need to override run() method while extending Thread?

As such it is not mandatory. But not overriding serves no purpose. As run() function is where the code that the Thread is to process goes. If we don't override and call thread.start(0, then nothing happens. Thread ends without doing anything.

47. How will you handle InterruptedException from a Thread?

Normally functions like sleep() and join() end up throwing InterruptedException, if the Thread is interrupted (when the Thread was taking a rest). Interrupt signals something trigger that something has gone wrong. We end up catching and logging the Exception inside the run().

48. What are the advantages of check condition in the loop. while waiting?

A waiting thread can get false wake up calls. Say a notifyAll(), which notifies all the threads. Since we don't have a feature to notify a particular Thread, we end up notifying all. Only a particular Thread needs to be awoken. This can be achieved by check condition and a loop. When a waiting Thread is notified, it should be inside a loop and go to the condition to check if should vie for the CPU cycle or it should go back waiting.

Once we have a conditional wait, this might not be required. Read More: Conditional Wait Missing.

49. What is the difference between concurrent collections and synchronized collections in Java?

A revolution took place when java.util.concurrent was introduced in Java in Java 1.5.

Synchronized collections are thread-safe like Vectors/HashTables or synchronized(HashMap), which takes a lock on the entire Object every time a Thread access them. This makes processing slower.

Concurrent Collections like ConcurrentHashMaps are also thread-safe but they are intelligent. They take lock on part of the Object. The processing is faster in this case and less contentions.

50. How is Lock Interface better than synchronization?

Locks are more flexible than synchronization. Locks are better in the following ways:

  1. Thread can be made responsive to interruption while waiting on a Lock object.
  2. While trying to acquire lock, Thread can return immediately or after a timeout if Lock can;'t be acquired.
  3. We can have Fair Locks.
  4. Locks can be acquired in different orders as required.

51. Explain shutdown hook in Java.

The thread which gets executed when JVM shuts down is called Shutdown Hook. We can register a shutdown hook by Runtime.getRuntime().addShutdownHook ().

52. How can we achieve atomic operation using Java Concurrency API?

Atomic operations are ones which are executed as a single unit. They are either executed completely or not executed at all. They ensure there is not data inconsistency. Take an example int a = 1;a++ . Here a++ is not atomic operation as at hardware level, it comprises of Three steps. Copy, Increment, copy back. This can result in data inconsistency in case of Multi-threaded environment.

We have java.util.concurrent.atomic.AtomicInteger and other such classes which provide Atomicity of operation without synchronization.

53. When we call synchronized method, On what Object does it takes lock?

Synchronized Method takes lock on this. The Calling Object. Lock is released once the method ends or throws and Exception.

54. In the context of multi-threading, how would you differentiate Heap and Stack memory?

A process has its own Heap Memory Space. Heap is shared by all Threads.

Each thread inside the process has its own Thread Stack. On Thread stack, variables local to the Thread, method params, call stack are stored. These are not visible to other Threads.

55. Can we have a synchronized constructor?

No, we can't have. It is not allowed. There is not need actually. A constructor is not required to be accessed by different threads. Only the creating Thread needs to call the constructor. Other threads are free to use or abuse the Object created.

56. Is an intrinsic lock reentrant?

All Intrinsic locks are reentrant. They can be accessed by same Thread over and over again. No need to check if we already have a lock on the same Object.

57. For intrinsic Locks, can we use primitive values?

No, primitive values are not allowed as they don't extend Object class.

58. What is Executors Framework?

java.util.concurrent.Executor interface is used for Executor framework for scheduling execution and controlling asynchronous tasks. We can't just go on creating threads. ThreadPool is a way to go, where threads are pooled together and tasks re-use same threads. Executor framework facilitate this process.

59. Solve Producer Consumer problem with code.

Consider a factory. It produces products and we as Consumers consumes the product. One Thread produce tasks, and other Thread consumes the tasks. This needs a shared object, wait/notify or some Concurrent data-structure. This can be solved in a number of ways. Please check the solution using BlockingQueue.

60. How can you implement a deadlock detection?

We can try it by modelling and monitoring all exclusive locks as direct graphs. A system can search for two threads in this graph that are waiting on each other. Some kind of exception can be thrown from one of the Thread in such a case and break this deadlock.

61. What is a livelock?

Result is same as deadlock. Threads take some action to resolve a deadlock by some action which still results in a deadlock. State of threads keeps on changing but no progress. Imagine a scenario of "you first", Both tries to take the stairs, and both hesitates. This goes on and on and on.

62. How to know if the Thread holds a lock?

There is a method holdsLock() in Thread class. This returns true is current thread holds a lock; false otherwise.

63. What is BlockingQueue.

This interface extends Queue interface (which in turn extends Collection interface). All implementations of Blocking Queue are Thread-Safe. Blocking terminology comes from the fact that BlockingQueue provides methods which can make the calling Thread to Wait before proceeding further. Read More: Blocking Queue

64. What does yield() do?

Yield() requests current thread to release the CPU. Who gets the CPU cycle is out of applications control. It may very well be that same threads get the CPU back.

65. What is the difference between sleep() and wait().

Oxford Dictionary defines wait and sleep as below:
wait: delay action until (someone) arrives or is ready.
sleep: a condition of body and mind which typically recurs for several hours every night, in which the nervous system is relatively inactive and consciousness practically suspended

Read More: Sleep v/s Wait

66. Explain ForkJoin Framework in Java.

ForkJoin framework in Java 1..7 helps fully utilize of multiple processors. Work that can be divided into smaller pieces can utilize ForkJoin. Key point is that Threads that are idle tries to snatch a sub-task from other threads.
Read More:

67. Concurrence Level of ConcurrentHashMap?

Concurrence Level of ConcurrentHashMap is an optional param. It's default value is 16. It is the number of regions, map is divided into.

68. What is Thread starvation?

Thread starvation occurs in case a Thread (lower priority), is hogged by another thread (higher priority). Lower priority Thread may not get CPU for a long time, hence it will STARVE without CPU time slice and will not be able to finish work assigned to it.

69. What are fair locks?

A lock which grants access to the thread which has been waiting for the longest time, Thus it tries to do a fair allocation, An example is ReentrantLock. Waiting time is taken into account.

70. What is an Immutable Class in Java?

Immutable Object once created cannot be modified. A class which has no setters and no public variables such that it cannot be modified once instantiated is called Immutable Class. It is used a lot in multi-threaded environment as it can be shared around without any synchronization.

71. What is the ThreadPool is filled completely and we submit a task to it?

We get a RejectedExecutionException. We can write a custom handler for that if we want.

72. What is different between submit() and execute() method thread pool in Java?

Both methods are used to submit a task to Thread Pool. execute(Runnable) does not return anything, while submit(Runnable or Callable) can return a Future object with the result of the computation .

73. What is a CountDownLatch?

This is used when we want Threads to wait and to be executed together after certain other Threads reach the same state, such that they all can no start together. A synchronized counter is initialized by the number of threads. Each Thread that reaches the give state, decrements the counter. Once the Counter reaches zero, all the Threads were start together.

74. What is a Semaphore?

java.util.concurrent.Semaphore maintains number of permits that have to be acquired by competing threads. Semaphore can control the number of threads accessing a resource at the same time. Permit is allocated by acquire() function. Once the computation finishes, the Thread can return back the permit to the Semaphore.

75. What is the function to access Thread Pool used for Parallel Stream Operations?

ForkJoinPool.commonPool() is the used to access the thread pool used for Parallel Stream Operations. commonPool.getParallelism() gives us the level of parallelism too.

76. Can a Thread Pool process Stream Operations?

Yes, with Java 8, parallelStream() method from Collections is used to create a stream that is processed by Thread Pool.

77. Differentiate between RecursiveTask and RecursiveAction.

RecursiveAction, does not return any value after compute() unlike RecursiveTask which returns a computed value.

78. What does Fork/Join achieve?

Fork/Join has a ThreadPool, ForkJoinPool which executes ForkJoinTask which in turn has two functions fork() and join(). fork() does asynchronous execution, while join() waits for the result of a computation. Fork/Join helps us implement divide and conquer algorithms, where we can divide a complex problem into similar sub-problems.

79. Give an example using ForkJoin.

ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new SumArray(array, 0, array.length));
SumArray extends ForkJoinTask (RecursiveTask/RecursiveAction). See here the analogy with a simple ThreadPoolExecutor, which requires a Runnable/Callable task.
The SumArray needs to have function compute() (analogous to run()) which will be called post pool.invoke() (analogous to execute()). Also a function invokeAll() is available to the SumArray, which is just like invoke, but takes multiple ForkJoinTasks and assign them to the ForkJoinPool.
protected void compute() {
        if(length < 1000 ) { //No need to Split the Task
        //Need to split the Task
        invokeAll(new SumArray(array, 0, length/2),
                new SumArray(array, length/2, length));

80. How to get a synchronized instance of any Collection/List/Map?

Collection: synchronizedCollection(Collection)
List: synchronziedList(List)
Map: synchronizedMap(Map)

This will return a thread-safe object backed by the given instance.

81. Can we force start a Thread in Java?

No. There is no method to force start a Thread. The start of  thread is solely a prerogative of Thread Scheduler of the JVM. We might have an API for this in coming releases.

82. How to create a double checked locking of Singleton?

A very popular question. You should write it on piece of paper a number of times. Check the code below. Check of null is done twice. This is a Thread Safe Singleton. No chance Two Threads creating two Instances. Check code below,

83. What other ways to create a Thread Safe Singleton apart from double checking?

We can use Enum or Initializing static field. See below:

84. What is the difference between HashMap and HashTable?

HashMap is not thread safe. HashTable is thread safe. All methods are synchronized in HashTable. In single-threaded applications we should better use HashMap as it is less expensive.

85. What is the java.util.concurrent.Future used for?

Some asynchronous computation which is yet not finished and result will be available later, uses Future to hold the result. We can retrieve the result via get() which blocks until the result is available.

86. What happens if an exception is thrown from inside the synchronized block?

See, however we exit the synchronized block, the lock is released. Simple! This is as against in Lock, which does not release the lock and we have to code it inside finally.

87. How different are volatile and atomic variable in Java?

They both are used in multi-threaded programs. Volatile does not guarantee atomicity, just says that a write will happen before any subsequent write. If we declare a variable volatile, does not make variable++ atomic. AtomicInteger promises atomicty. It has a getAndIncrement() method which is an atomic increment method.

88. What is ReadWriteLock in Java?

It maintains two locks, one for read-only and one for writing. Read Lock can be held by multiple reader threads, when there are no writers. Only one Thread can get Write Lock.

89. Executor v/s Executor Service?

Execute has only into one function execute(Runnable). ExecutorService is an extension of Executor and provides additional methods to allow submitting Runnable, await termination of all sumbitteed tasks etc.

90. Object Pooling. Is it always helpful?

Object Pooling makes sense  as we can use already created Object ans saves time required to create a new Object. It is fine for Single Threaded program.

For multi-threaded program, the Object pool needs to be synchronized which incurs additional costs. It ends up charging more than it pays.

91. Whatte is Lock Splitting?

Instead of having method level lock. We can have a function which performs three steps which depends on separate part of Data. We can have three blocks synchronized on different Monitors/Take lock on different Objects. This is an example of Lock Splitting.

92. What is Lock Stripping?

This is a technique where we use different locks to guard different parts of the same data structure. Like in ConcurrentHashMap. Different locks are used to guard different buckets. Hence multiple threads can modify this data structure simultaneously.

93. How does AtomicInteger works internally?

AtomicInteger works by CAS (compare and swap). Processor provides a separate instruction, which updated the register of the value of the register is equal to the current value. This helps if register gets updated by another thread in the meanwhile. Our update operation fails as the value is different from current value (read earlier).

94. How can we control stack size of a Thread?

It cane done using JVM options -Xss.

95. Differentiate between Preemptive scheduling and Time slicing.

Preemptive scheduling schedules the highest priority task first, till it is complete or an higher priority task comes.

Time slicing, schedules tasks for a predefined slice of time, after which it enters a pool of ready tasks,

96. How synchronized keyword works differently with static and non-static function?

With a non-static method, the lock is on the Object. With static lock is obtained on the Class. Since these two locks are separate, Two different threads can access these two functions simultaneously.

97. What is the initial priority of a Thread which is newly created?

The priority of the Thread which is newly created is equal to the priority of the thread that has created it.

98. Can we override start method of a Thread?

Yes, it can be don. But we should avoid doing it contains code to create a new executable thread. It is a custom code which should not be tinkered with unless one has proper understanding.

99. What is a Thread Leak?

It occurs if a program does not release references to a Thread Object in a proper way. It results in some object not getting garbage collected and number of unused Thread growing overtime. This may cause application to slow down or hang with time.

100. Can you differentiate between Concurrency and Parallelism?

Parallelism is the concept of dividing computation into sub-computation which cab be executed in parallel and does not share same process space.

Concurrency is the concept when we have multiple threads within the same process These threads might fight for same shared process or not.

101. Are Threads always lightweight processes?

A tricky question. Answer is No. When threads are part of the same process they are lightweight process. If they belong to different Process and are executing together, they are heavyweight process.

No comments:

Post a Comment