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....
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...
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...
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....
6. Is BlockingQueue implementations are thread safe?
Yes, BlockingQueue implementations are thread-safe. Even all the queue method action and its effects are atomic.
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...
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<?
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....
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...
13. Explain DelayQueue in Java Concurrent collections.
DelayQueue class implements the BlockingQueue interface. It is introduced in Java 1.5....
14. Explain LinkedBlockingQueue in Java concurrent collections.
The LinkedBlockingQueue class implements the BlockingQueue interface. It is introduced in Java 1.5....
15. Explain PriorityBlockingQueue in Java concurrency collections.
The PriorityBlockingQueue class implements the BlockingQueue interface. It is introduced in Java 1.5....
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.
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....
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....
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....
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....
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....
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....
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....
27. Why is Thread.stop deprecated?
It is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked....
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....
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.
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....
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....
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....
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....
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....
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...
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....
47. How does ConcurrentHashMap achieve thread-safety?
Concurrent collections allow concurrent reads and writes without wrapping a synchronized collection. ConcurrentHashMap is the usual default map.
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...
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,...
50. What is Spliterator in Java 8?
Spliterator stands for Splitable Iterator. Similar to Iterator and ListIterator, It is also an Iterator interface....
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.
52. Why reactive programming is preferred?
Simpler code, thus improved readablity. Abstracts away from boiler plate code to focus on business logic....
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 ....
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.