Java / Concurrent collections
1. Explain concurrent collection API.
The java.util.concurrent package includes a number of additions to the Java Collections Framework. These collections helps preventing Memory Consistency Errors by defining a happens-before relationship between an operation that adds an object to the collection with subsequent operations that acce...
2. List some of the concurrency collection interfaces.
BlockingQueue defines a FIFO (first-in-first-out) data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue. ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-valu...
3. Explain BlockingQueue in Java concurrent collections.
BlockingQueue extends Queue interface, is a queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the fixed length queue when storing an element while it is full. A BlockingQueue does not allow...
4. What are the 4 forms of BlockingQueue methods?
BlockingQueue methods are categorized into 4 forms due to its way of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future. Methods that throws an exception , for example, add(element) throws exception while trying to add the element failed whe...
5. Does BlockingQueue supports removal of arbitrary element?
Yes. BlockingQueue supports Collection interface, it is possible to remove an arbitrary element from a queue using remove(x) method. However, such operations are not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled. It is also possib...
6. Is BlockingQueue implementations are thread safe?
Yes, BlockingQueue implementations are thread-safe. Even all the queue method action and its effects are atomic. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation.
7. Define poison pill or object in Java collections.
Poison Pill or poison object is a data item placed on the queue and when the consumer reads this item it closes down. Obviously, the poison pill will be last item placed on the queue otherwise the consumer will shut down prematurely.
8. What does drainDo method in BlockingQueue do?
drainTo method removes all available elements from this queue and adds them to the given collection. int drainTo(Collection super E> c)
9. List the implementations of BlockingQueue.
ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.
10. Does BlockingQueue allow null elements?
No. It doesn't allow and it throws NullPointerException.
11. Explain ArrayBlockingQueue in Java concurrency collections.
The ArrayBlockingQueue class implements the BlockingQueue interface. It is introduced in Java 1.5. ArrayBlockingQueue is a bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest ...
12. What is Bounded buffer?
Bounded buffer or datastructure means that it cannot store unlimited amounts of elements and there is an upper bound on the number of elements it can store at the same time. You set the upper bound at instantiation time, and after that it cannot be changed.
13. Explain DelayQueue in Java Concurrent collections.
DelayQueue class implements the BlockingQueue interface. It is introduced in Java 1.5. DelayQueue is an unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. The head of the queue is that Delayed element whose delay expired furthest in the...
14. Explain LinkedBlockingQueue in Java concurrent collections.
The LinkedBlockingQueue class implements the BlockingQueue interface. It is introduced in Java 1.5. The LinkedBlockingQueue keeps the elements internally in a linked structure (linked nodes). This linked structure can optionally have an upper bound if desired. If no upper bound is specified, Inte...
15. Explain PriorityBlockingQueue in Java concurrency collections.
The PriorityBlockingQueue class implements the BlockingQueue interface. It is introduced in Java 1.5. An unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. While this queue is logically unbounded, attempted additions may f...
16. Difference between ArrayBlockingQueue and LinkedBlockingQueue.
ArrayBlockingQueue and LinkedBlockingQueue are common implementations of the BlockingQueue interface. ArrayBlockingQueue is a fixed size bounded buffer on the other hand LinkedBlockingQueue is an optionally bounded queue built on top of Linked nodes. LinkedBlockingQueue provides higher throughput...
17. Difference between synchronizedMap and ConcurrentHashMap in Java.
The synchronizedMap(HashMap) locks the entire map while ConcurrentHashMap synchronizes or locks on the certain portion of the Map . To optimize the performance of ConcurrentHashMap , Map is divided into different Segments. ConcurrentHashMap shows good performance than synchronized version of Hash...
18. Why does ConcurrentHashMap does not allow null key or values?
The main reason that null is not allowed in ConcurrentMaps such as ConcurrentHashMaps, ConcurrentSkipListMaps is to avoid ambiguities. If map.get(key) returns null, you cannot detect whether the key explicitly maps to null or the key itself is not mapped. In a non-concurrent map, you may check th...
19. Can we use ConcurrentHashMap in a single threaded application?
Yes. However the ConcurrentHashMap is designed to work in a multi threaded environment and it will exhibit poor performance.
20. Difference between Hashtable and ConcurrentHashMap in Java.
ConcurrentHashMap uses multiple buckets to store data. This avoids read locks and greatly improves performance over a HashTable. Hashtable uses single lock for whole data. ConcurrentHashMap uses multiple locks on Segment level (16 by default) instead of whole Map. ConcurrentHashMap Locking is app...
21. What is High throughput computing?
High-throughput computing (HTC) describes the use of many computing resources over long periods of time to accomplish a computational task.
22. Difference between ConcurrentHashMap and HashMap.
ConcurrentHashMap is thread safe while HashMap is not. ConcurrentHashMap does not allow NULL key or value while HashMap allows one null key.
23. Explain SynchronousQueue in Java concurrent collections.
The SynchronousQueue class implements the BlockingQueue interface introduced in Java 1.5. SynchronousQueue is a blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity. ...
24. What is shutdown hook in Java Thread?
A shutdown hook is simply a thread that JVM invokes implicitly before it shuts down. When the JVM begins its shutdown sequence it starts all registered shutdown hooks in a random order and let runs it concurrently. When all the hooks have completed its execution JVM will then run all uninvoked fi...
25. Difference between Runnable and Callable in Java Thread.
The Callable interface is similar to Runnable, both designed for classes whose instances are executed by another thread. A Callable needs to implement call() method while a Runnable needs to implement run() method. Callable can return a value however a Runnable cannot. Callable can throw checked ...
26. How to stop a running thread in Java?
To stop threads in Java, we rely on a cooperative mechanism called Interruption. To stop a thread, all we can do is deliver it a interrupt signal, requesting that the thread stops itself at the next available opportunity. This means that threads could only signal other threads to stop, not force ...
27. Why is Thread.stop deprecated?
It is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. W...
28. Why are Thread.suspend and Thread.resume deprecated?
Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this ...
29. Difference between findMonitorDeadlockedThreads and findDeadlockedThreads in Java ThreadMXBean.
findMonitorDeadlockThreads method finds cycles of threads that are in deadlock waiting to acquire object monitors while findDeadlockedThreads finds cycles of threads that are in deadlock waiting to acquire object monitors or ownable synchronizers .
30. Define ownable synchronizer in Java thread.
An ownable synchronizer is a synchronizer that may be exclusively owned by a thread and uses AbstractOwnableSynchronizer (or its subclass) to implement its synchronization property. ReentrantLock and ReentrantReadWriteLock are 2 examples of ownable synchronizers provided by the platform. To detec...
31. Explain ThreadMXBean in Java.
ThreadMXBean gives the information about threads in JVM. ThreadMXBean gives the complete information of threads running, daemon thread, peak thread count, current thread user time.
32. Design patterns used in Java multithreading.
Immutable Object pattern, Observer Pattern.
33. Is final field initialized in constructor thread-safe?
Yes. Presence of final guarantees that other threads would see values in the map after constructor finished without any external synchronization. Without final it cannot be guaranteed in all the case. final and volatile fields will be guaranteed to be fully initialized by the time the constructor...
34. Difference between submit and execute method with ThreadPoolExecutor.
The difference is that execute does not return a Future. A task queued with execute() that generates a Throwable will cause the UncaughtExceptionHandler for the Thread running the task to be invoked. The default UncaughtExceptionHandler, which typically prints the Throwable stack trace to System....
35. If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method?
If you are in a synchronized method, then calls to other methods that are also synchronized by other threads are locked. However calls to non-synchronized methods by other threads are not locked.
36. What is defensive copying in Java?
Defensive copying is a technique where an identical, but the copy of an object is returned instead of the original object by performing deep copy. Thus any modification to the returned object will not affect the original object.
37. What is Program counter?
Program counter (PC) register keeps track of the current instruction executing at any moment. A program counter (PC) Register is created every time a new thread is created. PC keeps a pointer to the current statement that is being executed in its thread.
38. What is Java Shutdown Hook?
The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. So if you want to execute some code before JVM shuts down, use shutdown hook. public class MyShutdownHook { public static void main (String [] args) { System.out.println( "Executi...
39. When to use FixedThreadPool in Java?
N threads will be processing tasks and when all the threads are busy, tasks are added to the queue with no limit. Fixed Thread pool are ideal for CPU intensive tasks.
40. Advantages of immutable objects in multithreaded environment.
Immutable objects facilitate safe publication and prevent publishing partially constructed objects.
41. Difference between LinkedBlockingQueue and ConcurrentLinkedQueue in Java.
ConcurrentLinkedQueue is not a blocking queue while LinkedBlockingQueue implements BlockingQueue interface. LinkedBlockingQueue provides blocking methods such as put and take while ConcurrentLinkedQueue does not provide those methods.
42. How to make sure the overrided method is also synchronized in Java?
It cannot be guaranteed. However an workaround would be to create a synchronized method and invoke an abstract method from it. We also need to ensure the abstract method is directly invoked. public synchronized final void method () { absMethod(); } protected abstract void absMethod ();
43. Explain ConcurrentHashMap in Java.
Java.util.concurrent.ConcurrentHashMap is a concurrent collection class added in JDK 1.5 as a replacement of synchronized hash-based map implementations such as Hashtable and synchronized HashMap. They offer better performance and scalability over their synchronized counterpart.
44. Is ConcurrentHashMap thread-safe in Java?
Yes, ConcurrentHashMap is thread-safe in Java, two thread can modify the map without damaging its internal data structures: array and linked list. HashMap is not thread-safe and in multi threaded environment, multiple threads may damage internal data structure and may render the map completely un...
45. Can multiple threads read from ConcurrentHashMap at same time?
Yes, ConcurrentHashMap allows concurrent read without locking as reading operation doesn't require locking or thread-safety.
46. How ConcurrentHashMap works internally?
ConcurrentHashMap works similar to HashMap by storing key/value pairs and retrieving values. The difference in its implementation in terms of concurrency and how it achieves thread-safety. ConcurrentHashMap divides the map into several segments, by default 16, also known as synchronization level....
47. How does ConcurrentHashMap achieve thread-safety?
ConcurrentHashMap achieves thread-safety by dividing the map into segments and locking only the segment which requires instead of locking the whole map. It achieves thread-safety using locking but it performs better because it never locks the whole map. This technique is also known as lock stripp...
48. How to atomically update a value in ConcurrentHashMap?
Use replace() method to update the existing value at ConcurrentHashMap. It takes both old value and new value and only updates the map if the existing value in the map matches with the old value provided otherwise replace method fails by retaining false.
49. Is Iterator of ConcurrentHashMap fail-safe or fail-fast?
Iterator of ConcurrentHashMap is a fail-safe iterator so it will not throw a ConcurrentModificationException, eliminating the need to lock the map during iteration. The iterator returned by ConcurrentHashMap are also weakly consistent so if the Map is modified during iteration, it may or may not ...
50. What is Spliterator in Java 8?
Spliterator stands for Splitable Iterator. Similar to Iterator and ListIterator, It is also an Iterator interface. Spliterator is used to split given element set into multiple sets so that we can perform operations/calculations on each set in different threads independently, possibly taking advan...
51. What is reactive streaming in Java9?
Java9 has introduced reactive streams that is used for Asynchronous communication. This is based on Publish/Subscribe framework. The class java.util.concurrent.Flow provides interfaces that support the Reactive Streams.
52. Why reactive programming is preferred?
Simpler code, thus improved readablity. Abstracts away from boiler plate code to focus on business logic. Abstracts away from low-level threading, synchronization, and concurrency issues. Stream processing implies memory efficient. The model can be applied almost everywhere to solve almost any ki...
53. Explain stream pipelining in Java 8.
Stream pipelining is the concept of chaining operations together. This is done by splitting the operations that can happen on a stream into two categories, intermediate operations and terminal operations . Each intermediate operation returns an instance of Stream itself when it runs, an arbitrary...
54. How does CopyOnWriteArrayList internally works in Java?
CopyOnWriteArrayList is a thread safe variant of ArrayList introduced in Java 5. As the name indicates, whenever there is a write, it creates a fresh copy of list and perform modifications.
55. Difference between ConcurrentSkipListMap and ConcurrentHashMap.
ConcurrentSkipListMap has sorted keys while ConcurrentHashMap does not sort. ConcurrentSkipListMap is not fast as compared to ConcurrentHashMap.