Prev Next

Java / Java Multithreading

1. Multitasking. 2. Multiprogramming/Multiprocessing. 3. Basic units of execution in concurrent programming. 4. Is concurrency possible on simple single processor systems without multiple processors? 5. Define Processes. 6. Define Threads. 7. What is the default thread of every Java application? 8. When does Thread Interference occur? 9. Thread Objects. 10. How do you create a Thread? 11. Which approach is recommended? 12. Does Thread class implements Runnable? 13. What is the signature of Thread run() method? 14. Define synchronization. 15. Can a thread be interrupted when it is in sleep? 16. Does sleep() method throws any Exception? 17. Can the start method be called twice on the same Thread? (OR) Can the start() method invoked again on the same thread object after start() been called first time? 18. Why do we call Thread.start() method which in turns calls run method? 19. Consumer Producer problem. 20. Difference between Thread.interrupted() and Thread.isInterrupted(). 21. Give few example from Java API that throws InterruptedException. 22. Best practice for "DO Nothing" Strategy for InterruptedException. 23. Thread.sleep method() 24. How do you interrupt an thread that does not call any method that throws InterruptedException? 25. join() method. 26. Interrupts 27. is join() a overloaded method? 28. An example for join(long milliseconds). 29. How do you interrupt an thread that does not call any method that throws InterruptedException? 30. Explain the interrupt mechanism. 31. Can run() method throw exception? 32. Difference between sleep and wait method in Java. 33. Is ++ (increment) operator thread-safe in Java? 34. What is thread starvation? 35. Does pressing Control-C causes InterruptedException in Java? 36. What is livelock in multithreading? 37. Explain race condition in multithreading. 38. What causes starvation in threads? 39. Difference between deadlock and livelock in Java multithreading. 40. What is Slipped Condition in multithreading? 41. What is Intrinsic Lock in Java multithreading? 42. Explain Guarded Blocks in Java. 43. What is BLOCKED state of a thread? 44. Different states of a Java thread. 45. Difference between thread state WAIT and BLOCKED. 46. Difference between synchronizing a static method and a non static method in Java. 47. What is reentrant synchronization in Java? 48. What is Reentrant lock in Java? 49. Can a thread hold more than one lock at the same time? 50. Difference between synchronized method and synchronized block in Java. 51. What is Runnable in Java? 52. Difference between start and run methods in Java Thread. 53. Define Critical section in Java multi-threading. 54. Explain IllegalMonitorStateException in Java multi-threading. 55. What is Spurious Wakeups in Java threads? 56. What is Daemon thread in Java? 57. Difference between Daemon and Non Daemon thread in Java. 58. Difference between a wait() and sleep() in Threads. 59. Difference between concurrency and parallelism. 60. Explain wait(), notify() and notifyAll() methods in Java threading. 61. Can a thread wait on multiple objects in Java? 62. What is mutex in Java? 63. Explain semaphore in Java. 64. Difference between Mutex and Semaphore in Java. 65. Difference between notify and interrupt in Java. 66. Difference between notify and notifyAll in Java. 67. When the lock is released after notify/notifyAll is called? 68. Why do we use ReentrantLock over synchronized (this)? 69. Define Liveness in Java Thread. 70. How threads communicate with each other? 71. Difference between synchronized and volatile keyword in Java. 72. Explain Thread Priority. 73. What is Thread Scheduler? 74. Define time slicing. 75. Define context-switching in multi-threading. 76. Which is preferred - Synchronized method or Synchronized block? 77. Why wait, notify and notifyAll are declared in Object class and not in Thread class? 78. What is Thread Group in Java? 79. Explain setUncaughtExceptionHandler method of Java Thread class. 80. What is Thread dump? 81. Explain about jstack tool. 82. How to debug and analyse Thread deadlock? 83. Can we not override run method when we extend Thread class? 84. Define Java thread pool. 85. Advantages of using threadpool. 86. What are atomic classes in Java Concurrency API? 87. What is Lock interface in Java Concurrency API? 88. Define preemptive scheduling. 89. What is the priority for Daemon threads? 90. Explain yield() method of a thread. 91. Can 2 threads call different synchronized instance methods of same Object? 92. What is thread leak in Java? 93. What is CountDownLatch in Java? 94. Applications of CountDownLatch in Java thread. 95. Explain CyclicBarrier in Java thread. 96. Difference between wait-notify and CountDownLatch. 97. How do you create an immutable class in Java? 98. What is the purpose of the class java.lang.ThreadLocal? 99. Explain volatile keyword in Java. 100. Explain fork/join framework in Java thread. 101. Explain Fork-Join framework API. 102. Explain Exchanger in Java thread. 103. Difference between ReadLock and WriteLock in Java ReentrantReadWriteLock. 104. General practice for releasing lock while using Lock implementation in Java. 105. Advantages of using Lock implementations in Java threading. 106. Difference between Runnable and Callable interfaces in Java. 107. What is the Thread’s interrupt flag? 108. What is FutureTask Class? 109. What are some common problems you face in multi-thread programming? 110. Limitations of Future. 111. What is the enhanced version of Future (or) alternative to Future? 112. Difference between green and native threads.

