Prev Next

Java / Concurrent collections

1. Explain concurrent collection API. 2. List some of the concurrency collection interfaces. 3. Explain BlockingQueue in Java concurrent collections. 4. What are the 4 forms of BlockingQueue methods? 5. Does BlockingQueue supports removal of arbitrary element? 6. Is BlockingQueue implementations are thread safe? 7. Define poison pill or object in Java collections. 8. What does drainDo method in BlockingQueue do? 9. List the implementations of BlockingQueue. 10. Does BlockingQueue allow null elements? 11. Explain ArrayBlockingQueue in Java concurrency collections. 12. What is Bounded buffer? 13. Explain DelayQueue in Java Concurrent collections. 14. Explain LinkedBlockingQueue in Java concurrent collections. 15. Explain PriorityBlockingQueue in Java concurrency collections. 16. Difference between ArrayBlockingQueue and LinkedBlockingQueue. 17. Difference between synchronizedMap and ConcurrentHashMap in Java. 18. Why does ConcurrentHashMap does not allow null key or values? 19. Can we use ConcurrentHashMap in a single threaded application? 20. Difference between Hashtable and ConcurrentHashMap in Java. 21. What is High throughput computing? 22. Difference between ConcurrentHashMap and HashMap. 23. Explain SynchronousQueue in Java concurrent collections. 24. What is shutdown hook in Java Thread? 25. Difference between Runnable and Callable in Java Thread. 26. How to stop a running thread in Java? 27. Why is Thread.stop deprecated? 28. Why are Thread.suspend and Thread.resume deprecated? 29. Difference between findMonitorDeadlockedThreads and findDeadlockedThreads in Java ThreadMXBean. 30. Define ownable synchronizer in Java thread. 31. Explain ThreadMXBean in Java. 32. Design patterns used in Java multithreading. 33. Is final field initialized in constructor thread-safe? 34. Difference between submit and execute method with ThreadPoolExecutor. 35. If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method? 36. What is defensive copying in Java? 37. What is Program counter? 38. What is Java Shutdown Hook? 39. When to use FixedThreadPool in Java? 40. Advantages of immutable objects in multithreaded environment. 41. Difference between LinkedBlockingQueue and ConcurrentLinkedQueue in Java. 42. How to make sure the overrided method is also synchronized in Java? 43. Explain ConcurrentHashMap in Java. 44. Is ConcurrentHashMap thread-safe in Java? 45. Can multiple threads read from ConcurrentHashMap at same time? 46. How ConcurrentHashMap works internally? 47. How does ConcurrentHashMap achieve thread-safety? 48. How to atomically update a value in ConcurrentHashMap? 49. Is Iterator of ConcurrentHashMap fail-safe or fail-fast? 50. What is Spliterator in Java 8? 51. What is reactive streaming in Java9? 52. Why reactive programming is preferred? 53. Explain stream pipelining in Java 8. 54. How does CopyOnWriteArrayList internally works in Java? 55. Difference between ConcurrentSkipListMap and ConcurrentHashMap.
Could not find what you were looking for? send us the question and we would be happy to answer your question.

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...

Read full answer

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...

Read full answer

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...

Read full answer

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...

Read full answer

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...

Read full answer

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.

Read full answer

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.

Read full answer

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 c)

Read full answer

9. List the implementations of BlockingQueue.

ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

Read full answer

10. Does BlockingQueue allow null elements?

No. It doesn't allow and it throws NullPointerException.

Read full answer

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 ...

Read full answer

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.

Read full answer

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...

Read full answer

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...

Read full answer

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...

Read full answer

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...

Read full answer

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...

Read full answer

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...

Read full answer

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.

Read full answer

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...

Read full answer

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.

Read full answer

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.

Read full answer

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. ...

Read full answer

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...

Read full answer

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 ...

Read full answer

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 ...

Read full answer

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...

Read full answer

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 ...

Read full answer

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 .

Read full answer

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...

Read full answer

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.

Read full answer

32. Design patterns used in Java multithreading.

Immutable Object pattern, Observer Pattern.

Read full answer

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...

Read full answer

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....

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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...

Read full answer

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.

Read full answer

40. Advantages of immutable objects in multithreaded environment.

Immutable objects facilitate safe publication and prevent publishing partially constructed objects.

Read full answer

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.

Read full answer

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 ();

Read full answer

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.

Read full answer

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...

Read full answer

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.

Read full answer

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....

Read full answer

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...

Read full answer

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.

Read full answer

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 ...

Read full answer

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...

Read full answer

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.

Read full answer

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...

Read full answer

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...

Read full answer

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.

Read full answer

55. Difference between ConcurrentSkipListMap and ConcurrentHashMap.

ConcurrentSkipListMap has sorted keys while ConcurrentHashMap does not sort. ConcurrentSkipListMap is not fast as compared to ConcurrentHashMap.

Read full answer

«
»

Comments & Discussions