| Qns-1: What do you understand by Executor Framework in Java? |
| Ans: Executor Framework in java has been introduced in JDK 5. Executor Framework handles creation of thread, creating the thread pool and checking health while running and also terminates if needed. |
|
| Qns-2: What is the role of ExecutorService in Java? |
| Ans: ExecutorService provides different methods to start and terminate thread. There are two methods execute() and submit() in ExecutorService. Execute() method is used for threads which is Runnable and submit() method is used for Callable threads. |
|
| Qns-3: What is Executors in java Executor Framework? |
Ans: Executors is a factory that provides the methods to return ExecutorService, ScheduledExecutorService, ThreadFactory. Find some method details. newFixedThreadPool(): It returns the pool with fixed number of size. We need to pass the number of threads to this method. If concurrently task are submitted more than the pool size, then rest of task need to wait in queue. It returns ExecutorService. newScheduledThreadPool: This also creates a fixed size pool but it can schedule the thread to run after some defined delay. It is useful to schedule the task. It returns ScheduledExecutorService. newCachedThreadPool(): There is no fixed size of this pool. Thread will be created at run time and if there is no task it will alive for 60 second and then die. For short lived threads this pool works good. It returns ExecutorService. |
|
| Qns-4: What is the role of FutureTask and Future in java? |
| Ans: FutureTask is a cancellable asynchronous computation in java. It can cancel the task which is running. Once the FutureTask will be cancelled, it cannot be restarted. Future is result of asynchronous computation. Future checks if task is complete and if completed it gets the output. |
|
| Qns-5: What is difference between shutdownNow() and shutdown() in Executor Framework in java? |
| Ans: shutdown() and shutdownNow() methods belongs to ExecutorService. shutdown() method tries to stop the threads and do not accept new task to execute but it completes the execution which has been submitted. shutdownNow() methods also tries to stop the running threads and will not execute any task which has been submitted but not started. |
|
| Qns-6: How to terminate a thread in Executor Framework in java? |
Ans: ExecutorService provides a method awaitTermination(long timeout, TimeUnit unit) that takes time and unit of time as an arguments. After that time thread pool is terminated. Suppose we need to terminate a task just now, then we can do asExecutorService.awaitTermination(0, TimeUnit.SECONDS)
|
|
| Qns-7: What is the role of Executors.privilegedThreadFactory() in Executor Framework? |
| Ans: privilegedThreadFactory returns a thread factory that creates thread with same permission as main thread. |
|
| Qns-8: What is the role of Executors.unconfigurableExecutorService in Executor Framework? |
| Ans: unconfigurableExecutorService returns an object that delegates all methods of ExecutorService to the given executor so that any other method cannot accessed by cast. |
|
| Qns-9: What are the different policy in Executor Framework? |
Ans: There are different policy within ThreadPoolExecutor in java. a. ThreadPoolExecutor.AbortPolicy : AbortPolicy is a handler for rejected task. It handles those task which has been rejected. b. ThreadPoolExecutor.CallerRunsPolicy : This also handles the rejected task and runs the rejected task directly. c. ThreadPoolExecutor.DiscardOldestPolicy : This handles those rejected task that is oldest and unhandled. It discards those that oldest task. d. ThreadPoolExecutor.DiscardPolicy : This is the handler for those rejected task that are rejected silently. |
|
| Qns-10: How to get return value of a callable thread in java Executor Framework? |
Ans: Using Future, we can get the return value of callable thread.
ExecutorService exService = Executors.newCachedThreadPool();
Future future=exService.submit(new CallableThread());
int val=future.get();
What is atomic operation? What are atomic classes in Java Concurrency API?
Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.
int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.
To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization. Go to this article to learn more about atomic concurrent classes.
What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?
Lock interface 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.
The advantages of a lock are
- it’s possible to make them fair
- it’s possible to make a thread responsive to interruption while waiting on a Lock object.
- it’s possible to try to acquire the lock, but return immediately or after a timeout if the lock can’t be acquired
- it’s possible to acquire and release locks in different scopes, and in different orders
What is Executors Framework?
In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface.
The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.
Creating a lot many threads with no bounds to the maximum threshold can cause application to run out of heap memory. So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused. Executors framework facilitate process of creating Thread pools in java. Check out this post to learn with example code to create thread pool using Executors framework.
What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?
java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.
What is Callable and Future?
Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Check this post for Callable Future Example.
What is FutureTask Class?
FutureTask is the base implementation class of Future interface and we can use it with Executors for asynchronous processing. Most of the time we don’t need to use FutureTask class but it comes real handy if we want to override some of the methods of Future interface and want to keep most of the base implementation. We can just extend this class and override the methods according to our requirements. Check out Java FutureTask Example post to learn how to use it and what are different methods it has.
What are Concurrent Collection Classes?
Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException.
What is Executors Class?
Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.
Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations.
What are some of the improvements in Concurrency API in Java 8?
Some important concurrent API enhancements are:
- ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
- CompletableFuture that may be explicitly completed (setting its value and status).
- Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.
|