1. Multitasking.

We often multi task, listing to music while working or driving; Browsing internet while waiting for a download to complete. Even every computer application do things parallel. An email software will be downloading new emails from the server while you are reading an already downloaded email, archi...

Read full answer

2. Multiprogramming/Multiprocessing.

A computer or device running more than one application at the given time. For e.g. running mp3 player application while reading a blog using internet browser. Here mp3 player application and browser are two different programs/applications(or multiple programs) running at the same time.

Read full answer

3. Basic units of execution in concurrent programming.

There are two basic units of execution. processes and threads

Read full answer

4. Is concurrency possible on simple single processor systems without multiple processors?

Yes, it is.

Read full answer

5. Define Processes.

Processes also known as programs or applications has its self-contained execution environment with its own memory space. Process is considered to be heavyweight processes.

Read full answer

6. Define Threads.

These are lightweight processes, has its execution environment , requires minimal resource to create than Process. Threads are subset of process, each process has at least one thread and it shares process' memory and resources.

Read full answer

7. What is the default thread of every Java application?

"main" thread. This thread can create additional threads. ackage com.tutorials.threading; public class MainThread { public static void main (String [] args) { System.out.println(Thread.currentThread().getName()); } }

Read full answer

8. When does Thread Interference occur?

When two threads trying to act on the same data, latest thread wins and the first thread update is lost.

Read full answer

9. Thread Objects.

Each thread in java is an instance of the class java.lang.Thread.

Read full answer

10. How do you create a Thread?

Implement Runnable interface and its only method run(), which will have the code to be executed by the thread. The object for the class that implements the Runnable interface is passed as an argument to the Thread constructor as explained below. An application can use the Executor framework, in o...

Read full answer

11. Which approach is recommended?

Implementing the Runnable interface is used when your class need to extend another class. When you extend Thread class, you can not extend another class. so Implementing the Runnable interface is preferred.

Read full answer

12. Does Thread class implements Runnable?

13. What is the signature of Thread run() method?

public void run() {}

Read full answer

14. Define synchronization.

Synchronization means allowing only one thread at a time to access an object. Synchronization control the access the multiple threads to a shared resources. Without thread synchronization, one thread can modify a shared variable while another thread is working on the same variable, which leads to...

Read full answer

15. Can a thread be interrupted when it is in sleep?

16. Does sleep() method throws any Exception?

Yes. We need to handle java.lang.InterruptedException. The Sleeping thread throws InterruptedException when another thread intercepts its sleep.

Read full answer

17. Can the start method be called twice on the same Thread? (OR) Can the start() method invoked again on the same thread object after start() been called first time?

No. It will throw IllegalThreadStateException during runtime. We need to create a new thread object and invoke start() method only once. A thread may not be restarted once it has completed execution as it goes to dead state.

Read full answer

18. Why do we call Thread.start() method which in turns calls run method?

