From beb89dc33f7f2ce2551dd2d56c4ad9d73ed9b677 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:21:00 -0700 Subject: [PATCH 01/37] Create interviewQuestions.md --- interviewQuestions.md | 130 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 interviewQuestions.md diff --git a/interviewQuestions.md b/interviewQuestions.md new file mode 100644 index 0000000..23210c8 --- /dev/null +++ b/interviewQuestions.md @@ -0,0 +1,130 @@ +#### 1.Multi-thread +Two ways to create thread: extends from thread class, or implement runnable interface (prefer). +Yield() and sleeping(): yield changes thread from running state to runnable state; +sleeping() changes thread from running state to waiting state(); +Threads can communicate with each other by wait(), notify(), notifyAll() method. +Used in user interface, like when you open the interface, it takes a long time to open the whole page, in the same time you can click your mouse on some button to do something. + +#### 2.Synchronized type? +synchronized methods and synchronized block. + +#### 3.what's violate? +Essentially, volatile is used to indicate that a variable's value will be modified by different threads. + +#### 4.Daemon Thread. +A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. +You can use the setDaemon() method to change the Thread daemon properties. +5.What’s difference between notify() and notifyAll()? +Main difference between notify and notifyAll isthat notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. +By the way this is something you have been reading in all over places and to be frank, this statement despite being correct is not complete and its very difficult to understand difference between notify vs notifyAll by just reading this statement. Lot of questions comes in mind like + +#### 6.What’s the states of a thread? +read state. 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 indefinitely for another thread to perform a particular action is in this state. +· TIMED_WAITING +A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. +· TERMINATED +A thread that has exited is in this state. + +#### 7.What is difference between forking a process and spawning a thread? +Forking processes:new process will run same code as parent process but in different memory space + +Spawning thread: creates another independent path of execution but share same memory space + +#### 8.What is the relationship between threads and processes? +A process can have multiple threads but a thread always belongs to a single process. Two process cannot share memory space until they are purposefully doing inter process communication via shared memory but two threads from same process always share same memory. + +#### 9.You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2? +Use join() method +T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. + +#### 10.What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? +The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. + +#### 11.What are differences between wait and sleep method in java? +wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. + Wait is used for inter-thread communication while sleep is used to introduce pause on execution. +在java.lang.Thread类中,提供了sleep(), +而java.lang.Object类中提供了wait(), +sleep need try catch + +#### 12.What is difference between CyclicBarriar and CountdownLatch in Java ? +One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch. + Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events, main difference between them is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. + +#### 13.Difference between Thread and Process in Java? +Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. + +#### 14.Difference between Runnable and Callable in Java? +both Runnable and Callable represent task which is intended to be executed in separate thread. Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these two is that +Callable's call() method can return value and throw Exception, which was not possible with Runnable's run() method + +#### 15.How to stop thread in Java? +There was some control methods in JDK 1.0 e.g. stop(), suspend() and resume() which was deprecated in later releases due to potential deadlock threats,. +To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks + +#### 16.How do you share data between two thread in Java? +You can share data between threads by using shared object, or concurrent data-structure like BlockingQueue. + +#### 17.Why we call start() method which in turns calls run() method, why not we directly call run() method ? +Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews. Answer to this question is that, when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread. + +#### 18.How will you awake a blocked thread in java? +This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing InterruptedException. + +#### 19.What is FutureTask in Java? +FutureTask represents a cancellable asynchronous computation in concurrent Java application. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. A FutureTask object can be used to wrap a Callable or Runnable object. Since FutureTask also implements Runnable, it can be submitted to an Executor for execution. + +#### 20.What is thread pool? Why should you thread pool in Java? +Creating thread is expensive in terms of time and resource. If you create thread at time of request processing it will slow down your response time, also there is only a limited number of threads a process can create. To avoid both of these issues, a pool of thread is created when application starts-up and threads are reused for request processing. This pool of thread is known as "thread pool" and threads are known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of threads) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks). See this article to learn more about thread pools in Java to prepare detailed answer of this question. + +#### 21.How do you check if a Thread holds a lock or not? +There is a method called holdsLock() on java.lang.Thread, it returns true if and only if the current thread holds the monitor lock on the specified object. + +#### 22.What happens if you submit a task when the queue of the thread pool is already filled? +This is another tricky question on my list. Many programmers will think that it will block until a task is cleared but its true. ThreadPoolExecutor's submit() method throws RejectedExecutionException if the task cannot be scheduled for execution. + +#### 23.What is the difference between the submit() and execute() method thread pool in Java? +A main difference between the submit() and execute() method is that ExecuterService.submit()can return result of computation because it has a return type of Future, but execute() method cannot return anything because it's return type is void. + +Both methods are ways to submit a task to thread pools but there is a slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. + +On other hand submit() is an overloaded method, it can take either Runnable or Callable task and can return Future object which can hold the pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. + +#### 24.Is it possible to start a thread twice? +No, there is no possibility to start a thread twice. If we does, it throws an exception. + +#### 25.What about the daemon threads? +The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. + +#### 26.What is static synchronization? +If you make any static method as synchronized, the lock will be on the class not on object. + +#### 27.Thread Commutation Methods +Wait() +sleep +Notify +notifyAll() + +#### 28.Use Executor create Thread Pool +``` +public class TestThreadPool { + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads + for (int i = 0; i < 10; i++) { + Runnable worker = new WorkerThread("" + i); + executor.execute(worker);//calling execute method of ExecutorService + } + executor.shutdown(); + while (!executor.isTerminated()) { } + System.out.println("Finished all threads"); + } + } + ``` From 9ecaf0b5073ee7ad571946991e6b47d0b64af2ba Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:22:46 -0700 Subject: [PATCH 02/37] Update interviewQuestions.md --- interviewQuestions.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 23210c8..97be1b8 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -1,7 +1,7 @@ #### 1.Multi-thread -Two ways to create thread: extends from thread class, or implement runnable interface (prefer). -Yield() and sleeping(): yield changes thread from running state to runnable state; -sleeping() changes thread from running state to waiting state(); +Two ways to create thread: extends from Thread class, or implement runnable interface (prefer). +`yield()` and `sleeping()`: `yield()` changes thread from running state to runnable state; +`sleeping()` changes thread from running state to waiting state(); Threads can communicate with each other by wait(), notify(), notifyAll() method. Used in user interface, like when you open the interface, it takes a long time to open the whole page, in the same time you can click your mouse on some button to do something. From 759be6c3b84da2848eb6903b7c09cc9a17f51737 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:31:10 -0700 Subject: [PATCH 03/37] Update interviewQuestions.md --- interviewQuestions.md | 74 ++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 97be1b8..b09ec3a 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -1,8 +1,11 @@ #### 1.Multi-thread -Two ways to create thread: extends from Thread class, or implement runnable interface (prefer). -`yield()` and `sleeping()`: `yield()` changes thread from running state to runnable state; -`sleeping()` changes thread from running state to waiting state(); -Threads can communicate with each other by wait(), notify(), notifyAll() method. +- Two ways to create thread + - extends from Thread class + - implement runnable interface (prefer) +- `yield()` and `sleeping()` + - `yield()` changes thread from running state to runnable state + - `sleeping()` changes thread from running state to waiting state +- Threads can communicate with each other by `wait()`, `notify()`, `notifyAll()` method. Used in user interface, like when you open the interface, it takes a long time to open the whole page, in the same time you can click your mouse on some button to do something. #### 2.Synchronized type? @@ -13,36 +16,30 @@ Essentially, volatile is used to indicate that a variable's value will be modifi #### 4.Daemon Thread. A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. -You can use the setDaemon() method to change the Thread daemon properties. -5.What’s difference between notify() and notifyAll()? -Main difference between notify and notifyAll isthat notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. -By the way this is something you have been reading in all over places and to be frank, this statement despite being correct is not complete and its very difficult to understand difference between notify vs notifyAll by just reading this statement. Lot of questions comes in mind like +You can use the `setDaemon()` method to change the Thread daemon properties. + +#### 5.What’s difference between `notify()` and n`otifyAll()`? +- Main difference between notify and notifyAll isthat notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. +- By the way this is something you have been reading in all over places and to be frank, this statement despite being correct is not complete and its very difficult to understand difference between notify vs notifyAll by just reading this statement. Lot of questions comes in mind like #### 6.What’s the states of a thread? read state. 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 indefinitely for another thread to perform a particular action is in this state. -· TIMED_WAITING -A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. -· TERMINATED -A thread that has exited is in this state. +- **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 indefinitely for another thread to perform a particular action is in this state. +- **TIMED_WAITING**: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. +- **TERMINATED**: A thread that has exited is in this state. #### 7.What is difference between forking a process and spawning a thread? -Forking processes:new process will run same code as parent process but in different memory space - -Spawning thread: creates another independent path of execution but share same memory space +- Forking processes:new process will run same code as parent process but in different memory space +- Spawning thread: creates another independent path of execution but share same memory space #### 8.What is the relationship between threads and processes? A process can have multiple threads but a thread always belongs to a single process. Two process cannot share memory space until they are purposefully doing inter process communication via shared memory but two threads from same process always share same memory. - + #### 9.You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2? -Use join() method +Use `join()` method T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. #### 10.What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? @@ -51,9 +48,7 @@ The major advantage of lock interfaces on multi-threaded and concurrent programm #### 11.What are differences between wait and sleep method in java? wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. -在java.lang.Thread类中,提供了sleep(), -而java.lang.Object类中提供了wait(), -sleep need try catch +在`java.lang.Thread`类中,提供了`sleep()`,而`java.lang.Object`类中提供了`wait()`,sleep need try catch #### 12.What is difference between CyclicBarriar and CountdownLatch in Java ? One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch. @@ -67,17 +62,16 @@ both Runnable and Callable represent task which is intended to be executed in se Callable's call() method can return value and throw Exception, which was not possible with Runnable's run() method #### 15.How to stop thread in Java? -There was some control methods in JDK 1.0 e.g. stop(), suspend() and resume() which was deprecated in later releases due to potential deadlock threats,. -To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks +There was some control methods in JDK 1.0 e.g. `stop()`, `suspend()` and `resume()` which was deprecated in later releases due to potential deadlock threats,. To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks #### 16.How do you share data between two thread in Java? You can share data between threads by using shared object, or concurrent data-structure like BlockingQueue. -#### 17.Why we call start() method which in turns calls run() method, why not we directly call run() method ? +#### 17.Why we call `start()` method which in turns calls `run() method`, why not we directly call `run()` method ? Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews. Answer to this question is that, when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread. #### 18.How will you awake a blocked thread in java? -This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing InterruptedException. +This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling `wait()`, `sleep()` or `join()` method you can interrupt the thread and it will awake by throwing InterruptedException. #### 19.What is FutureTask in Java? FutureTask represents a cancellable asynchronous computation in concurrent Java application. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. A FutureTask object can be used to wrap a Callable or Runnable object. Since FutureTask also implements Runnable, it can be submitted to an Executor for execution. @@ -86,17 +80,17 @@ FutureTask represents a cancellable asynchronous computation in concurrent Java Creating thread is expensive in terms of time and resource. If you create thread at time of request processing it will slow down your response time, also there is only a limited number of threads a process can create. To avoid both of these issues, a pool of thread is created when application starts-up and threads are reused for request processing. This pool of thread is known as "thread pool" and threads are known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of threads) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks). See this article to learn more about thread pools in Java to prepare detailed answer of this question. #### 21.How do you check if a Thread holds a lock or not? -There is a method called holdsLock() on java.lang.Thread, it returns true if and only if the current thread holds the monitor lock on the specified object. +There is a method called `holdsLock()` on `java.lang.Thread`, it returns true if and only if the current thread holds the monitor lock on the specified object. #### 22.What happens if you submit a task when the queue of the thread pool is already filled? -This is another tricky question on my list. Many programmers will think that it will block until a task is cleared but its true. ThreadPoolExecutor's submit() method throws RejectedExecutionException if the task cannot be scheduled for execution. +This is another tricky question on my list. Many programmers will think that it will block until a task is cleared but its true. ThreadPoolExecutor's `submit()` method throws RejectedExecutionException if the task cannot be scheduled for execution. #### 23.What is the difference between the submit() and execute() method thread pool in Java? -A main difference between the submit() and execute() method is that ExecuterService.submit()can return result of computation because it has a return type of Future, but execute() method cannot return anything because it's return type is void. +A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of Future, but `execute()` method cannot return anything because it's return type is void. Both methods are ways to submit a task to thread pools but there is a slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. -On other hand submit() is an overloaded method, it can take either Runnable or Callable task and can return Future object which can hold the pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. +On other hand `submit()` is an overloaded method, it can take either Runnable or Callable task and can return Future object which can hold the pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. #### 24.Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an exception. @@ -108,10 +102,10 @@ The daemon threads are basically the low priority threads that provides the back If you make any static method as synchronized, the lock will be on the class not on object. #### 27.Thread Commutation Methods -Wait() -sleep -Notify -notifyAll() +- `wait()` +- `sleep()` +- `notify()` +- `notifyAll()` #### 28.Use Executor create Thread Pool ``` From 50ea79d5ce8a00b008f6e5faae72dd26ebf4d1b8 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:32:40 -0700 Subject: [PATCH 04/37] Update interviewQuestions.md --- interviewQuestions.md | 54 +++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index b09ec3a..fb7989e 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -1,4 +1,4 @@ -#### 1.Multi-thread +#### 1. Multi-thread - Two ways to create thread - extends from Thread class - implement runnable interface (prefer) @@ -8,21 +8,21 @@ - Threads can communicate with each other by `wait()`, `notify()`, `notifyAll()` method. Used in user interface, like when you open the interface, it takes a long time to open the whole page, in the same time you can click your mouse on some button to do something. -#### 2.Synchronized type? +#### 2. Synchronized type? synchronized methods and synchronized block. -#### 3.what's violate? +#### 3. What's violate? Essentially, volatile is used to indicate that a variable's value will be modified by different threads. -#### 4.Daemon Thread. +#### 4. Daemon Thread. A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. You can use the `setDaemon()` method to change the Thread daemon properties. -#### 5.What’s difference between `notify()` and n`otifyAll()`? +#### 5. What’s difference between `notify()` and n`otifyAll()`? - Main difference between notify and notifyAll isthat notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. - By the way this is something you have been reading in all over places and to be frank, this statement despite being correct is not complete and its very difficult to understand difference between notify vs notifyAll by just reading this statement. Lot of questions comes in mind like -#### 6.What’s the states of a thread? +#### 6. What’s the states of a thread? read state. 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. @@ -31,83 +31,83 @@ read state. A thread can be in one of the following states: - **TIMED_WAITING**: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. - **TERMINATED**: A thread that has exited is in this state. -#### 7.What is difference between forking a process and spawning a thread? +#### 7. What is difference between forking a process and spawning a thread? - Forking processes:new process will run same code as parent process but in different memory space - Spawning thread: creates another independent path of execution but share same memory space -#### 8.What is the relationship between threads and processes? +#### 8. What is the relationship between threads and processes? A process can have multiple threads but a thread always belongs to a single process. Two process cannot share memory space until they are purposefully doing inter process communication via shared memory but two threads from same process always share same memory. -#### 9.You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2? +#### 9. You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2? Use `join()` method T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. -#### 10.What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? +#### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. -#### 11.What are differences between wait and sleep method in java? +#### 11. What are differences between wait and sleep method in java? wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. 在`java.lang.Thread`类中,提供了`sleep()`,而`java.lang.Object`类中提供了`wait()`,sleep need try catch -#### 12.What is difference between CyclicBarriar and CountdownLatch in Java ? +#### 12. What is difference between CyclicBarriar and CountdownLatch in Java ? One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch. Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events, main difference between them is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. -#### 13.Difference between Thread and Process in Java? +#### 13. Difference between Thread and Process in Java? Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. -#### 14.Difference between Runnable and Callable in Java? +#### 14. Difference between Runnable and Callable in Java? both Runnable and Callable represent task which is intended to be executed in separate thread. Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these two is that Callable's call() method can return value and throw Exception, which was not possible with Runnable's run() method -#### 15.How to stop thread in Java? +#### 15. How to stop thread in Java? There was some control methods in JDK 1.0 e.g. `stop()`, `suspend()` and `resume()` which was deprecated in later releases due to potential deadlock threats,. To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks #### 16.How do you share data between two thread in Java? You can share data between threads by using shared object, or concurrent data-structure like BlockingQueue. -#### 17.Why we call `start()` method which in turns calls `run() method`, why not we directly call `run()` method ? +#### 17. Why we call `start()` method which in turns calls `run() method`, why not we directly call `run()` method ? Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews. Answer to this question is that, when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread. -#### 18.How will you awake a blocked thread in java? +#### 18. How will you awake a blocked thread in java? This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling `wait()`, `sleep()` or `join()` method you can interrupt the thread and it will awake by throwing InterruptedException. -#### 19.What is FutureTask in Java? +#### 19. What is FutureTask in Java? FutureTask represents a cancellable asynchronous computation in concurrent Java application. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. A FutureTask object can be used to wrap a Callable or Runnable object. Since FutureTask also implements Runnable, it can be submitted to an Executor for execution. -#### 20.What is thread pool? Why should you thread pool in Java? +#### 20. What is thread pool? Why should you thread pool in Java? Creating thread is expensive in terms of time and resource. If you create thread at time of request processing it will slow down your response time, also there is only a limited number of threads a process can create. To avoid both of these issues, a pool of thread is created when application starts-up and threads are reused for request processing. This pool of thread is known as "thread pool" and threads are known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of threads) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks). See this article to learn more about thread pools in Java to prepare detailed answer of this question. -#### 21.How do you check if a Thread holds a lock or not? +#### 21. How do you check if a Thread holds a lock or not? There is a method called `holdsLock()` on `java.lang.Thread`, it returns true if and only if the current thread holds the monitor lock on the specified object. -#### 22.What happens if you submit a task when the queue of the thread pool is already filled? +#### 22. What happens if you submit a task when the queue of the thread pool is already filled? This is another tricky question on my list. Many programmers will think that it will block until a task is cleared but its true. ThreadPoolExecutor's `submit()` method throws RejectedExecutionException if the task cannot be scheduled for execution. -#### 23.What is the difference between the submit() and execute() method thread pool in Java? +#### 23. What is the difference between the submit() and execute() method thread pool in Java? A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of Future, but `execute()` method cannot return anything because it's return type is void. Both methods are ways to submit a task to thread pools but there is a slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. On other hand `submit()` is an overloaded method, it can take either Runnable or Callable task and can return Future object which can hold the pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. -#### 24.Is it possible to start a thread twice? +#### 24. Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an exception. -#### 25.What about the daemon threads? +#### 25. What about the daemon threads? The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. -#### 26.What is static synchronization? +#### 26. What is static synchronization? If you make any static method as synchronized, the lock will be on the class not on object. -#### 27.Thread Commutation Methods +#### 27. Thread Commutation Methods - `wait()` - `sleep()` - `notify()` - `notifyAll()` -#### 28.Use Executor create Thread Pool +#### 28. Use Executor create Thread Pool ``` public class TestThreadPool { public static void main(String[] args) { From 26c91d548c68887044850fa17f9bb7610199df7a Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:36:57 -0700 Subject: [PATCH 05/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index fb7989e..6c475a1 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -18,7 +18,7 @@ Essentially, volatile is used to indicate that a variable's value will be modifi A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. You can use the `setDaemon()` method to change the Thread daemon properties. -#### 5. What’s difference between `notify()` and n`otifyAll()`? +#### 5. What’s difference between `notify()` and `notifyAll()`? - Main difference between notify and notifyAll isthat notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. - By the way this is something you have been reading in all over places and to be frank, this statement despite being correct is not complete and its very difficult to understand difference between notify vs notifyAll by just reading this statement. Lot of questions comes in mind like From f48c420476fca535c8a9edcb3ca1c4da6b17c985 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:37:24 -0700 Subject: [PATCH 06/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 6c475a1..d4ee139 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -19,7 +19,7 @@ A daemon thread is a thread, that does not prevent the JVM from exiting when the You can use the `setDaemon()` method to change the Thread daemon properties. #### 5. What’s difference between `notify()` and `notifyAll()`? -- Main difference between notify and notifyAll isthat notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. +- Main difference between notify and notifyAll is that notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. - By the way this is something you have been reading in all over places and to be frank, this statement despite being correct is not complete and its very difficult to understand difference between notify vs notifyAll by just reading this statement. Lot of questions comes in mind like #### 6. What’s the states of a thread? From 049767ae523acb322a935de31696c57da75dd39a Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:44:04 -0700 Subject: [PATCH 07/37] Update interviewQuestions.md --- interviewQuestions.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index d4ee139..e107973 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -19,8 +19,13 @@ A daemon thread is a thread, that does not prevent the JVM from exiting when the You can use the `setDaemon()` method to change the Thread daemon properties. #### 5. What’s difference between `notify()` and `notifyAll()`? -- Main difference between notify and notifyAll is that notify method will only notify one Thread and notifyAll method will notify all Threads which are waiting on that monitor or lock. -- By the way this is something you have been reading in all over places and to be frank, this statement despite being correct is not complete and its very difficult to understand difference between notify vs notifyAll by just reading this statement. Lot of questions comes in mind like +- First and main difference between `notify()` and `notifyAll()` method is that, if multiple threads is waiting on any lock in Java, notify method send notification to only one of waiting thread while notifyAll informs all threads waiting on that lock. + +- If you use notify method , It's not guaranteed that, which thread will be informed, but if you use notifyAll since all thread will be notified, they will compete for lock and the lucky thread which gets lock will continue. In a way, notifyAll method is safer because it sends notification to all threads, so if any thread misses the notification, there are other threads to do the job, while in the case of `notify()` method if the notified thread misses the notification then it could create subtle, hard to debug issues. + +- Some people argue that using notifyAll can drain more CPU cycles than notify itself but if you really want to sure that your notification doesn't get wasted by any reason, use notifyAll. Since wait method is called from the loop and they check condition even after waking up, calling notifyAll won't lead any side effect, instead it ensures that notification is not dropped. + +- Prefer notifyAll over notify whenever in doubt and if you can, avoid using notify and notifyAll altogether, instead use concurrency utility like `CountDownLatch`, `CyclicBarrier`, and `Semaphore` to write your concurrency code. #### 6. What’s the states of a thread? read state. A thread can be in one of the following states: From b4c1442b95506a0dfdf09e9d40e57ec2dfe8bbdc Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:44:51 -0700 Subject: [PATCH 08/37] Update interviewQuestions.md --- interviewQuestions.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index e107973..3e6ddf2 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -18,7 +18,7 @@ Essentially, volatile is used to indicate that a variable's value will be modifi A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. You can use the `setDaemon()` method to change the Thread daemon properties. -#### 5. What’s difference between `notify()` and `notifyAll()`? +#### 5. What’s difference between `notify()` and `notifyAll()`? [1] - First and main difference between `notify()` and `notifyAll()` method is that, if multiple threads is waiting on any lock in Java, notify method send notification to only one of waiting thread while notifyAll informs all threads waiting on that lock. - If you use notify method , It's not guaranteed that, which thread will be informed, but if you use notifyAll since all thread will be notified, they will compete for lock and the lucky thread which gets lock will continue. In a way, notifyAll method is safer because it sends notification to all threads, so if any thread misses the notification, there are other threads to do the job, while in the case of `notify()` method if the notified thread misses the notification then it could create subtle, hard to debug issues. @@ -127,3 +127,4 @@ public class TestThreadPool { } } ``` +[1]: https://www.java67.com/2013/03/difference-between-wait-vs-notify-vs-notifyAll-java-thread.html From 5af17603fecaa8ce308a26885402601d09b3e41e Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:45:47 -0700 Subject: [PATCH 09/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 3e6ddf2..f0d1d18 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -21,7 +21,7 @@ You can use the `setDaemon()` method to change the Thread daemon properties. #### 5. What’s difference between `notify()` and `notifyAll()`? [1] - First and main difference between `notify()` and `notifyAll()` method is that, if multiple threads is waiting on any lock in Java, notify method send notification to only one of waiting thread while notifyAll informs all threads waiting on that lock. -- If you use notify method , It's not guaranteed that, which thread will be informed, but if you use notifyAll since all thread will be notified, they will compete for lock and the lucky thread which gets lock will continue. In a way, notifyAll method is safer because it sends notification to all threads, so if any thread misses the notification, there are other threads to do the job, while in the case of `notify()` method if the notified thread misses the notification then it could create subtle, hard to debug issues. +- If you use notify method , It's not guaranteed that, which thread will be informed, but if you use notifyAll since all thread will be notified, they will compete for lock and the lucky thread which gets lock will continue. In a way, **notifyAll method is safer because it sends notification to all threads**, so if any thread misses the notification, there are other threads to do the job, while in the case of `notify()` method if the notified thread misses the notification then it could create subtle, hard to debug issues. - Some people argue that using notifyAll can drain more CPU cycles than notify itself but if you really want to sure that your notification doesn't get wasted by any reason, use notifyAll. Since wait method is called from the loop and they check condition even after waking up, calling notifyAll won't lead any side effect, instead it ensures that notification is not dropped. From a3db97fe8dd838b97379c6341d5e143ec3d4c6a5 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:48:17 -0700 Subject: [PATCH 10/37] Update interviewQuestions.md --- interviewQuestions.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index f0d1d18..3c23e82 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -27,14 +27,15 @@ You can use the `setDaemon()` method to change the Thread daemon properties. - Prefer notifyAll over notify whenever in doubt and if you can, avoid using notify and notifyAll altogether, instead use concurrency utility like `CountDownLatch`, `CyclicBarrier`, and `Semaphore` to write your concurrency code. -#### 6. What’s the states of a thread? +#### 6. What’s the states of a thread? [2] read state. 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 indefinitely for another thread to perform a particular action is in this state. -- **TIMED_WAITING**: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. -- **TERMINATED**: A thread that has exited is in this state. +- **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 indefinitely for another thread to perform a particular action is in this state. +- **TIMED_WAITING**: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. +- **TERMINATED**: A thread that has exited is in this state. + #### 7. What is difference between forking a process and spawning a thread? - Forking processes:new process will run same code as parent process but in different memory space @@ -128,3 +129,4 @@ public class TestThreadPool { } ``` [1]: https://www.java67.com/2013/03/difference-between-wait-vs-notify-vs-notifyAll-java-thread.html +[2]: https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/ From 1773b650efe3b2401e20c3e74a2a344f7cffb809 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:51:37 -0700 Subject: [PATCH 11/37] Update interviewQuestions.md --- interviewQuestions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 3c23e82..b69a6a2 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -28,14 +28,14 @@ You can use the `setDaemon()` method to change the Thread daemon properties. - Prefer notifyAll over notify whenever in doubt and if you can, avoid using notify and notifyAll altogether, instead use concurrency utility like `CountDownLatch`, `CyclicBarrier`, and `Semaphore` to write your concurrency code. #### 6. What’s the states of a thread? [2] -read state. A thread can be in one of the following states: +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 indefinitely for another thread to perform a particular action is in this state. - **TIMED_WAITING**: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. - **TERMINATED**: A thread that has exited is in this state. - +![Alt text](https://media.geeksforgeeks.org/wp-content/uploads/threadLifeCycle.jpg) #### 7. What is difference between forking a process and spawning a thread? - Forking processes:new process will run same code as parent process but in different memory space From c9d34d380e5557a6243db5e1513d2270cd20d998 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 20:58:14 -0700 Subject: [PATCH 12/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index b69a6a2..c200ec6 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -28,7 +28,7 @@ You can use the `setDaemon()` method to change the Thread daemon properties. - Prefer notifyAll over notify whenever in doubt and if you can, avoid using notify and notifyAll altogether, instead use concurrency utility like `CountDownLatch`, `CyclicBarrier`, and `Semaphore` to write your concurrency code. #### 6. What’s the states of a thread? [2] -A thread can be in one of the following states: +In Java, to get the current state of the thread, use `Thread.getState()` method to get the current state of the thread. Java provides `java.lang.Thread.State` class that defines the `ENUM` constants for the state of a 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. From 8c940d0efa209800c890f8eb22a8d916b14d2b61 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 21:01:33 -0700 Subject: [PATCH 13/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index c200ec6..c6add45 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -38,7 +38,7 @@ In Java, to get the current state of the thread, use `Thread.getState()` method ![Alt text](https://media.geeksforgeeks.org/wp-content/uploads/threadLifeCycle.jpg) #### 7. What is difference between forking a process and spawning a thread? -- Forking processes:new process will run same code as parent process but in different memory space +- Forking processes: new process will run same code as parent process but in different memory space - Spawning thread: creates another independent path of execution but share same memory space #### 8. What is the relationship between threads and processes? From 718b9e4bd035f48d2a42ad3f13d9a81c939ecacb Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 21:05:50 -0700 Subject: [PATCH 14/37] Update interviewQuestions.md --- interviewQuestions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index c6add45..3e0454d 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -45,8 +45,8 @@ In Java, to get the current state of the thread, use `Thread.getState()` method A process can have multiple threads but a thread always belongs to a single process. Two process cannot share memory space until they are purposefully doing inter process communication via shared memory but two threads from same process always share same memory. #### 9. You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2? -Use `join()` method -T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. +- `t.join()` instructs the current thread - the one that call `t.join()` - to wait until the `t` thread completes its job before continuing with the statements that follows. +- Use `join()` method, T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. #### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. From 4af4e77efdf1e74b511790df56b8817371ae249a Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 21:55:17 -0700 Subject: [PATCH 15/37] Update interviewQuestions.md --- interviewQuestions.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 3e0454d..02617da 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -49,7 +49,39 @@ A process can have multiple threads but a thread always belongs to a single proc - Use `join()` method, T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. #### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? -The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. +The major advantage of readwritelock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. + +``` +ExecutorService executor = Executors.newFixedThreadPool(2); +Map map = new HashMap<>(); +ReadWriteLock lock = new ReentrantReadWriteLock(); + +executor.submit(() -> { + lock.writeLock().lock(); + try { + sleep(1); + map.put("foo", "bar"); + } finally { + lock.writeLock().unlock(); + } +}); + +Runnable readTask = () -> { + lock.readLock().lock(); + try { + System.out.println(map.get("foo")); + sleep(1); + } finally { + lock.readLock().unlock(); + } +}; + +executor.submit(readTask); +executor.submit(readTask); + +stop(executor); +``` + #### 11. What are differences between wait and sleep method in java? wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. From fa9ceb5d9a7e4cc170515d288ceb75290a039730 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 21:56:35 -0700 Subject: [PATCH 16/37] Update interviewQuestions.md --- interviewQuestions.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 02617da..25be00d 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -48,8 +48,9 @@ A process can have multiple threads but a thread always belongs to a single proc - `t.join()` instructs the current thread - the one that call `t.join()` - to wait until the `t` thread completes its job before continuing with the statements that follows. - Use `join()` method, T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. -#### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? -The major advantage of readwritelock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. +#### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? [3] +- The major advantage of readwritelock on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. +- When you execute the following code sample you'll notice that both read tasks have to wait the whole second until the write task has finished. After the write lock has been released both read tasks are executed in parallel and print the result simultaneously to the console. They don't have to wait for each other to finish because read-locks can safely be acquired concurrently as long as no write-lock is held by another thread. ``` ExecutorService executor = Executors.newFixedThreadPool(2); @@ -162,3 +163,4 @@ public class TestThreadPool { ``` [1]: https://www.java67.com/2013/03/difference-between-wait-vs-notify-vs-notifyAll-java-thread.html [2]: https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/ +[3]: https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/ From 770b45516fc53a879ede59656162df6cbdbf36c2 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:11:36 -0700 Subject: [PATCH 17/37] Update interviewQuestions.md --- interviewQuestions.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/interviewQuestions.md b/interviewQuestions.md index 25be00d..c5465f0 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -161,6 +161,44 @@ public class TestThreadPool { } } ``` + + #### 29. Optimistic Locking using StampedLock +- In contrast to normal read locks an optimistic lock doesn't prevent other threads to obtain a write lock instantaneously. After sending the first thread to sleep for one second the second thread obtains a write lock without waiting for the optimistic read lock to be released. From this point the optimistic read lock is no longer valid. Even when the write lock is released the optimistic read locks stays invalid. + +- So when working with optimistic locks you have to validate the lock every time after accessing any shared mutable variable to make sure the read was still valid. + + +``` +ExecutorService executor = Executors.newFixedThreadPool(2); +StampedLock lock = new StampedLock(); + +executor.submit(() -> { + long stamp = lock.tryOptimisticRead(); + try { + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + sleep(1); + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + sleep(2); + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + } finally { + lock.unlock(stamp); + } +}); + +executor.submit(() -> { + long stamp = lock.writeLock(); + try { + System.out.println("Write Lock acquired"); + sleep(2); + } finally { + lock.unlock(stamp); + System.out.println("Write done"); + } +}); + +stop(executor); +``` + [1]: https://www.java67.com/2013/03/difference-between-wait-vs-notify-vs-notifyAll-java-thread.html [2]: https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/ [3]: https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/ From 7e29e94a3e33421304282495bbbd2b3ae532b60b Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:25:14 -0700 Subject: [PATCH 18/37] Update interviewQuestions.md --- interviewQuestions.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index c5465f0..b6adf35 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -49,7 +49,9 @@ A process can have multiple threads but a thread always belongs to a single proc - Use `join()` method, T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. #### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? [3] -- The major advantage of readwritelock on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. +- Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects. [4] +- A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock. [4] +- The major advantage of readwritelock is it provides two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. - When you execute the following code sample you'll notice that both read tasks have to wait the whole second until the write task has finished. After the write lock has been released both read tasks are executed in parallel and print the result simultaneously to the console. They don't have to wait for each other to finish because read-locks can safely be acquired concurrently as long as no write-lock is held by another thread. ``` @@ -202,3 +204,4 @@ stop(executor); [1]: https://www.java67.com/2013/03/difference-between-wait-vs-notify-vs-notifyAll-java-thread.html [2]: https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/ [3]: https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/ +[4]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html From b26a857c3d19e3334b90d8365e85ba097d7fc97f Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:27:44 -0700 Subject: [PATCH 19/37] Update interviewQuestions.md --- interviewQuestions.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index b6adf35..46f2a18 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -87,9 +87,15 @@ stop(executor); #### 11. What are differences between wait and sleep method in java? -wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. - Wait is used for inter-thread communication while sleep is used to introduce pause on execution. -在`java.lang.Thread`类中,提供了`sleep()`,而`java.lang.Object`类中提供了`wait()`,sleep need try catch +- `wait()` + - release the lock or monitor + - wait is used for inter-thread communication + - 在`java.lang.Thread`类中,提供了`sleep()` +- `sleep()` + - doesn't release any lock or monitor while waiting + - leep is used to introduce pause on execution. + - `java.lang.Object`类中提供了`wait()` + - sleep need try catch interruption #### 12. What is difference between CyclicBarriar and CountdownLatch in Java ? One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch. From 77ecbb23469ad719c8aca4dfa2748cd7c4fe7a73 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:28:50 -0700 Subject: [PATCH 20/37] Update interviewQuestions.md --- interviewQuestions.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 46f2a18..6b37e31 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -85,7 +85,6 @@ executor.submit(readTask); stop(executor); ``` - #### 11. What are differences between wait and sleep method in java? - `wait()` - release the lock or monitor @@ -98,7 +97,7 @@ stop(executor); - sleep need try catch interruption #### 12. What is difference between CyclicBarriar and CountdownLatch in Java ? -One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch. +One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse CountdownLatch. Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events, main difference between them is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. #### 13. Difference between Thread and Process in Java? From bad1230e382013a0f49147f31f8a8e1414175463 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:49:13 -0700 Subject: [PATCH 21/37] Update interviewQuestions.md --- interviewQuestions.md | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 6b37e31..7514b54 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -42,7 +42,8 @@ In Java, to get the current state of the thread, use `Thread.getState()` method - Spawning thread: creates another independent path of execution but share same memory space #### 8. What is the relationship between threads and processes? -A process can have multiple threads but a thread always belongs to a single process. Two process cannot share memory space until they are purposefully doing inter process communication via shared memory but two threads from same process always share same memory. +- Thread is subset of Process, in other words one process can contain multiple threads. +- Two process runs on different memory space, but all threads share same memory space. #### 9. You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2? - `t.join()` instructs the current thread - the one that call `t.join()` - to wait until the `t` thread completes its job before continuing with the statements that follows. @@ -100,60 +101,57 @@ stop(executor); One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse CountdownLatch. Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events, main difference between them is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. -#### 13. Difference between Thread and Process in Java? -Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. - -#### 14. Difference between Runnable and Callable in Java? +#### 13. Difference between Runnable and Callable in Java? both Runnable and Callable represent task which is intended to be executed in separate thread. Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these two is that Callable's call() method can return value and throw Exception, which was not possible with Runnable's run() method -#### 15. How to stop thread in Java? +#### 14. How to stop thread in Java? There was some control methods in JDK 1.0 e.g. `stop()`, `suspend()` and `resume()` which was deprecated in later releases due to potential deadlock threats,. To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks -#### 16.How do you share data between two thread in Java? +#### 15.How do you share data between two thread in Java? You can share data between threads by using shared object, or concurrent data-structure like BlockingQueue. -#### 17. Why we call `start()` method which in turns calls `run() method`, why not we directly call `run()` method ? +#### 16. Why we call `start()` method which in turns calls `run() method`, why not we directly call `run()` method ? Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews. Answer to this question is that, when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread. -#### 18. How will you awake a blocked thread in java? +#### 17. How will you awake a blocked thread in java? This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling `wait()`, `sleep()` or `join()` method you can interrupt the thread and it will awake by throwing InterruptedException. -#### 19. What is FutureTask in Java? +#### 18. What is FutureTask in Java? FutureTask represents a cancellable asynchronous computation in concurrent Java application. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. A FutureTask object can be used to wrap a Callable or Runnable object. Since FutureTask also implements Runnable, it can be submitted to an Executor for execution. -#### 20. What is thread pool? Why should you thread pool in Java? +#### 19. What is thread pool? Why should you thread pool in Java? Creating thread is expensive in terms of time and resource. If you create thread at time of request processing it will slow down your response time, also there is only a limited number of threads a process can create. To avoid both of these issues, a pool of thread is created when application starts-up and threads are reused for request processing. This pool of thread is known as "thread pool" and threads are known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of threads) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks). See this article to learn more about thread pools in Java to prepare detailed answer of this question. -#### 21. How do you check if a Thread holds a lock or not? -There is a method called `holdsLock()` on `java.lang.Thread`, it returns true if and only if the current thread holds the monitor lock on the specified object. +#### 20. How do you check if a Thread holds a lock or not? +There is a method called `Thread.holdsLock(Object obj)` on `java.lang.Thread`, it returns true if and only if the current thread holds the monitor lock on the specified object. -#### 22. What happens if you submit a task when the queue of the thread pool is already filled? +#### 21. What happens if you submit a task when the queue of the thread pool is already filled? This is another tricky question on my list. Many programmers will think that it will block until a task is cleared but its true. ThreadPoolExecutor's `submit()` method throws RejectedExecutionException if the task cannot be scheduled for execution. -#### 23. What is the difference between the submit() and execute() method thread pool in Java? +#### 22. What is the difference between the submit() and execute() method thread pool in Java? A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of Future, but `execute()` method cannot return anything because it's return type is void. Both methods are ways to submit a task to thread pools but there is a slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. On other hand `submit()` is an overloaded method, it can take either Runnable or Callable task and can return Future object which can hold the pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. -#### 24. Is it possible to start a thread twice? +#### 23. Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an exception. -#### 25. What about the daemon threads? +#### 24. What about the daemon threads? The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. -#### 26. What is static synchronization? +#### 25. What is static synchronization? If you make any static method as synchronized, the lock will be on the class not on object. -#### 27. Thread Commutation Methods +#### 26. Thread Commutation Methods - `wait()` - `sleep()` - `notify()` - `notifyAll()` -#### 28. Use Executor create Thread Pool +#### 27. Use Executor create Thread Pool ``` public class TestThreadPool { public static void main(String[] args) { @@ -169,7 +167,7 @@ public class TestThreadPool { } ``` - #### 29. Optimistic Locking using StampedLock + #### 28. Optimistic Locking using StampedLock - In contrast to normal read locks an optimistic lock doesn't prevent other threads to obtain a write lock instantaneously. After sending the first thread to sleep for one second the second thread obtains a write lock without waiting for the optimistic read lock to be released. From this point the optimistic read lock is no longer valid. Even when the write lock is released the optimistic read locks stays invalid. - So when working with optimistic locks you have to validate the lock every time after accessing any shared mutable variable to make sure the read was still valid. From fae072d88e2923309fa3d821985871d82fc456e4 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:52:13 -0700 Subject: [PATCH 22/37] Update interviewQuestions.md --- interviewQuestions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 7514b54..51c5de7 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -120,14 +120,14 @@ This is tricky question on threading, blocking can result on many ways, if threa #### 18. What is FutureTask in Java? FutureTask represents a cancellable asynchronous computation in concurrent Java application. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. A FutureTask object can be used to wrap a Callable or Runnable object. Since FutureTask also implements Runnable, it can be submitted to an Executor for execution. -#### 19. What is thread pool? Why should you thread pool in Java? +#### 19. What is thread pool? Why should you use thread pool in Java? Creating thread is expensive in terms of time and resource. If you create thread at time of request processing it will slow down your response time, also there is only a limited number of threads a process can create. To avoid both of these issues, a pool of thread is created when application starts-up and threads are reused for request processing. This pool of thread is known as "thread pool" and threads are known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of threads) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks). See this article to learn more about thread pools in Java to prepare detailed answer of this question. #### 20. How do you check if a Thread holds a lock or not? There is a method called `Thread.holdsLock(Object obj)` on `java.lang.Thread`, it returns true if and only if the current thread holds the monitor lock on the specified object. #### 21. What happens if you submit a task when the queue of the thread pool is already filled? -This is another tricky question on my list. Many programmers will think that it will block until a task is cleared but its true. ThreadPoolExecutor's `submit()` method throws RejectedExecutionException if the task cannot be scheduled for execution. +ThreadPoolExecutor's `submit()` method throws RejectedExecutionException if the task cannot be scheduled for execution. #### 22. What is the difference between the submit() and execute() method thread pool in Java? A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of Future, but `execute()` method cannot return anything because it's return type is void. From b9638b8ba2d85bc7dc9542b299dcfdfd5a08ab78 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:52:48 -0700 Subject: [PATCH 23/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 51c5de7..72695d6 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -127,7 +127,7 @@ Creating thread is expensive in terms of time and resource. If you create thread There is a method called `Thread.holdsLock(Object obj)` on `java.lang.Thread`, it returns true if and only if the current thread holds the monitor lock on the specified object. #### 21. What happens if you submit a task when the queue of the thread pool is already filled? -ThreadPoolExecutor's `submit()` method throws RejectedExecutionException if the task cannot be scheduled for execution. +ThreadPoolExecutor's `submit()` method throws `RejectedExecutionException` if the task cannot be scheduled for execution. #### 22. What is the difference between the submit() and execute() method thread pool in Java? A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of Future, but `execute()` method cannot return anything because it's return type is void. From 7ea2ecec8cecce5675102ba1ed4ed94411351a28 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 22:59:41 -0700 Subject: [PATCH 24/37] Update interviewQuestions.md --- interviewQuestions.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/interviewQuestions.md b/interviewQuestions.md index 72695d6..200e9b1 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -130,6 +130,8 @@ There is a method called `Thread.holdsLock(Object obj)` on `java.lang.Thread`, i ThreadPoolExecutor's `submit()` method throws `RejectedExecutionException` if the task cannot be scheduled for execution. #### 22. What is the difference between the submit() and execute() method thread pool in Java? +> Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. [5] + A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of Future, but `execute()` method cannot return anything because it's return type is void. Both methods are ways to submit a task to thread pools but there is a slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. @@ -208,3 +210,4 @@ stop(executor); [2]: https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/ [3]: https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/ [4]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html +[5]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.lang.Runnable) From 8acbc52e215295b02cbc2b5805b6ce0d3e9225cb Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 23:01:06 -0700 Subject: [PATCH 25/37] Update interviewQuestions.md --- interviewQuestions.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 200e9b1..49ee764 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -129,14 +129,14 @@ There is a method called `Thread.holdsLock(Object obj)` on `java.lang.Thread`, i #### 21. What happens if you submit a task when the queue of the thread pool is already filled? ThreadPoolExecutor's `submit()` method throws `RejectedExecutionException` if the task cannot be scheduled for execution. -#### 22. What is the difference between the submit() and execute() method thread pool in Java? +#### 22. What is the difference between the `submit()` and `execute()` method thread pool in Java? > Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. [5] -A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of Future, but `execute()` method cannot return anything because it's return type is void. +A main difference between the `submit()` and `execute()` method is that `ExecuterService.submit()` can return result of computation because it has a return type of `Future`, but `execute()` method cannot return anything because it's return type is void. -Both methods are ways to submit a task to thread pools but there is a slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. +Both methods are ways to submit a task to thread pools but there is a slight difference between them. `execute(Runnable command)` is defined in `Executor` interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. -On other hand `submit()` is an overloaded method, it can take either Runnable or Callable task and can return Future object which can hold the pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. +On other hand `submit()` is an overloaded method, it can take either `Runnable` or `Callable` task and can return `Future` object which can hold the pending result of computation. This method is defined on `ExecutorService` interface, which extends `Executor` interface, and every other thread pool class e.g. `ThreadPoolExecutor` or `ScheduledThreadPoolExecutor` gets these methods. #### 23. Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an exception. From d850f5ae564503c6d629cb90056ce196f9a666fc Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 23:04:04 -0700 Subject: [PATCH 26/37] Update interviewQuestions.md --- interviewQuestions.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/interviewQuestions.md b/interviewQuestions.md index 49ee764..00e622f 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -140,6 +140,10 @@ On other hand `submit()` is an overloaded method, it can take either `Runnable` #### 23. Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an exception. +> It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. [6] + +Throws: +IllegalThreadStateException - if the thread was already started. #### 24. What about the daemon threads? The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. @@ -211,3 +215,4 @@ stop(executor); [3]: https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/ [4]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html [5]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.lang.Runnable) +[6]: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#start() From 6cd194b8d923d274cbe180f1dfa3e959157678c2 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 23:04:42 -0700 Subject: [PATCH 27/37] Update interviewQuestions.md --- interviewQuestions.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 00e622f..451e6ee 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -140,10 +140,9 @@ On other hand `submit()` is an overloaded method, it can take either `Runnable` #### 23. Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an exception. -> It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. [6] - -Throws: -IllegalThreadStateException - if the thread was already started. +> It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. +> Throws: +> IllegalThreadStateException - if the thread was already started. [6] #### 24. What about the daemon threads? The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. From 0425568c60d9883f3d612028e6b76ddc1e873f4d Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 23:05:43 -0700 Subject: [PATCH 28/37] Update interviewQuestions.md --- interviewQuestions.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 451e6ee..9fe86d5 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -15,8 +15,9 @@ synchronized methods and synchronized block. Essentially, volatile is used to indicate that a variable's value will be modified by different threads. #### 4. Daemon Thread. -A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. -You can use the `setDaemon()` method to change the Thread daemon properties. +- The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. +- A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. +- You can use the `setDaemon()` method to change the Thread daemon properties. #### 5. What’s difference between `notify()` and `notifyAll()`? [1] - First and main difference between `notify()` and `notifyAll()` method is that, if multiple threads is waiting on any lock in Java, notify method send notification to only one of waiting thread while notifyAll informs all threads waiting on that lock. @@ -145,7 +146,7 @@ No, there is no possibility to start a thread twice. If we does, it throws an ex > IllegalThreadStateException - if the thread was already started. [6] #### 24. What about the daemon threads? -The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. + #### 25. What is static synchronization? If you make any static method as synchronized, the lock will be on the class not on object. From 46142238557e2f4e39300d8c001f0ffeaab2a401 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 23:06:09 -0700 Subject: [PATCH 29/37] Update interviewQuestions.md --- interviewQuestions.md | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 9fe86d5..02c4a03 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -145,19 +145,16 @@ No, there is no possibility to start a thread twice. If we does, it throws an ex > Throws: > IllegalThreadStateException - if the thread was already started. [6] -#### 24. What about the daemon threads? - - -#### 25. What is static synchronization? +#### 24. What is static synchronization? If you make any static method as synchronized, the lock will be on the class not on object. -#### 26. Thread Commutation Methods +#### 25. Thread Commutation Methods - `wait()` - `sleep()` - `notify()` - `notifyAll()` -#### 27. Use Executor create Thread Pool +#### 26. Use Executor create Thread Pool ``` public class TestThreadPool { public static void main(String[] args) { @@ -173,7 +170,7 @@ public class TestThreadPool { } ``` - #### 28. Optimistic Locking using StampedLock + #### 27. Optimistic Locking using StampedLock - In contrast to normal read locks an optimistic lock doesn't prevent other threads to obtain a write lock instantaneously. After sending the first thread to sleep for one second the second thread obtains a write lock without waiting for the optimistic read lock to be released. From this point the optimistic read lock is no longer valid. Even when the write lock is released the optimistic read locks stays invalid. - So when working with optimistic locks you have to validate the lock every time after accessing any shared mutable variable to make sure the read was still valid. From 57bb6bc2bba8390bd8bde23773c6afa4461e95ef Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 5 Jul 2019 23:07:20 -0700 Subject: [PATCH 30/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 02c4a03..8652227 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -148,7 +148,7 @@ No, there is no possibility to start a thread twice. If we does, it throws an ex #### 24. What is static synchronization? If you make any static method as synchronized, the lock will be on the class not on object. -#### 25. Thread Commutation Methods +#### 25. Thread Communication Methods - `wait()` - `sleep()` - `notify()` From 33875da3947e23af79d2a7eff7a01680f1212d28 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Fri, 12 Jul 2019 23:12:22 -0700 Subject: [PATCH 31/37] Update interviewQuestions.md --- interviewQuestions.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interviewQuestions.md b/interviewQuestions.md index 8652227..e434ccd 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -53,6 +53,7 @@ In Java, to get the current state of the thread, use `Thread.getState()` method #### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? [3] - Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects. [4] - A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock. [4] +- A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. [7] - The major advantage of readwritelock is it provides two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. - When you execute the following code sample you'll notice that both read tasks have to wait the whole second until the write task has finished. After the write lock has been released both read tasks are executed in parallel and print the result simultaneously to the console. They don't have to wait for each other to finish because read-locks can safely be acquired concurrently as long as no write-lock is held by another thread. @@ -213,3 +214,4 @@ stop(executor); [4]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html [5]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.lang.Runnable) [6]: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#start() +[7]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html From a384156823144f3c270a0dca180887597071fe06 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Sat, 7 Sep 2019 11:34:17 -0700 Subject: [PATCH 32/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index e434ccd..82023c1 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -11,7 +11,7 @@ Used in user interface, like when you open the interface, it takes a long time t #### 2. Synchronized type? synchronized methods and synchronized block. -#### 3. What's violate? +#### 3. What's volatile? Essentially, volatile is used to indicate that a variable's value will be modified by different threads. #### 4. Daemon Thread. From 45c3c9d126da909383008ef008b22a37777291fe Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Sat, 7 Sep 2019 11:51:38 -0700 Subject: [PATCH 33/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 82023c1..cf06aed 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -51,7 +51,7 @@ In Java, to get the current state of the thread, use `Thread.getState()` method - Use `join()` method, T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. #### 10. What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? [3] -- Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects. [4] +- Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects (`lock.newCondition()`). [4] - A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock. [4] - A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. [7] - The major advantage of readwritelock is it provides two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. From 3dff63f53b258fcc06e5639bd600b71f41fbeece Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Sat, 7 Sep 2019 12:01:37 -0700 Subject: [PATCH 34/37] Update interviewQuestions.md --- interviewQuestions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index cf06aed..fa222f8 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -92,11 +92,11 @@ stop(executor); - `wait()` - release the lock or monitor - wait is used for inter-thread communication - - 在`java.lang.Thread`类中,提供了`sleep()` + - `java.lang.Object`类中提供了`wait()` - `sleep()` - doesn't release any lock or monitor while waiting - leep is used to introduce pause on execution. - - `java.lang.Object`类中提供了`wait()` + - `java.lang.Thread`类中,提供了`sleep()` - sleep need try catch interruption #### 12. What is difference between CyclicBarriar and CountdownLatch in Java ? From f84851a3b23bf1231a411fc812cf175355a7bedc Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Sat, 7 Sep 2019 12:01:56 -0700 Subject: [PATCH 35/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index fa222f8..4f83c08 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -95,7 +95,7 @@ stop(executor); - `java.lang.Object`类中提供了`wait()` - `sleep()` - doesn't release any lock or monitor while waiting - - leep is used to introduce pause on execution. + - sleep is used to introduce pause on execution. - `java.lang.Thread`类中,提供了`sleep()` - sleep need try catch interruption From 384b6c236a293748d82fca0b8b16c4e74ec26334 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Sat, 7 Sep 2019 12:03:35 -0700 Subject: [PATCH 36/37] Update interviewQuestions.md --- interviewQuestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index 4f83c08..b176d5e 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -92,7 +92,7 @@ stop(executor); - `wait()` - release the lock or monitor - wait is used for inter-thread communication - - `java.lang.Object`类中提供了`wait()` + - `java.lang.Object`类中,提供了`wait()` - `sleep()` - doesn't release any lock or monitor while waiting - sleep is used to introduce pause on execution. From cb957c93821faa8793caef55fa104591febca278 Mon Sep 17 00:00:00 2001 From: Elessar <4529231+DIBL@users.noreply.github.com> Date: Sat, 7 Sep 2019 12:17:42 -0700 Subject: [PATCH 37/37] Update interviewQuestions.md --- interviewQuestions.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/interviewQuestions.md b/interviewQuestions.md index b176d5e..5cf572d 100644 --- a/interviewQuestions.md +++ b/interviewQuestions.md @@ -100,7 +100,10 @@ stop(executor); - sleep need try catch interruption #### 12. What is difference between CyclicBarriar and CountdownLatch in Java ? -One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse CountdownLatch. +- CountdownLatch: 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 count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier. + +- One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse CountdownLatch. Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events, main difference between them is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. #### 13. Difference between Runnable and Callable in Java?