Top 49 Java Concurrency Interview Questions
Q1. Why Is It Named Reentrantlock?
It is called ReentrantLock as there is an acquisition count number related to the lock which me while you operate lock() technique to collect a lock and also you get it then the acquisition count number is 1.
A Reentrant lock can even allow the lock holder to enter another block of code with the equal lock item as thread already owned it. In that case, if a thread that holds the lock acquires it once more, the purchase count number is incremented and the lock then desires to be released twice to clearly launch the lock.
Q2. What Is The Difference Between Arraylist And Copyonwritearraylist In Java?
ArrayList isn't always thread-secure whereas CopyOnWriteArrayList is thread-safe and in shape to be used in multi-threaded surroundings.
Iterator lower back by ArrayList is fail-rapid. Iterator again by CopyOnWriteArrayList is fail-secure.
Performance smart ArrayList is quicker as it isn't always synchronized and there is no introduced burden of thread-protection. CopyOnWriteArrayList is comparatively slower and if there are plenty of writes by way of numerous threads in an effort to degrade the performance of the CopyOnwriteArrayList as there will be copies made consistent with mutation.
Q3. What Is Trferqueue In Java?
TrferQueue interface, brought in Java 7, extends BlockingQueue interface. The extra capability provided by using TrferQueue interface is that it affords blocking approach on the way to wait until other thread gets your element.
That's the way it differs from BlockingQueue where you could simplest positioned element into queue or retrieve element from queue and block if queue is complete (while you are setting elements) or block if queue is empty (while you're retrieving factors).
TrferQueue has a blocking off technique trfer(E e) with the intention to make sure that the detail is trferred to the client, it will wait if required to do so.
Q4. What Is Readwritelock In Java?
In a multi-threading software a couple of reads can arise simultaneously for a shared resource. It is best when more than one writes manifest simultaneously or intermix of study and write that there's a threat of writing the wrong value or reading the wrong cost.
ReadWriteLock uses the same concept with the intention to enhance the overall performance by using having separate pair of locks. A ReadWriteLock keeps a pair of associated locks -
One for study-handiest operations;
and
One for writing.
The study lock can be held concurrently by means of multiple reader threads, as long as there are no writers. The write lock is distinctive.
Q5. What Is Threadpool In Java?
In a large scale software if each project uses its own thread then allocating and deallocating many thread gadgets creates a considerable memory control overhead.
Thread pool because the name indicates offers a hard and fast of threads, any challenge which has to be achieved get a thread from this pool.
// developing executor with pool of 2 threads
ExecutorService ex = Executors.NewFixedThreadPool(2);
// walking 6 obligations
ex.Execute(new Task());
ex.Execute(new Task());
ex.Execute(new Task());
ex.Execute(new Task());
ex.Execute(new Task());
ex.Execute(new Task());
//shutting down the executor carrier
ex.Shutdown();
Even if we're strolling 6 responsibilities here, some of these obligations would be run using the 2 threads from the pool.
Q6. What Is The Difference Between Reentrantlock And Synchronized?
When you operate a synchronized block or technique you just need to put in writing synchronized key-word (and provide associated item) acquiring lock and freeing it's miles done implicitly.
With ReentrantLock acquiring and releasing lock is performed by using person using lock() and release() methods.
Synchronized forces all lock acquisition and launch to occur in a block-established manner which me when multiple locks are obtained they have to be released inside the contrary order, and all locks must be launched in the same lexical scope wherein they were obtained.
ReentrantLock provides greater flexibility, it lets in a lock to be received and launched in distinct scopes, and permitting a couple of locks to be acquired and released in any order.
ReentrantLock affords additional capability over using synchronized methods and statements by means of imparting an choice for fairness, providing a non-blocking attempt to acquire a lock (tryLock()), an try and gather the lock that can be interrupted (lockInterruptibly(), and an attempt to accumulate the lock which can timeout (tryLock(lengthy, TimeUnit)).
Q7. What Is Priorityblockingqueue In Java Concurrency?
PriorityBlockingQueue magnificence implements the BlockingQueue interface. The elements of the PriorityBlockingQueue are ordered in keeping with their natural ordering, or by using a Comparator furnished at queue creation time, relying on which of the subsequent constructor is used.
PriorityBlockingQueue() - Creates a PriorityBlockingQueue with the default preliminary capability (11) that orders its elements consistent with their herbal ordering.
PriorityBlockingQueue(int initialCapacity, Comparator<? Super E> comparator) - Creates a PriorityBlockingQueue with the desired initial ability that orders its factors in keeping with the required comparator.
Q8. What Is Atomic Variable In Java?
In Java concurrency classes like AtomicInteger, AtomicLong are furnished with a int, lengthy value respectively that may be updated atomically.
These atomic variable lessons in Java concurrency like AtomicInteger, AtomicLong makes use of non-blockading algorithm. These non-blocking off algorithms use low-level atomic system instructions which include examine-and-switch as opposed to locks to make sure records integrity under concurrent access.
Q9. What Is Cyclicbarrier In Java Concurrency?
CyclicBarrier is useful in scenarios wherein you need set of threads to wait for each different to attain a not unusual barrier factor. When each thread reaches the barrier (commonplace point) you need to call await() technique on the CyclicBarrier item. This will suspend the thread until all of the thread also name the await() method on the identical CyclicBarrier object.
Once all of the designated threads have called anticipate() approach so one can ride the barrier and all threads can resume operation.
The barrier is referred to as cyclic due to the fact it could be re-used after the ready threads are launched.
Q10. What Is Countdownlatch In Java Concurrency?
CountDownLatch may be visualized as a latch that is released handiest after the given range of activities arise. CountDownLatch is initialized with that count (given variety of events).
Each time one of those activities occur rely is decremented, for that countdown() technique is used. Thread(s) which might be watching for the latch to release (cutting-edge be counted reaches zero because of invocations of the countDown()approach) are blocked using look ahead to() method.
It is beneficial inside the state of affairs when you want one or extra threads to wait till one or more activities being finished in other threads complete.
Q11. What Is Linkedtrferqueue In Java?
LinkedTrferQueue, is an implementation of the TrferQueue. It is an unbounded queue and stores factors as related nodes.
Q12. What Is Linkedblockingdeque In Java?
LinkedBlockingDeque is an implementation of the BlockingDeque interface and it was added in Java @LinkedBlockingDeque is an optionally bounded deque and it stores its elements as related nodes.
Q13. What Is Arrayblockingqueue In Java Concurrency?
Methods which need to execute the task assigned without relinquishing control to different thread are referred to as blocking off strategies.
A very applicable instance of blocking off methods, which most of you would have encountered is examine() method of theInputStream elegance. This technique blocks until input records is available, the end of the movement is detected, or an exception is thrown.
Q14. Why Concurrenthashmap Is Faster Than Hashtable In Java?
In HashTable each approach is synchronized on a unmarried lock which me at any given time only one thread can enter any technique.
ConcurrentHashMap makes use of separate lock for separate buckets for this reason locking best a part of the Map. By default there are 16 buckets and additionally separate locks for separate buckets. So the default concurrency stage is @Thus theoretically at any given time 16 threads can get entry to separate buckets with out blocking which improves the overall performance of the ConcurrentHashMap.
In ConcurrentHashMap overall performance is in addition progressed by imparting examine access concurrently without any blocking. Retrieval operations (such as get) typically do now not block, so might also overlap with replace operations (such as put and get rid of).
Q15. What Is Exchanger In Java Concurrency?
Exchanger makes it easy for 2 threads to trade statistics between themselves.
Exchanger affords a synchronization point at which two threads can pair and swap elements. Exchanger waits until separate threads name its exchange() technique. When two threads have referred to as the alternate() technique, Exchanger will switch the gadgets offered by the threads.
Q16. If A Countdownlatch Is Initialized With Some Count Let's Say 3 (new Countdownlatch(three)). Do We Need To Have 3 Threads For Countdown In That Case?
No. Same quantity of threads aren't required. A CountDownLatch initialized to N may be used to make one thread wait till N threads have finished a few action, or a few action has been completed N times.
Q17. What Is Blockingqueue In Java Concurrency?
BlockingQueueinterface is delivered in Java 5 with inside the java.Util.Concurrent package deal.
BlockingQueue is a queue which could block the operations. Which me BlockingQueue helps operations that anticipate the queue to emerge as non-empty whilst retrieving an element, and look forward to space to grow to be available inside the queue whilst storing an detail.
BlockingQueue offers following blocking techniques -
positioned(E e) - Inserts the required detail into this queue, ready if necessary for space to emerge as available.
Take() - Retrieves and eliminates the head of this queue, waiting if necessary till an detail becomes to be had.
Q18. What Is Busy Spinning? When Will You Use Busy Spinning As Waiting Strategy?
An set of rules is known as non-blockading if it would not block threads in one of these manner that simplest one thread has get right of entry to to the statistics shape and all the different threads are ready. Same way failure of any thread in a non-blocking set of rules does not mean failure or suspension of different threads.
Implementation of non-blocking off statistics structures in Java like atomic variables or ConcurrentLinkedQueue use an atomic read-regulate-write form of practise primarily based on examine-and-switch.
Q19. What Is Concurrentlinkeddequeue In Java?
ConcurrentLinkedDeque is an unbounded thread-safeDeque which stores its elements as linked nodes. Since it implements deque interface ConcurrentLinkedDequesupports element insertion and elimination at both ends.
ConcurrentLinkedDequeue is thread safe and it doesn't block operations.
Q20. What Is Executors Class?
Executors elegance offer factory and utility methods for Executors framework classes like Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable.
Though you could use ThreadPoolExecutor and ScheduledThreadPoolExecutor at once, however the first-rate way to get an executor is to apply one of the static manufacturing facility strategies provided by way of the Executors software class.
Some of the factory methods -
static ExecutorService newCachedThreadPool() - Creates a thread pool that creates new threads as needed, however will reuse formerly built threads while they are available.
Static ExecutorService newFixedThreadPool(int numThreads) - Creates a thread pool that reuses a fixed wide variety of threads.
Static ScheduledExecutorService newScheduledThreadPool(int numThreads) - Creates a thread pool which could time table commands to run after a given put off, or to execute periodically.
NewSingleThreadExecutor() - Creates an Executor that makes use of a single worker thread operating off an unbounded queue.
As example -
ExecutorService ex = Executors.NewFixedThreadPool(2);
Q21. What Is Executor In Java Concurrency?
The concurrent API has a feature referred to as executors that provides an alternative to handling threads thru the Thread magnificence. At the center of the executors is the Executor interface - An object of kind Executor can execute runnable responsibilities. An Executor is commonly used in place of explicitly creating threads.
For example If r is a Runnable object, and e is an Executor item you can update
(new Thread(r)).Start();
with
e.Execute(r);
The Executor interface gives a single approach, execute -
void execute(Runnable command)
Q22. What Do You Mean By Non-blocking off Algorithm/facts Structure?
An algorithm is called non-blockading if it would not block threads in this sort of way that most effective one thread has get admission to to the information shape and all of the other threads are waiting. Same way failure of any thread in a non-blockading algorithm doesn't imply failure or suspension of different threads.
Implementation of non-blocking facts structures in Java like atomic variables or ConcurrentLinkedQueue use an atomic examine-alter-write form of preparation primarily based on compare-and-switch.
Q23. What Is Blockingdeque In Java Concurrency?
BlockingDeque interface (introduced in Java 6) is a Deque that provides additional support for blockading operations. Blocking strategies of BlockingDeque interface come in four bureaucracy.
Throw exception - Methods falling in this category will throw exception if blocked.
Return unique fee - This type of strategies will go back some fee if need to attend, like fake.
Blocks - This type of methods will wait if necessary for space to end up to be had.
Times out - This type of techniques will block for simplest a given maximum time limit before giving up.
BlockingDeque is thread secure, does not allow null factors, and can (or won't) be capability-restrained.
Q24. What Is Concurrenthashmap In Java?
ConcurrentHashMap is likewise a hash based map like HashMap, how it differs is the locking method used by ConcurrentHashMap. Unlike HashTable (or synchronized HashMap) it doesn't synchronize each method on a not unusual lock. ConcurrentHashMap makes use of separate lock for separate buckets accordingly locking handiest a portion of the Map.
That manner ConcurrentHashMap depite being a thread secure opportunity to HashTable offers much higher overall performance.
Q25. What Is Copyonwritearrayset In Java?
CopyOnWriteArraySet is a thread-secure collection and it internally uses CopyOnWriteArrayList for all of its operations.
Since it uses CopyOnWriteArrayList internally so thread-protection is accomplished in the same way in CopyOnwriteArraySet as in CopyOnWriteArrayList - all mutative operations (add, set, and so on) are carried out via creating a fresh replica of the underlying array.
The iterator lower back with the aid of CopyOnwriteArraySet is fail-secure which me any structural amendment made to the CopyOnwriteArraySet may not throw ConcurrentModificationException.
Q26. What Is Phaser In Java Concurrency?
Phaser is extra appropriate for use where it's far required to synchronize threads over one or extra stages of hobby. Though Phaser can be used to synchronize a single section, in that case it acts more like a CyclicBarrier.
Phaser is reusable (like CyclicBarrier) and greater bendy in utilization.
The wide variety of parties registered to synchronize on a phaser can also range over the years. Tasks can be registered at any time (the use of strategies sign up(), bulkRegister(int), or through specifying preliminary range of parties inside the constructor). Tasks may also be optionally deregistered upon any arrival (using arriveAndDeregister()).
Q27. What Is Blocking Method In Java?
Methods which want to execute the challenge assigned without relinquishing control to other thread are referred to as blocking off methods.
A very applicable example of blockading strategies, which maximum of you would have encountered is examine() technique of theInputStream magnificence. This approach blocks until enter data is available, the cease of the circulation is detected, or an exception is thrown.
Q28. How To Construct A Thread Pool With 2 Threads That Executes Some Tasks That Return A Value?
You can create a hard and fast thread pool the use of the newFixedThreadPool() technique of the Executors magnificence.
// growing executor with pool of two threads
ExecutorService ex = Executors.NewFixedThreadPool(2);
// going for walks obligations
Future f1 = ex.Publish(new Task());
Future f2 = ex.Put up(new Task());
try
// getting the destiny price
System.Out.Println("Future f1 " + f1.Get());
System.Out.Println("Future f1 " + f1.Get());
trap (InterruptedException e)
// TODO Auto-generated catch block
e.PrintStackTrace();
trap (ExecutionException e)
// TODO Auto-generated catch block
e.PrintStackTrace();
ex.Shutdown();
Q29. What Is Executorservice In Java Concurrency?
ExecutorService interface extends Executor interface and affords techniques to control termination and strategies that could produce a Future for tracking progress of one or extra asynchronous obligations.
ExecutorService has more versatile submit approach. Like execute, put up accepts Runnable items, however additionally accepts Callable items, which permit the venture to return a fee. The submit approach returns a Future item, which is used to retrieve the Callable return value and to manage the status of both Callable and Runnable obligations.
Q30. What Is The Difference Between A Countdownlatch And Cyclicbarrier?
When you're the usage of a CountDownLatch, you specify the range of calls to the countdown() approach while developing a CountDownLatch object. What this me is you could use CountDownLatch with simplest a single thread and the use of countdown() to decrement as and when the desired even occur.
When you are using CyclicBarrier you specify the quantity of threads that ought to name anticipate() technique if you want to experience the barrier. That me if you have a CyclicBarrier initialized to three that me you need to have at least 3 threads to name anticipate().
CountDownLatch cannot be reused, when remember reaches zero it can't be reset.
CyclicBarrier can be reused after the waiting threads are released.
Q31. What Is Callable And Future In Java Concurrency?
Callable, an interface, became delivered in Java @It permits you to define a venture to be completed through a thread asynchronously. The Callable interface has a call() technique, due to the fact that it's far a conventional interface so it can go back any fee (Object, String, Integer and so on.) primarily based on how it's miles initialized. Main feature of the decision() approach furnished through Callable interface is that it could return fee.
Future interface - A Future represents the result of an asynchronous computation. When you publish a callable venture using the submit() technique of the ExecutorService, Future item is again.
Future offers techniques to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
Get() - get() method retrieves the end result of the computation, blockading if vital for the computation to finish.
Q32. What Is Difference Between Submit() And Execute() Method Of Executor And Executorservice In Java?
Execute() approach is supplied by means of Executor interface wherein as submit() technique is provided by ExecutorService.
Execute() technique best takes Runnable as argument - execute(Runnable command) and does no longer go back any cost.
ExecutorService has extra flexible submit() method. Post() technique is overloaded and accepts each Runnable items and Callable objects, put up also permits the assignment to return a fee (an object of type Future). The Future's get method will return the given end result upon successful finishing touch.
Q33. What Is Concurrentlinkedqueue In Java?
ConcurrentLinkedQueue is an unbounded thread-safe queue which stores its elements as linked nodes. This queue orders elements FIFO (first-in-first-out).
It would not block operations as it's miles completed within the implementations of BlockingQueue interface like ArrayBlockingQueue.
Q34. What Is A Scheduledexecutorservice?
ScheduledExecutorService extends ExecutorService and provides methods that could agenda commands to run after a given delay, or to execute periodically.
It has methods that execute a Runnable or Callable challenge after a targeted delay.
Time table(Callable<V> callable, long put off, TimeUnit unit) - Creates and executes a ScheduledFuture that turns into enabled after the given delay.
Schedule(Runnable command, lengthy delay, TimeUnit unit) - Creates and executes a one-shot movement that becomes enabled after the given postpone.
Q35. What Is Concurrentskiplistset In Java?
ConcurrentSkipListSet implements NavigableSet and it is a taken care of set much like TreeSet with introduced characteristic of being concurrent.
The factors of the set are stored taken care of consistent with their natural ordering, or by a Comparator provided at set introduction time, relying on which constructor is used.
Q36. What Is Concurrentskiplistmap In Java?
ConcurrentSkipListMap implements ConcurrentNavigableMap and it's miles a looked after map similar to TreeMap with the introduced feature of being concurrent.
ConcurrentSkipListMap is taken care of according to the natural ordering of its keys, or through a Comparator provided at map introduction time, depending on which constructor is used.
Q37. How Readwritelock Can Help In Reducing Contention Among Multiple Threads? Or What Is Benefit Of Using Readwritelock In Java?
ReadWriteLock offers separate set of locks for reading and writing operations. Where study lock can be held simultaneously with the aid of more than one reader threads, so long as there are no writers. The write lock is one-of-a-kind.
So examine operations aren't jointly one-of-a-kind. It exploits the fact that even as handiest a single thread at a time (a creator thread) can regulate the shared records, in lots of instances any quantity of threads can simultaneously read the records (therefore reader threads).
Thus inside the applications where reads are extra than writes or period of reads is extra the thread competition might be less as read lock is shared by way of many thread in preference to being jointly unique. So you won't have a state of affairs where only one thread is reading and different threads are waiting.
Q38. What Is Reentrantlock In Java?
ReentrantLock is a concrete implementation of the Lock interface that is gift injava.Util.Concurrent.Locks package.
Every item created in Java has one together special lock related to it. When you are the use of synchronized you are the usage of that lock implicitly (without a other function) whereas whilst you are the usage of any of the lock implementation (like Reentrant lock) you're the use of that lock explicitly. Which me there are strategies like lock() to gather the lock and unlock() to launch the lock. Along with that ReentrantLock provides many other features like equity, capability to break and a thread waiting for a lock most effective for a unique period.
Q39. How Can I Immediately Block A Thread Even If I Am Using Submit Method And Using A Callable Object?
If you would like to at once block anticipating a project, you can use constructions of the form
result = exec.Publish(aCallable).Get();
Q40. What Is Synchronous Queue In Java?
SynchronousQueue is an implementation of the BlockingQueue interface. SynchronousQueue does now not have any internal potential, no longer even a capacity of one. In SynchronousQueue every insert operation must watch for a corresponding take away operation via another thread, and vice versa.
If you positioned an detail in SynchronousQueue the usage of put() approach it'll anticipate some other thread to get hold of it, you cannot positioned any other detail in the SynchronousQueue as it is blocked.
Q41. What Is Linkedblockingqueue In Java Concurrency?
LinkedBlockingQueue is an implementation of BlockingQueue interface.
LinkedBlockingQueue internally makes use of linked nodes to store factors. It is optionally bounded and that's in which it differs from ArrayBlockingQueue that is bounded.
Q42. What Is Copyonwritearraylist In Java?
CopyOnWriteArrayList is likewise an implementation of the List interface but it's far a thread safe version. This thread protection is accomplished through creating a fresh copy of the underlying array with each mutative operations (add, set, and so forth).
Using CopyOnWriteArrayList offers higher overall performance in eventualities wherein there are more iterations of the listing than mutations.
Q43. What Is Reentrantreadwritelock In Java Concurrency?
ReentrantReadWriteLock is an implementation of the ReadWriteLock interface which presents a pair of study-write lock.
To get a read lock you want to apply - rw.ReadLock().Lock();
To get a write lock you want to apply - rw.WriteLock().Lock();
Where rw is an object of ReentrantReadWriteLock magnificence.
ReentrantReadWriteLock additionally permits downgrading from the write lock to a study lock. You can first gather a write lock, then the examine lock and then release the write lock.
Q44. How To Shut Down An Executorservice?
An ExecutorService can be shut down, so one can reason it to reject new tasks. Two special methods are furnished for shutting down an ExecutorService.
The shutdown() technique will permit previously submitted duties to execute earlier than terminating, while the shutdownNow() method prevents waiting duties from starting and attempts to prevent currently executing duties. Upon termination, an executor has no obligations actively executing, no tasks looking ahead to execution, and no new obligations can be submitted.
Q45. Name Any Class That Implements Executor Or Executorservice Interface?
In the Java concurrency there are 3 pre defined executor classes that implement the Executor and ExecutorService interface.
ThreadPoolExecutor - Implements the Executor and ExecutorService interfaces and executes the submitted mission the use of one of the pooled thread.
ScheduledThreadPoolExecutor - It extends ThreadPoolExecutor and also implements the ScheduledExecutorService. This class agenda commands to run after a given put off, or to execute periodically.
ForkJoinPool - It implements the Executor and ExecutorService interfaces and is used by the Fork/Join Framework.
Q46. What Is Semaphore In Java Concurrency?
The Semaphore elegance present in java.Util.Concurrent bundle is a counting semaphore wherein a semaphore, conceptually, maintains a fixed of allows. Thread that desires to get entry to the shared useful resource attempts to collect a allow the usage of collect() method. At that time if the Semaphore's matter is greater than 0 thread will gather a allow and Semaphore's remember could be decremented with the aid of one. If Semaphore's rely is zero, while thread calls gather() approach, then the thread could be blocked till a permit is to be had. When thread is carried out with the shared useful resource get right of entry to, it could call the discharge() approach to release the allow. That consequences in the Semaphore's count incremented by way of one.
Q47. What Is Delayqueue In Java Concurrency?
DelayQueue is an unbounded implementation of BlockingQueue interface. DelayQueue can store elements of kind Delayed most effective and an element can only be retrieved from DelayQueue while its postpone has expired.
When you enforce Delayed interface two strategies must be implementedgetDelay(TimeUnit unit) and compareTo(T o).
GetDelay(TimeUnit unit) - Returns the last postpone associated with this item, in the given time unit.
Q48. What Is Lock Striping In Concurrent Programming?
The concept of lock striping is to have separate locks for a portion of a records structure wherein each lock is locking on a variable sized set of independent objects.
That's how ConcurrentHashMap in Java provides synchronization. By default ConcurrentHashMap has sixteen buckets and every bucket has its very own lock so there are 16 locks too. So the threads which can be having access to keys in separate buckets can get admission to them concurrently.
Q49. What Is The Difference Between Hashmap And Concurrenthashmap In Java?
ConcurrentHashMap is thread secure and match for use in a multi-threaded surroundings while HashMap is not thread safe.
HashMap may be synchronized using the Collections.SynchronizedMap() method however that synchronizes all the methods of the HashMap and effectively reduces it to a records structure in which one thread can input at a time.
In ConcurrentHashMap synchronization is completed a touch otherwise. Rather than locking each approach on a not unusual lock, ConcurrentHashMap makes use of separate lock for separate buckets therefore locking best a part of the Map.