run() method can be called directly however it will not be executing the method under new thread instead the method gets run on current thread. When start() method is called it invokes run() by create a new Thread. package com.tutorials.threading; public class ThreadExtended extends Thread { publ...

Read full answer

19. Consumer Producer problem.

Posted on Apr 1, 2016 by Senthil Kumar.

package com.tutorials.threading; public class ConsumerProducerProblem { int value = 0 ; volatile boolean hasChanged = false ; public void produce( int value) throws InterruptedException { while (hasChanged == true ) { } System.out.println( "Value set:" + value); this.value = value; hasChanged = t...

Read full answer

20. Difference between Thread.interrupted() and Thread.isInterrupted().

Thread.interrupted() Thread.isInterrupted() interrupted() is a static method of Thread class and checks the current running thread if it is interrupted. isInterrupted() is an instance method which checks the Thread object for its interrupt status that it is called on. Calling interrupted() clears...

Read full answer

21. Give few example from Java API that throws InterruptedException.

Thread.sleep(), Object.wait(), join().

Read full answer

22. Best practice for "DO Nothing" Strategy for InterruptedException.

try { while (true) { Thread.sleep(2000) ; } } catch ( InterruptedException swallowedTheException ) { /* BAD PRACTICE */ } Instead re-interrupt the thread by calling interrupt() method. Because when the sleep() blocking method sniffs an interruption and throws InterruptedException, it clears the i...

Read full answer

23. Thread.sleep method()

This static method causes the current thread to suspend its execution for a specified period of time so that processor be available for the other threads of the application or yielding for other thread to complete. sleep() method is overloaded and there are two versions. public static void sleep(...

Read full answer

24. How do you interrupt an thread that does not call any method that throws InterruptedException?

We may add check as explained below. if (Thread.interrupted()) { return; }

Read full answer

25. join() method.

An Instance method of a thread object. It pauses the current thread execution in which the statement is called until the thread object on which join method is invoked complete its execution. Consider an example Without using join(). package com.tutorials.threading; public class ThreadJoinExample ...

Read full answer

26. Interrupts

indicates that the object has to stop doing what it does by calling interrupt() on the thread object. When it receives an interrupt, it returns from the run() method . package com.tutorials.threading; public class HandleInterruptedException { public static void main(String[] args) { String change...

Read full answer

27. is join() a overloaded method?

Yes. public final void join() pause for the invoking thread object to complete. public final synchronized void join (long milliSeconds) pause for the invoking thread object to complete or resume after the specified milliseconds. public final synchronized void join (long milliSeconds, int nano) pa...

Read full answer

28. An example for join(long milliseconds).

package com.tutorials.threading; public class WaitForMSToJoinExample implements Runnable { public static void main(String[] args) throws InterruptedException { WaitForMSToJoinExample myObj = new WaitForMSToJoinExample(); Thread MyThreadObj = new Thread(myObj, "Child Thread" ); MyThreadObj.start()...

Read full answer

29. How do you interrupt an thread that does not call any method that throws InterruptedException?

We may add check as explained below. if (Thread.interrupted()) { throw new InterruptedException(); }

Read full answer

30. Explain the interrupt mechanism.

The internal flag "interrupt status" tracks the status. Thread.interrupt() sets this flag and this flag is reset when Thread.interrupted (static) method is invoked to check the interruption status. The non-static isInterrupted method, which queries the interrup status of another, does not change ...

Read full answer

31. Can run() method throw exception?

32. Difference between sleep and wait method in Java.

Although both methods pause the execution of the currently running thread, sleep() is meant for suspending the execution for short pause as it does not release the lock, while wait() is a conditional wait and it releases lock which can be acquired by another thread to change the condition on whic...

Read full answer

33. Is ++ (increment) operator thread-safe in Java?

No. Neither increment operator (++) nor the decrement operaor (--) is thread safe. For example, the statement i++ is not atomic. It involves multiple instructions that includes reading the value of i variable, increment its value by 1 and store the new i value to the variable.

Read full answer

34. What is thread starvation?

When a thread is not granted CPU time because other threads were using it all, it is called starvation . The thread starves to death because other threads are using the CPU time instead of it.

Read full answer

35. Does pressing Control-C causes InterruptedException in Java?

No. Invoking the interrupt() method in a thread only triggers InterruptedException while that thread executing a method that throws InterruptedException.

Read full answer

36. What is livelock in multithreading?

A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. It is a recursive situation where two or more threads would keep repeating a particular code logic. The intended logic is typ...

Read full answer

37. Explain race condition in multithreading.

Race conditions occurs when 2 or more threads operate on same object without proper synchronization and the steps on the operation interleaves on other thread. An example of Race condition is incrementing a counter since increment is not an atomic operation and can be further divided into three s...

Read full answer

38. What causes starvation in threads?

Threads with high priority takes up all CPU time from threads with lower priority. Threads are blocked indefinitely waiting to enter a synchronized block. Threads waiting on an object by calling wait() and remain waiting indefinitely.

Read full answer

39. Difference between deadlock and livelock in Java multithreading.

A deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock. A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another however none progressing. Livelo...

Read full answer

40. What is Slipped Condition in multithreading?

Slipped conditions represents that from the time a thread has checked a certain condition until it acts upon it, the condition has been changed by another thread so that it is erroneous for the first thread to act.

Read full answer

41. What is Intrinsic Lock in Java multithreading?

Synchronization is internally controlled by an entity known as the intrinsic lock or monitor lock. Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state to one thread and preventing access to other threads and establishing happens-before r...

Read full answer

42. Explain Guarded Blocks in Java.

Guarded block is a mechanism of coordinating the execution of multiple threads in a multithreaded environment. Guarded block keeps checking for a particular condition to become true and only in that case the actual execution of the thread resumes. Guarded blocks are of 2 types, synchronized guard...

Read full answer

43. What is BLOCKED state of a thread?

A thread is said to be in BLOCKED state when it waits to acquire a object's monitor.

Read full answer

44. Different states of a Java thread.

A thread can be in one of the following states: NEW: A thread that has not yet started is in this state. RUNNABLE: A thread executing in the Java virtual machine is in this state. BLOCKED: A thread that is blocked waiting for a monitor lock is in this state. WAITING: A thread that is waiting inde...

Read full answer

45. Difference between thread state WAIT and BLOCKED.

A thread gets to wait state once it calls wait() on an Object. This is called Waiting State. Once a thread attains waiting state , it will continue to wait till some other thread notify() or notifyAll() on the object. Once this thread is notified, it will not be runnable. It might be that other t...

Read full answer

46. Difference between synchronizing a static method and a non static method in Java.

Synchronization in Java is basically an implementation of monitors. When synchronizing a non static method, the monitor belongs to the instance. When synchronizing on a static method, the monitor belongs to the class. A synchronized method acquires a monitor before it executes. For a class (stati...

Read full answer

47. What is reentrant synchronization in Java?

Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code block synchronized on the same monitor object. A thread cannot acqui...

Read full answer

48. What is Reentrant lock in Java?

java.util. concurrent.locks ReentrantLock is a concrete implementation of Lock interface provided in Java concurrency package introduced in Java 1.5. ReentrantLock is a mutual exclusive lock with extended feature like fairness, which can be used to provide lock to longest waiting thread. Reentran...

Read full answer

49. Can a thread hold more than one lock at the same time?

Yes. A thread can have more than one lock. synchronized (obj1) { synchronized (obj2) { //some code... } }

Read full answer

50. Difference between synchronized method and synchronized block in Java.

A synchronized method uses the method receiver as a lock, 'this' for non static methods and the enclosing class for static methods. Synchronized blocks uses the expression as a lock. A synchronized method locks on the object instance the method is contained in while a synchronized block can lock ...

Read full answer

51. What is Runnable in Java?

Runnable represents a task in Java which is executed by Thread. java.lang.Runnable is an interface that defines only one method called run(). When a Thread is started in Java by using Thread.start() method it calls and execute the run() method of Runnable task which was passed to Thread when crea...

Read full answer

52. Difference between start and run methods in Java Thread.

when a program calls start() method, a new thread will be created and code inside run() method is executed in newly created thread whereas if the program calls run() method directly no new Thread be created and code inside run() will execute on current Thread itself.

Read full answer

53. Define Critical section in Java multi-threading.

A critical section represents a section of code or a block that is executed by multiple threads at the same time and where the sequence of execution of the threads makes a difference in the result of the concurrent execution of the critical section.

Read full answer

54. Explain IllegalMonitorStateException in Java multi-threading.

This run-time exception is thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor. It is mandatory that a thread cannot call wait(), notify() or notifyAll() without holding the lo...

Read full answer

55. What is Spurious Wakeups in Java threads?

The thread on WAIT state on an object wakes up for no reason, it is neither notified, timed out nor interrupted.For some reasons it is possible for a thread to wake up even if notify() and notifyAll() has not been called. This behavior is known as spurious wakeups, Wakeups without any reason.

Read full answer

56. What is Daemon thread in Java?

Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task. A daemon thread is a thread that does not prevent the JVM from exiting when the Java program finishes but the thread is still running. An example for a daemon thread is the ga...

Read full answer

57. Difference between Daemon and Non Daemon thread in Java.

JVM doesn't wait for any daemon thread to finish the Java program before exiting while JVM waits for all the non-daemon thread to complete before exiting the Java program. When JVM terminates, it doesn't not invoke the daemon thread's finally block or unwind the stack. However it is not the case ...

Read full answer

58. Difference between a wait() and sleep() in Threads.

A wait can be "woken up" by another thread calling notify on the monitor which is being waited on whereas a sleep cannot. A wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not. You call wait on Object itself whereas you call sleep on Thread. While sl...

Read full answer

59. Difference between concurrency and parallelism.

Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. An application can be concurrent when multiple tasks are performed simultaneously with shared resources. An application is parallel when a single task is divided into multiple simple indep...

Read full answer

60. Explain wait(), notify() and notifyAll() methods in Java threading.

The Object class in Java has 3 final methods that allow threads to communicate about the locked status of a resource. wait() instructs the calling thread to release the lock and go to sleep until some other thread enters the same monitor and calls notify(). The wait() method releases the lock pri...

Read full answer

61. Can a thread wait on multiple objects in Java?

No. A thread cannot wait on more than one object at a time. The wait() and notify() methods are object specific and invoke on the object. The wait() method suspends the current thread of execution, and instructs the object to keep track of the suspended thread. The notify() method tells the objec...

Read full answer

62. What is mutex in Java?

Official Definition is as follows: Mutexes are typically used to serialize access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to th...

Read full answer

63. Explain semaphore in Java.

The Official Definition is as follows: A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore).

Read full answer

64. Difference between Mutex and Semaphore in Java.

Mutex is basically mutual exclusion. Only one thread can acquire the resource at once and others wait. Semaphore is used to control the number of threads executing. There will be fixed set of resources. When the semaphore count reaches 0 then no other threads are allowed to acquire the resource. ...

Read full answer

65. Difference between notify and interrupt in Java.

When a thread calls notify on some monitor, it wakes up a single thread that's waiting on that monitor, but which thread gets woken is decided by the scheduler. Unlike notify, interruption targets a specific thread and interruption does not require that the interrupted thread be waiting on a moni...

Read full answer

66. Difference between notify and notifyAll in Java.

The key difference between notify and notifyAll is that notify() will cause only one thread to wake up while notifyAll method will make all the wating thread to wake up. When a thread calls notify on some monitor, it wakes up a single thread that's waiting on that monitor, but which thread gets w...

Read full answer

67. When the lock is released after notify/notifyAll is called?

The monitor is released only after completing the remaining statements of the synchronized code even after the thread calls notify or notifyAll on the object.

Read full answer

68. Why do we use ReentrantLock over synchronized (this)?

A ReentrantLock is unstructured and flexible compared to the synchronized constructs. We don't need to use a block structure for locking and can even hold a lock across methods. private ReentrantLock lock; public void method1 () { ... lock.lock(); ... } public void method2 () { ... lock.unlock();...

Read full answer

69. Define Liveness in Java Thread.

A concurrent application's ability to execute in a timely manner is known as its liveness. The liveness problems include deadlock, starvation and livelock.

Read full answer

70. How threads communicate with each other?

Threads can communicate with each other by using wait(), notify() and notifyAll() methods.

Read full answer

71. Difference between synchronized and volatile keyword in Java.

Volatile keyword is used on the variables and not on method while synchronized keyword is applied on methods and blocks not on variables. Volatile does not acquire any lock on variable or object, but synchronized statement acquires lock on method or block in which it is used. Volatile does not ca...

Read full answer

72. Explain Thread Priority.

Every thread has a priority, usually threads with higher priority gets precedence in execution but it depends on Thread scheduler. We can specify the priority of thread but it doesn't guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int w...

Read full answer

73. What is Thread Scheduler?

Thread Scheduler is the service that allocates the CPU time to the available runnable threads. Once a thread is created and started, it?s execution rely on the implementation of Thread Scheduler. Thread scheduler is OS dependent.

Read full answer

74. Define time slicing.

Time Slicing is the process to split the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the longest waiting thread will gets priority.

Read full answer

75. Define context-switching in multi-threading.

Context Switching is the process of storing and restoring of CPU state so that the thread execution can be resumed from the same point at a later point of time. Context Switching is an essential feature for multitasking and for multi-threaded environment.

Read full answer

76. Which is preferred - Synchronized method or Synchronized block?

Synchronized block is preferred as it provides more granular control. It only locks the critical section of the code and that eliminates unnecessary object locking.

Read full answer

77. Why wait, notify and notifyAll are declared in Object class and not in Thread class?

Every Object is associated with a monitor, only one thread can hold the monitor at a time. Acquiring the object monitor allow thread to hold lock on object. These methods are not called on the thread as it does not have its own lock. As the monitor is with the object, wait is called on the object...

Read full answer

78. What is Thread Group in Java?

ThreadGroup is a class that provides information about a thread group. It helps to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. Ever since setUncaughtExceptionHandler (UncaughtExceptionHandler e) was added in Java 1.5, it serves the pu...

Read full answer

79. Explain setUncaughtExceptionHandler method of Java Thread class.

The java.lang.Thread. setUncaughtExceptionHandler() method sets the handler to be invoked when this thread abruptly terminates due to an uncaught exception. public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) This method does not return any thing. public class ExceptionHan...

Read full answer

80. What is Thread dump?

A thread dump is a snapshot of the state of all threads that are part of the process. The state of each thread is presented with a stack trace, which shows the contents of a thread's stack. Some of the threads belong to the Java application you are running, while others are JVM internal threads. ...

Read full answer

81. Explain about jstack tool.

The jstack command-line utility attaches to the specified process or core file and prints the stack traces of all threads that are attached to the virtual machine, including Java threads and VM internal threads, and optionally native stack frames. The utility also performs deadlock detection. A s...

Read full answer

82. How to debug and analyse Thread deadlock?

We may analyse any deadlock by getting the thread dump and verifying the stack trace of the active threads. we may looks for the threads that are BLOCKED, the resource it is waiting for, the thread that is currently holding the lock from the stack trace. Since JDK 1.5 there are some powerful meth...

Read full answer

83. Can we not override run method when we extend Thread class?

Yes. we can avoid overriding run method while extending Thread class. The start method will execute the default implementation which has no action.

Read full answer

84. Define Java thread pool.

Java Thread pool is a group of worker threads that are waiting for the tasks to be assigned and be reused again. Worker threads return to the thread pool after it completes its task. A group of fixed size threads are created in the thread pool. A thread from the thread pool is chosen and assigned...

Read full answer

85. Advantages of using threadpool.

Improves performance of multithreaded application as the thread pool eliminates the overhead of creating/recreating thread objects.

Read full answer

86. What are atomic classes in Java Concurrency API?

The java.util.concurrent. atomic package defines classes that support atomic operations on single variables. All classes have get and set methods to read and write similar to volatile variables. import java.util.concurrent.atomic.AtomicInteger ; public class AtomicCounter { private AtomicInteger ...

Read full answer

87. What is Lock interface in Java Concurrency API?

A lock is a thread synchronization mechanism like synchronized blocks that are sophisticated than Java's synchronized blocks. From Java 5 the package java.util.concurrent.locks contains several lock implementations. The advantages of using locks are, implements fairness. possible to try to acquir...

Read full answer

88. Define preemptive scheduling.

In preemptive scheduling, the thread with highest priority executes until it enters into the waiting or dead state.

Read full answer

89. What is the priority for Daemon threads?

Priority of daemon threads is always 1, the lowest priority. Thread scheduler schedules these threads only when CPU is idle.

Read full answer

90. Explain yield() method of a thread.

yield() method gives a notice to the thread scheduler that the current thread is willing to yield its current use of a processor. The thread scheduler is free to ignore this hint.

Read full answer

91. Can 2 threads call different synchronized instance methods of same Object?

No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.

Read full answer

92. What is thread leak in Java?

Thread leak happens when an application does not release references to a thread object properly that prevents the thread from being garbage collected. Thread leak can cause performance issues and application slowness, when too many threads gets created and not garbage collected after it attains t...

Read full answer

93. What is CountDownLatch in Java?

CountDownLatch is a synchronizer type which allows one Thread to wait for one or more Threads before starts processing. A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. A CountDownLatch is initialized with a given ...

Read full answer

94. Applications of CountDownLatch in Java thread.

CountDownLatch works in latch principle, main thread will wait until gate is open. One thread waits for n number of threads specified while creating CountDownLatch in Java. Classical example of using CountDownLatch in Java is any server side core Java application which uses services architecture,...

Read full answer

95. Explain CyclicBarrier in Java thread.

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after th...

Read full answer

96. Difference between wait-notify and CountDownLatch.

CountDownLatch behavior could be achieved using low level constructs such as wait-notify, synchronized. CountDownLatch is built using such constructs only.

Read full answer

97. How do you create an immutable class in Java?

An object is considered immutable if its state cannot change after it is constructed. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. The below are the rules...

Read full answer

98. What is the purpose of the class java.lang.ThreadLocal?

You can find the ThreadLocal questions here .

Read full answer

99. Explain volatile keyword in Java.

Find the volatile related questions here .

Read full answer

100. Explain fork/join framework in Java thread.

The fork/join framework is an implementation of the ExecutorService interface that helps you deal with multiple processors. It is designed for tasks that can be broken into smaller subtasks recursively. The goal is to use all the available processing power to enhance the performance of your appli...

Read full answer

101. Explain Fork-Join framework API.

The core of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTask processes.

Read full answer

102. Explain Exchanger in Java thread.

Exchanger is a synchronization point at which threads can pair and swap elements between the pair. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner's object on return. An Exchanger may be viewed as a bidirectional form of a ...

Read full answer

103. Difference between ReadLock and WriteLock in Java ReentrantReadWriteLock.

When a thread acquires a WriteLock, no other thread can acquire the ReadLock nor the WriteLock of the same instance of ReentrantReadWriteLock, unless that thread releases the lock. However, multiple threads can acquire the ReadLock at the same time.

Read full answer

104. General practice for releasing lock while using Lock implementation in Java.

When using any of the Lock implementation the lock is usually released in finally block. This ensures that if there is exception in method body, lock is released. public void method () { reentrantLock.lock() ; try { //perform task } finally { reentrantLock.unlock() ; } }

Read full answer

105. Advantages of using Lock implementations in Java threading.

Non-blocking or optimistic attempt to acquire a lock using tryLock , attempt to acquire the lock that can be interrupted using lockInterruptibly, attempt to acquire a lock that can timeout using tryLock(long time, TimeUnit unit), guaranteed ordering, and deadlock detection.

Read full answer

106. Difference between Runnable and Callable interfaces in Java.

The Callable interface is similar to Runnable,both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception unlike Callable which returns a result and throw exceptions.

Read full answer

107. What is the Thread’s interrupt flag?

The interrupt flag or interrupt status, is an internal Thread flag that is set when the thread is interrupted. To set it, simply call thread.interrupt() on the thread object. If a thread is currently inside one of the methods that throw InterruptedException (wait, join, sleep), then this method i...

Read full answer

108. What is FutureTask Class?

FutureTask implements Future interface and provides asynchronous processing. It contains the methods to start and cancel a task and also methods that can return the state of the FutureTask as whether it’s completed or cancelled. We need a callable object to create a future task and then we can us...

Read full answer

109. What are some common problems you face in multi-thread programming?

Memory-interference, race conditions, deadlock, livelock, and starvation are example of problems we encounter in multi-threading and concurrent programming.

Read full answer

110. Limitations of Future.

You cannot perform any further action/callback on a Future’s result without blocking since Future does not notify when completed. It provides get() method that blocks until the result is ready. Multiple Future cannot be chained together, for example, the result of one Future cannot be sent to oth...

Read full answer

111. What is the enhanced version of Future (or) alternative to Future?

CompletableFuture achieves all the limitations in Future. CompletableFuture implements Future and CompletionStage interfaces and provides a huge set of convenience methods for creating, chaining and combining multiple Futures. It also has a very comprehensive exception handling support .

Read full answer

112. Difference between green and native threads.

Green threads refers to a model in which the Java virtual machine itself creates, manages, and context switches all Java threads within one operating system process. No operating system threads library is used. Green threads are in past, JVMs work only with native threads since 1.3. Native thread...

Read full answer

«
»

Comments & Discussions