InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What Are Possible Use Cases For Java.lang.threadlocal? |
|
Answer» Instances of ThreadLocal can be used to transport information THROUGHOUT the application WITHOUT the need to PASS this from method to method. Examples would be the TRANSPORTATION of security/login information within an INSTANCE of ThreadLocal such that it is accessible by each method. Another use case would be to transport transaction information or in general objects that should be accessible in all methods without passing them from method to method. Instances of ThreadLocal can be used to transport information throughout the application without the need to pass this from method to method. Examples would be the transportation of security/login information within an instance of ThreadLocal such that it is accessible by each method. Another use case would be to transport transaction information or in general objects that should be accessible in all methods without passing them from method to method. |
|
| 2. |
What Is The Purpose Of The Class Java.lang.threadlocal? |
|
Answer» As memory is shared between different threads, THREADLOCAL PROVIDES a way to store and retrieve values for each thread separately. Implementations of ThreadLocal store and retrieve the values for each thread INDEPENDENTLY such that when thread A stores the value A1 and thread B stores the value B1 in the same instance of ThreadLocal, thread A later on retrieves value A1 from this ThreadLocal instance and thread B retrieves value B1. As memory is shared between different threads, ThreadLocal provides a way to store and retrieve values for each thread separately. Implementations of ThreadLocal store and retrieve the values for each thread independently such that when thread A stores the value A1 and thread B stores the value B1 in the same instance of ThreadLocal, thread A later on retrieves value A1 from this ThreadLocal instance and thread B retrieves value B1. |
|
| 3. |
Provide An Example Why Performance Improvements For Single-threaded Applications Can Cause Performance Degradation For Multi-threaded Applications. |
|
Answer» A prominent example for such optimizations is a List implementation that HOLDS the number of elements as a separate variable. This improves the PERFORMANCE for single-threaded applications as the size() operation does not have to iterate over all elements but can return the CURRENT number of elements directly. Within a multi-threaded APPLICATION the ADDITIONAL counter has to be guarded by a lock as multiple concurrent threads may insert elements into the list. This additional lock can cost performance when there are more updates to the list than invocations of the size() operation. A prominent example for such optimizations is a List implementation that holds the number of elements as a separate variable. This improves the performance for single-threaded applications as the size() operation does not have to iterate over all elements but can return the current number of elements directly. Within a multi-threaded application the additional counter has to be guarded by a lock as multiple concurrent threads may insert elements into the list. This additional lock can cost performance when there are more updates to the list than invocations of the size() operation. |
|
| 4. |
What Is The Difference Between Hashmap And Hashtable Particularly With Regard To Thread-safety? |
|
Answer» The methods of Hashtable are all SYNCHRONIZED. This is not the case for the HashMap IMPLEMENTATION. HENCE Hashtable is thread-safe WHEREAS HashMap is not thread-safe. For single-threaded applications it is therefore more efficient to use the “NEWER” HashMap implementation. The methods of Hashtable are all synchronized. This is not the case for the HashMap implementation. Hence Hashtable is thread-safe whereas HashMap is not thread-safe. For single-threaded applications it is therefore more efficient to use the “newer” HashMap implementation. |
|
| 5. |
How Can We Access The Thread Pool That Is Used By Parallel Stream Operations? |
|
Answer» The THREAD pool used for parallel STREAM operations can be accessed by ForkJoinPool.commonPool(). This WAY we can query its LEVEL of parallelism with commonPool.getParallelism(). The level cannot be changed at runtime but it can be configured by PROVIDING the following JVM parameter: -Djava.util.concurrent.ForkJoinPool.common.parallelism=5. The thread pool used for parallel stream operations can be accessed by ForkJoinPool.commonPool(). This way we can query its level of parallelism with commonPool.getParallelism(). The level cannot be changed at runtime but it can be configured by providing the following JVM parameter: -Djava.util.concurrent.ForkJoinPool.common.parallelism=5. |
|
| 6. |
Is It Possible To Perform Stream Operations In Java 8 With A Thread Pool? |
|
Answer» Collections PROVIDE the METHOD parallelStream() to create a stream that is processed by a thread pool. ALTERNATIVELY you can call the intermediate method PARALLEL() on a given stream to CONVERT a sequential stream to a parallel counterpart. Collections provide the method parallelStream() to create a stream that is processed by a thread pool. Alternatively you can call the intermediate method parallel() on a given stream to convert a sequential stream to a parallel counterpart. |
|
| 7. |
What Is Time Slicing? |
|
Answer» Timeslicing is the method of ALLOCATING CPU TIME to individual THREADS in a PRIORITY schedule. Timeslicing is the method of allocating CPU time to individual threads in a priority schedule. |
|
| 8. |
Name The Methods Available In The Thread Class. |
| Answer» | |
| 9. |
Can You Tell Some Ways In Which A Thread Can Enter The Waiting State? |
|
Answer» A THREAD can ENTER the waiting state by the following WAYS:
A thread can enter the waiting state by the following ways: |
|
| 10. |
What Is The Difference Between Pre Emptive Scheduling And Time Slicing? |
Answer»
|
|
| 11. |
Explain The Method Of Thread Class With Example. |
Answer»
For example { For example { |
|
| 12. |
What Is Thread Leak? |
Answer»
To overcome this PROBLEM we can do the following To overcome this problem we can do the following |
|
| 13. |
What Happens If We Invoke Run Method Without Calling The Start Method For A Thread Instance? |
|
Answer» 1.If we instantiate a thread it is CALLED in new state until the Start() method is called. 1.If we instantiate a thread it is called in new state until the Start() method is called. |
|
| 14. |
Explain The Method Of Runnable Interface With Example. |
Answer»
|
|
| 15. |
What Are The Methods Of The Thread Class Used To Schedule The Threads? |
|
Answer» The METHODS of the thread CLASS used to SCHEDULE the threads are as follows:
The methods of the thread class used to schedule the threads are as follows: |
|
| 16. |
How Do You Debug Your Application For Issues When Multiple Threads Are Being Executed? |
|
Answer» Following are some way to debug issues in multi-threaded applications in Java.
Following are some way to debug issues in multi-threaded applications in Java. |
|
| 17. |
What Is Starvation? |
Answer»
|
|
| 18. |
What Is The Difference Between Wait() And Sleep()? |
Answer»
|
|
| 19. |
What Is A Volatile Keyword? |
|
Answer» In GENERAL each THREAD has its own copy of VARIABLE, such that one thread is not concerned with the VALUE of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a METHOD is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. |
|
| 20. |
What Is The Difference When The Synchronized Keyword Is Applied To A Static Method Or To A Non Static Method? |
|
Answer» When a SYNCH non static method is called a lock is obtained on the OBJECT. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class don’t INTERFERE with each other. It means, a thread accessing a synch non static method, then the other thread can ACCESS the synch static method at the same time but can’t access the synch non static method. When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class don’t interfere with each other. It means, a thread accessing a synch non static method, then the other thread can access the synch static method at the same time but can’t access the synch non static method. |
|
| 21. |
What Is Use Of Synchronized Keyword? |
|
Answer» synchronized keyword 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 there are multiple threads TRYING to access the same method then other threads have to WAIT for the EXECUTION of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g. synchronized keyword 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 there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g. |
|
| 22. |
What Are The Different States Of A Thread's Life Cycle? |
|
Answer» The different states of threads are as follows: The different states of threads are as follows: |
|
| 23. |
If Code Running Is A Thread Creates A New Thread What Will Be The Initial Priority Of The Newly Created Thread? |
|
Answer» When a code running in a THREAD CREATES a new thread OBJECT, the PRIORITY of the new thread is set equal to the priority of the thread which has created it. When a code running in a thread creates a new thread object, the priority of the new thread is set equal to the priority of the thread which has created it. |
|
| 24. |
What Happens When Start() Is Called? |
|
Answer» A NEW thread of EXECUTION with a new call STACK STARTS. The state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run. A new thread of execution with a new call stack starts. The state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run. |
|
| 25. |
What Happens If A Start Method Is Not Invoked And The Run Method Is Directly Invoked? |
|
Answer» If a thread has been INSTANTIATED but not started its is SAID to be in NEW state. Unless until a start() method is invoked on the instance of the thread, it will not said to be ALIVE. If you do not CALL a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread. If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread. |
|
| 26. |
What Do You Mean By An Atomic Operation? |
|
Answer» In programming, an atomic operation is one that effectively happens all at once. An atomic operation cannot stop in the MIDDLE: it either happens completely, or it doesn’t happen at all. No SIDE effects of an atomic operation are visible until the action is complete.
Atomic actions cannot be INTERLEAVED, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. In programming, an atomic operation is one that effectively happens all at once. An atomic operation cannot stop in the middle: it either happens completely, or it doesn’t happen at all. No side effects of an atomic operation are visible until the action is complete. Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. |
|
| 27. |
What Happens When An Uncaught Exception Occurs In The Run() Method? |
|
Answer» When an unchecked exception has occurred in the run() method, the thread is STOPPED by the JAVA Virtual Machine. It is possible to CATCH this exception by REGISTERING an instance that implements the interface UncaughtExceptionHandler as an exception handler. When an unchecked exception has occurred in the run() method, the thread is stopped by the Java Virtual Machine. It is possible to catch this exception by registering an instance that implements the interface UncaughtExceptionHandler as an exception handler. |
|
| 28. |
How Can You Access The Current Thread In Java? |
|
Answer» The CURRENT THREAD can be accessed by calling the STATIC METHOD currentThread() of the java.lang.Thread class. E.g. Thread.currentThread().getName(). The current thread can be accessed by calling the static method currentThread() of the java.lang.Thread class. E.g. Thread.currentThread().getName(). |
|
| 29. |
Why Thread Communication Methods Wait(), Notify() And Notifyall() Are In Object Class? |
|
Answer» In JAVA, wait and notify methods acts as synchronization utility and are essential methods for inter thread communication. HENCE these methods are defined in Object class so that EVERY object will have access to it. Also every Object has a monitor and Locks are made available on PER Object basis. This is ANOTHER reason why wait and notify is declared in Object class rather then Thread class. In Java, wait and notify methods acts as synchronization utility and are essential methods for inter thread communication. Hence these methods are defined in Object class so that every object will have access to it. Also every Object has a monitor and Locks are made available on per Object basis. This is another reason why wait and notify is declared in Object class rather then Thread class. |
|
| 30. |
How Can You Ensure All Threads That Started From Main Must End In Order In Which They Started? |
|
Answer» We can use JOIN() method to ENSURE all THREADS that started from main will END in order in which they started and also main should end in last. We can use join() method to ensure all threads that started from main will end in order in which they started and also main should end in last. |
|
| 31. |
What Is The Difference Between Notify() And Notifyall()? |
|
Answer» notify() method wakes up a single THREAD that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is random and OCCURS at the discretion of the implementation. NOTIFYALL() wakes up all threads that are waiting on this object’s monitor. A thread WAITS on an object’s monitor by calling one of the WAIT methods. notify() method wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is random and occurs at the discretion of the implementation. notifyAll() wakes up all threads that are waiting on this object’s monitor. A thread waits on an object’s monitor by calling one of the wait methods. |
|
| 32. |
What Does The Join() Method In Thread Class Do? |
|
Answer» The join METHOD allows one THREAD to wait for the COMPLETION of another. If t is a Thread OBJECT whose thread is currently executing, t.join() causes the current thread(the thread which calls t.join(), MOSTLY the main thread) to pause execution until t’s thread terminates. The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t.join() causes the current thread(the thread which calls t.join(), mostly the main thread) to pause execution until t’s thread terminates. |
|
| 33. |
What Does Yield Method Of Thread Class Do? |
|
Answer» yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute. If there is no waiting thread or all the waiting threads have a LOWER priority than the CURRENT thread, then the same thread will continue its execution. When the yielded thread will GET the CHANCE for execution is decided by the thread scheduler WHOSE behavior is platform dependent. yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute. If there is no waiting thread or all the waiting threads have a lower priority than the current thread, then the same thread will continue its execution. When the yielded thread will get the chance for execution is decided by the thread scheduler whose behavior is platform dependent. |
|
| 34. |
What Is Volatile In Java? |
|
Answer» VOLATILE is a special modifier which is used to indicate that a variable’s value will be modified by different threads. The volatile keyword will mark a Java variable as “being stored in main memory”. The value of this variable will never be cached locally: all reads and WRITES will go straight to “main memory”. Volatile variable GUARANTEES that a write will happen before any subsequent read. Access to the variable ACTS as THOUGH it is enclosed in a synchronized block. volatile is a special modifier which is used to indicate that a variable’s value will be modified by different threads. The volatile keyword will mark a Java variable as “being stored in main memory”. The value of this variable will never be cached locally: all reads and writes will go straight to “main memory”. Volatile variable guarantees that a write will happen before any subsequent read. Access to the variable acts as though it is enclosed in a synchronized block. |
|
| 35. |
What Is Difference Between User Thread And Daemon Thread? |
|
Answer» By DEFAULT a thread created in a JAVA program is always a user thread however we can make it daemon by calling setDaemon(true) method, if NEEDED. A daemon thread runs in the background and doesn’t prevent JVM from terminating. As soon as all user thread finishes execution, Java program or JVM terminates itself, JVM doesn’t wait for daemon thread to finish their execution. As soon as last non daemon thread finished, JVM terminates no matter how many Daemon thread exists or RUNNING INSIDE JVM. By default a thread created in a Java program is always a user thread however we can make it daemon by calling setDaemon(true) method, if needed. A daemon thread runs in the background and doesn’t prevent JVM from terminating. As soon as all user thread finishes execution, Java program or JVM terminates itself, JVM doesn’t wait for daemon thread to finish their execution. As soon as last non daemon thread finished, JVM terminates no matter how many Daemon thread exists or running inside JVM. |
|
| 36. |
Explain About Thread Priority? |
|
Answer» EVERY thread has a PRIORITY, usually higher priority thread gets precedence in execution but it DEPENDS on Thread Scheduler implementation that is OS dependent. We can specify the priority of thread using Thread’s setPriority(INT) method but it doesn’t guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int WHOSE value varies from 1 to 10 where 1 is the lowest priority and 10 is the highest priority. Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS dependent. We can specify the priority of thread using Thread’s setPriority(int) method but it doesn’t guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int whose value varies from 1 to 10 where 1 is the lowest priority and 10 is the highest priority. |
|
| 37. |
How Does Thread Communicate With Each Other? |
|
Answer» Threads can COMMUNICATE using wait(), notify() and notifyAll() METHODS. Read this post to understand INTER THREAD communication. Threads can communicate using wait(), notify() and notifyAll() methods. Read this post to understand inter thread communication. |
|
| 38. |
Can We Call Run() Method Of A Thread Class? |
|
Answer» YES, we can call run() method of a Thread CLASS but it will behave LIKE a normal method and a new thread will not be created to execute the run() method. In this CASE the run() method will be executed in the same thread which called the run method. To actually execute it in a new Thread, we need to start it USING Thread.start() method. Yes, we can call run() method of a Thread class but it will behave like a normal method and a new thread will not be created to execute the run() method. In this case the run() method will be executed in the same thread which called the run method. To actually execute it in a new Thread, we need to start it using Thread.start() method. |
|
| 39. |
What Is The Difference Between Thread And Process In Java? |
Answer»
|
|