YouTube Icon

Interview Questions.

Top 100+ Java Concurrency Interview Questions And Answers - May 31, 2020

fluid

Top 100+ Java Concurrency Interview Questions And Answers

Question 1. What Is Countdownlatch In Java Concurrency?

Answer :

CountDownLatch may be visualized as a latch that is launched only after the given quantity of occasions occur. CountDownLatch is initialized with that rely (given variety of events).

Each time one of these occasions arise matter is decremented, for that countdown() method is used. Thread(s) which can be awaiting the latch to release (contemporary count reaches 0 due to invocations of the countDown()method) are blocked the use of wait for() method.

It is beneficial inside the scenario when you want one or more threads to attend until one or greater events being executed in different threads whole.

Question 2. What Is Cyclicbarrier In Java Concurrency?

Answer :

CyclicBarrier is useful in scenarios wherein you need set of threads to wait for every other to attain a commonplace barrier factor. When each thread reaches the barrier (commonplace point) you want to name look forward to() technique at the CyclicBarrier item. This will suspend the thread till all of the thread also name the watch for() technique on the same CyclicBarrier item.

Once all the special threads have referred to as watch for() method so one can experience the barrier and all threads can resume operation.

The barrier is referred to as cyclic because it can be re-used after the ready threads are released.

Adv Java Interview Questions
Question 3. What Is The Difference Between A Countdownlatch And Cyclicbarrier?

Answer :

When you're using a CountDownLatch, you specify the number of calls to the countdown() technique whilst developing a CountDownLatch item. What this means is you can use CountDownLatch with only a unmarried thread and the usage of countdown() to decrement as and while the desired even occur.

When you're the use of CyclicBarrier you specify the wide variety of threads that must call wait for() approach so one can journey the barrier. That method when you have a CyclicBarrier initialized to three that means you should have at least 3 threads to call wait for().
CountDownLatch can't be reused, when matter reaches zero it cannot be reset.

CyclicBarrier may be reused after the ready threads are launched.
Question 4. If A Countdownlatch Is Initialized With Some Count Let's Say three (new Countdownlatch(3)). Do We Need To Have three Threads For Countdown In That Case?

Answer :

No. Same range of threads aren't required. A CountDownLatch initialized to N may be used to make one thread wait till N threads have finished some movement, or some movement has been finished N times.

Adv Java Tutorial
Question five. What Is Phaser In Java Concurrency?

Answer :

Phaser is greater appropriate to be used in which it's far required to synchronize threads over one or greater levels of activity. Though Phaser can be used to synchronize a single segment, in that case it acts greater like a CyclicBarrier.

Phaser is reusable (like CyclicBarrier) and more flexible in utilization.

The number of events registered to synchronize on a phaser might also range over time. Tasks can be registered at any time (using strategies check in(), bulkRegister(int), or by way of specifying preliminary quantity of parties in the constructor). Tasks can also be optionally deregistered upon any arrival (the usage of arriveAndDeregister()).

J2EE Interview Questions
Question 6. What Is Exchanger In Java Concurrency?

Answer :

Exchanger makes it clean for 2 threads to exchange information between themselves.

Exchanger affords a synchronization point at which two threads can pair and switch elements. Exchanger waits until  separate threads call its change() method. When  threads have called the exchange() method, Exchanger will change the items provided by means of the threads.

Question 7. What Is Semaphore In Java Concurrency?

Answer :

The Semaphore elegance present in java.Util.Concurrent package deal is a counting semaphore wherein a semaphore, conceptually, maintains a fixed of permits. Thread that desires to get admission to the shared resource attempts to collect a allow the use of gather() technique. At that point if the Semaphore's remember is extra than zero thread will gather a allow and Semaphore's be counted can be decremented via one. If Semaphore's remember is 0, while thread calls accumulate() approach, then the thread can be blocked until a allow is available. When thread is achieved with the shared aid access, it is able to call the release() technique to release the permit. That consequences inside the Semaphore's remember incremented by using one.

J2EE Tutorial Core Java Interview Questions
Question eight. What Is Reentrantlock In Java?

Answer :

ReentrantLock is a concrete implementation of the Lock interface that's gift injava.Util.Concurrent.Locks package deal.

Every object created in Java has one collectively one of a kind lock associated with it. When you are the use of synchronized you're the usage of that lock implicitly (with no different characteristic) while while you are the usage of any of the lock implementation (like Reentrant lock) you're the use of that lock explicitly. Which method there are methods like lock() to acquire the lock and free up() to launch the lock. Along with that ReentrantLock provides many other features like equity, ability to interrupt and a thread looking ahead to a lock simplest for a unique length.

Question nine. What Is The Difference Between Reentrantlock And Synchronized?

Answer :

When you use a synchronized block or approach you just need to put in writing synchronized key-word (and offer related object) obtaining lock and releasing it's miles accomplished implicitly.
With ReentrantLock obtaining and freeing lock is performed by means of person using lock() and release() techniques.

Synchronized forces all lock acquisition and release to arise in a block-dependent way which means whilst multiple locks are received they ought to be launched inside the opposite order, and all locks need to be released inside the same lexical scope in which they were acquired.

ReentrantLock presents extra flexibility, it allows a lock to be received and launched in unique scopes, and allowing a couple of locks to be obtained and launched in any order.

ReentrantLock affords extra capability over the usage of synchronized techniques and statements by using providing an choice for equity, supplying a non-blocking try and collect a lock (tryLock()), an attempt to gather the lock that may be interrupted (lockInterruptibly(), and an try to gather the lock which can timeout (tryLock(long, TimeUnit)).
JSP Interview Questions
Question 10. Why Is It Named Reentrantlock?

Answer :

It is called ReentrantLock as there may be an acquisition rely related to the lock which means that when you operate lock() approach to collect a lock and you get it then the purchase depend is 1.

A Reentrant lock may even permit the lock holder to go into some other block of code with the equal lock object as thread already owned it. In that case, if a thread that holds the lock acquires it once more, the purchase be counted is incremented and the lock then desires to be launched two times to in reality release the lock.

Core Java Tutorial
Question eleven. What Is Readwritelock In Java?

Answer :

In a multi-threading application a couple of reads can arise simultaneously for a shared aid. It is only when more than one writes show up simultaneously or intermix of study and write that there's a danger of writing the wrong fee or analyzing the wrong price.

ReadWriteLock makes use of the equal concept on the way to enhance the performance by means of having separate pair of locks. A ReadWriteLock maintains a pair of related locks -

One for read-handiest operations;
and
One for writing.
The examine lock may be held concurrently by means of more than one reader threads, so long as there are not any writers. The write lock is different.

Java-Springs Interview Questions
Question 12. What Is Reentrantreadwritelock In Java Concurrency?

Answer :

ReentrantReadWriteLock is an implementation of the ReadWriteLock interface which affords a pair of read-write lock.

To get a read lock you need to use - rw.ReadLock().Lock();
To get a write lock you want to apply - rw.WriteLock().Lock();
Where rw is an object of ReentrantReadWriteLock elegance.

ReentrantReadWriteLock additionally lets in downgrading from the write lock to a read lock. You can first gather a write lock, then the examine lock after which launch the write lock.

Adv Java Interview Questions
Question thirteen. How Readwritelock Can Help In Reducing Contention Among Multiple Threads? Or What Is Benefit Of Using Readwritelock In Java?

Answer :

ReadWriteLock offers separate set of locks for analyzing and writing operations. Where examine lock may be held concurrently by way of more than one reader threads, so long as there are not any writers. The write lock is distinctive.

So examine operations aren't at the same time different. It exploits the truth that while handiest a single thread at a time (a creator thread) can modify the shared data, in lots of cases any quantity of threads can simultaneously study the records (as a result reader threads).

Thus inside the programs wherein reads are greater than writes or length of reads is more the thread contention could be much less as examine lock is shared through many thread rather than being mutually special. So you won't have a state of affairs wherein only one thread is analyzing and different threads are ready.

JSP Tutorial
Question 14. What Is Concurrenthashmap In Java?

Answer :

ConcurrentHashMap is also a hash based map like HashMap, how it differs is the locking method utilized by ConcurrentHashMap. Unlike HashTable (or synchronized HashMap) it does not synchronize every method on a common lock. ConcurrentHashMap uses separate lock for separate buckets as a consequence locking best a part of the Map.

That way ConcurrentHashMap depite being a thread safe opportunity to HashTable gives a whole lot higher performance.

Question 15. What Is Lock Striping In Concurrent Programming?

Answer :

The idea of lock striping is to have separate locks for a portion of a information shape in which each lock is locking on a variable sized set of independent objects.

That's how ConcurrentHashMap in Java offers synchronization. By default ConcurrentHashMap has 16 buckets and each bucket has its own lock so there are sixteen locks too. So the threads that are gaining access to keys in separate buckets can get admission to them simultaneously.

JMS(Java Message Service) Interview Questions
Question sixteen. What Is The Difference Between Hashmap And Concurrenthashmap In Java?

Answer :

ConcurrentHashMap is thread safe and in shape to be used in a multi-threaded surroundings while HashMap isn't thread secure.
HashMap can be synchronized the usage of the Collections.SynchronizedMap() technique but that synchronizes all the strategies of the HashMap and efficaciously reduces it to a data structure wherein one thread can enter at a time.
In ConcurrentHashMap synchronization is performed a little in another way. Rather than locking every technique on a common lock, ConcurrentHashMap uses separate lock for separate buckets as a consequence locking best a part of the Map.

Java-Springs Tutorial
Question 17. Why Concurrenthashmap Is Faster Than Hashtable In Java?

Answer :

In HashTable each approach is synchronized on a single lock which means that at any given time simplest one thread can enter any technique. 

ConcurrentHashMap uses separate lock for separate buckets consequently locking handiest a part of the Map. By default there are sixteen buckets and also separate locks for separate buckets. So the default concurrency stage is 16. Thus theoretically at any given time sixteen threads can access separate buckets without blocking off which improves the overall performance of the ConcurrentHashMap.

In ConcurrentHashMap overall performance is in addition progressed by using presenting study get entry to simultaneously without any blocking. Retrieval operations (which includes get) usually do no longer block, so may additionally overlap with update operations (along with positioned and put off).

Java applet Interview Questions
Question 18. What Is Copyonwritearraylist In Java?

Answer :

CopyOnWriteArrayList is likewise an implementation of the List interface however it's far a thread secure variant. This thread safety is carried out by creating a fresh reproduction of the underlying array with every mutative operations (upload, set, and so forth).

Using CopyOnWriteArrayList offers better performance in scenarios wherein there are greater iterations of the list than mutations.

J2EE Interview Questions
Question 19. What Is The Difference Between Arraylist And Copyonwritearraylist In Java?

Answer :

ArrayList is not thread-secure whereas CopyOnWriteArrayList is thread-secure and suit for use in multi-threaded environment.

Iterator returned via ArrayList is fail-fast. Iterator back by CopyOnWriteArrayList is fail-secure.

Performance sensible ArrayList is faster as it is not synchronized and there may be no delivered burden of thread-protection. CopyOnWriteArrayList is relatively slower and if there are plenty of writes with the aid of various threads in an effort to degrade the overall performance of the CopyOnwriteArrayList as there may be copies made per mutation.

Java Tutorial
Question 20. What Is Copyonwritearrayset In Java?

Answer :

CopyOnWriteArraySet is a thread-safe series and it internally makes use of CopyOnWriteArrayList for all of its operations.

Since it uses CopyOnWriteArrayList internally so thread-protection is finished in the equal way in CopyOnwriteArraySet as in CopyOnWriteArrayList - all mutative operations (add, set, and so on) are applied via making a clean reproduction of the underlying array.

The iterator again by CopyOnwriteArraySet is fail-safe because of this any structural change made to the CopyOnwriteArraySet might not throw ConcurrentModificationException.

Java Interview Questions
Question 21. What Is Concurrentskiplistmap In Java?

Answer :

ConcurrentSkipListMap implements ConcurrentNavigableMap and it is a looked after map just like TreeMap with the introduced characteristic of being concurrent.

ConcurrentSkipListMap is taken care of in keeping with the herbal ordering of its keys, or by way of a Comparator provided at map creation time, depending on which constructor is used.

Question 22. What Is Concurrentskiplistset In Java?

Answer :

ConcurrentSkipListSet implements NavigableSet and it's miles a taken care of set just like TreeSet with delivered feature of being concurrent.

The elements of the set are kept looked after in step with their herbal ordering, or through a Comparator supplied at set introduction time, relying on which constructor is used.

Java eight Tutorial
Question 23. What Is Concurrentlinkedqueue In Java?

Answer :

ConcurrentLinkedQueue is an unbounded thread-secure queue which shops its factors as linked nodes. This queue orders factors FIFO (first-in-first-out).

It doesn't block operations as it is achieved within the implementations of BlockingQueue interface like ArrayBlockingQueue.

Java 8 Interview Questions
Question 24. What Is Concurrentlinkeddequeue In Java?

Answer :

ConcurrentLinkedDeque is an unbounded thread-safeDeque which stores its factors as connected nodes. Since it implements deque interface ConcurrentLinkedDequesupports detail insertion and removal at both ends.

ConcurrentLinkedDequeue is thread safe and it does not block operations.

Core Java Interview Questions
Question 25. What Do You Mean By Non-blockading Algorithm/data Structure?

Answer :

An algorithm is referred to as non-blockading if it does not block threads in this kind of manner that handiest one thread has get entry to to the records shape and all the different threads are waiting. Same manner failure of any thread in a non-blocking off set of rules would not imply failure or suspension of other threads.

Implementation of non-blocking off facts structures in Java like atomic variables or ConcurrentLinkedQueue use an atomic read-regulate-write sort of practise based on evaluate-and-switch.

Question 26. What Is Busy Spinning? When Will You Use Busy Spinning As Waiting Strategy?

Answer :

An set of rules is called non-blocking off if it does not block threads in one of these manner that simplest one thread has get right of entry to to the data shape and all of the different threads are ready. Same manner failure of any thread in a non-blocking algorithm doesn't imply failure or suspension of different threads.

Implementation of non-blocking off data systems in Java like atomic variables or ConcurrentLinkedQueue use an atomic examine-modify-write type of instruction based on compare-and-change.

Java Programmer Interview Questions
Question 27. What Is Blockingqueue In Java Concurrency?

Answer :

BlockingQueueinterface is added in Java five with inside the java.Util.Concurrent bundle.

BlockingQueue is a queue which could block the operations. Which means BlockingQueue supports operations that wait for the queue to end up non-empty when retrieving an element, and look forward to area to come to be available inside the queue when storing an element.

BlockingQueue presents following blocking techniques -

positioned(E e) - Inserts the desired element into this queue, ready if necessary for space to turn out to be available.
Take() - Retrieves and eliminates the pinnacle of this queue, ready if essential until an element becomes available.
JSP Interview Questions
Question 28. What Is Blocking Method In Java?

Answer :

Methods which want to execute the task assigned without relinquishing manage to other thread are known as blockading techniques.

A very applicable example of blocking off techniques, which most of you will have encountered is study() method of theInputStream class. This technique blocks till input statistics is available, the cease of the circulation is detected, or an exception is thrown.

Question 29. What Is Arrayblockingqueue In Java Concurrency?

Answer :

Methods which want to execute the project assigned without relinquishing manage to other thread are called blocking methods.

A very relevant example of blocking off methods, which most of you would have encountered is study() method of theInputStream magnificence. This technique blocks till input records is to be had, the give up of the move is detected, or an exception is thrown.

Question 30. What Is Linkedblockingqueue In Java Concurrency?

Answer :

LinkedBlockingQueue is an implementation of BlockingQueue interface.

LinkedBlockingQueue internally makes use of connected nodes to keep elements. It is optionally bounded and that's in which it differs from ArrayBlockingQueue that is bounded.

Question 31. What Is Priorityblockingqueue In Java Concurrency?

Answer :

PriorityBlockingQueue elegance implements the BlockingQueue interface. The elements of the PriorityBlockingQueue are ordered in keeping with their herbal ordering, or by way of a Comparator supplied at queue creation time, depending on which of the subsequent constructor is used.

PriorityBlockingQueue() - Creates a PriorityBlockingQueue with the default preliminary capacity (11) that orders its factors in keeping with their herbal ordering.
PriorityBlockingQueue(int initialCapacity, Comparator<? Super E> comparator) - Creates a PriorityBlockingQueue with the desired initial potential that orders its elements in keeping with the desired comparator.
Question 32. What Is Synchronous Queue In Java?

Answer :

SynchronousQueue is an implementation of the BlockingQueue interface. SynchronousQueue does not have any internal potential, no longer even a potential of one. In SynchronousQueue each insert operation have to anticipate a corresponding dispose of operation through every other thread, and vice versa.

If you placed an element in SynchronousQueue the use of positioned() method it's going to anticipate every other thread to acquire it, you cannot placed some other element inside the SynchronousQueue as it's miles blocked.

Question 33. What Is Delayqueue In Java Concurrency?

Answer :

DelayQueue is an unbounded implementation of BlockingQueue interface. DelayQueue can store factors of type Delayed most effective and an detail can most effective be retrieved from DelayQueue when its delay has expired.

When you put into effect Delayed interface two techniques need to be implementedgetDelay(TimeUnit unit) and compareTo(T o).

GetDelay(TimeUnit unit) - Returns the ultimate postpone related to this item, inside the given time unit.

Java-Springs Interview Questions
Question 34. What Is Transferqueue In Java?

Answer :

TransferQueue interface, brought in Java 7, extends BlockingQueue interface. The extra functionality provided by TransferQueue interface is that it gives blockading technique so one can wait until different thread receives your element.

That's the way it differs from BlockingQueue wherein you can handiest placed detail into queue or retrieve detail from queue and block if queue is full (even as you are placing factors) or block if queue is empty (even as you're retrieving elements).

TransferQueue has a blocking off approach switch(E e) which will make certain that the detail is transferred to the patron, it'll wait if required to achieve this.

Question 35. What Is Linkedtransferqueue In Java?

Answer :

LinkedTransferQueue, is an implementation of the TransferQueue. It is an unbounded queue and shops elements as connected nodes.

Question 36. What Is Blockingdeque In Java Concurrency?

Answer :

BlockingDeque interface (added in Java 6) is a Deque that offers extra guide for blockading operations. Blocking strategies of BlockingDeque interface are available 4 paperwork.

Throw exception - Methods falling in this class will throw exception if blocked.
Return unique fee - This sort of strategies will return a few fee if need to wait, like false.
Blocks - This type of techniques will wait if important for space to emerge as available.
Times out - This sort of strategies will block for most effective a given most time restrict earlier than giving up.
BlockingDeque is thread safe, does no longer permit null elements, and can (or won't) be capability-constrained.

JMS(Java Message Service) Interview Questions
Question 37. What Is Linkedblockingdeque In Java?

Answer :

LinkedBlockingDeque is an implementation of the BlockingDeque interface and it changed into introduced in Java 6. LinkedBlockingDeque is an optionally bounded deque and it shops its factors as connected nodes.

Question 38. What Is Executor In Java Concurrency?

Answer :

The concurrent API has a function referred to as executors that gives an opportunity to managing threads via the Thread class. At the core of the executors is the Executor interface - An item of kind Executor can execute runnable responsibilities. An Executor is usually used instead of explicitly creating threads.

For instance If r is a Runnable item, and e is an Executor object you may update

(new Thread(r)).Begin();
with
e.Execute(r);

The Executor interface gives a single technique, execute -

void execute(Runnable command)

Question 39. What Is Executorservice In Java Concurrency?

Answer :

ExecutorService interface extends Executor interface and provides techniques to control termination and methods that could produce a Future for monitoring development of one or greater asynchronous tasks.

ExecutorService has more flexible publish technique. Like execute, submit accepts Runnable items, however also accepts Callable gadgets, which allow the assignment to return a price. The submit method returns a Future object, which is used to retrieve the Callable return price and to control the repute of both Callable and Runnable obligations.

Question forty. Name Any Class That Implements Executor Or Executorservice Interface?

Answer :

In the Java concurrency there are three pre defined executor classes that put into effect the Executor and ExecutorService interface.

ThreadPoolExecutor - Implements the Executor and ExecutorService interfaces and executes the submitted mission using one of the pooled thread.
ScheduledThreadPoolExecutor - It extends ThreadPoolExecutor and additionally implements the ScheduledExecutorService. This class schedule instructions to run after a given delay, or to execute periodically.
ForkJoinPool - It implements the Executor and ExecutorService interfaces and is utilized by the Fork/Join Framework.
Java applet Interview Questions
Question 41. What Is Difference Between Submit() And Execute() Method Of Executor And Executorservice In Java?

Answer :

execute() approach is supplied by Executor interface where as submit() method is provided by ExecutorService.
Execute() method most effective takes Runnable as argument - execute(Runnable command) and does not return any value.
ExecutorService has greater flexible post() approach. Post() technique is overloaded and accepts each Runnable gadgets and Callable items, publish also lets in the undertaking to return a value (an object of kind Future). The Future's get approach will return the given result upon a success finishing touch.
Question 42. How Can I Immediately Block A Thread Even If I Am Using Submit Method And Using A Callable Object?

Answer :

If you would really like to immediately block awaiting a undertaking, you may use structures of the form

end result = exec.Put up(aCallable).Get();

Java Interview Questions
Question 43. What Will Happen If Submit Method Can’t Schedule A Task For Execution?

Answer :

It will throw RejectedExecutionException.

Question 44. How To Shut Down An Executorservice?

Answer :

An ExecutorService can be shut down, with the intention to reason it to reject new obligations. Two different techniques are furnished for shutting down an ExecutorService. 

The shutdown() approach will allow previously submitted duties to execute before terminating, while the shutdownNow() approach prevents ready tasks from starting and attempts to prevent currently executing obligations. Upon termination, an executor has no obligations actively executing, no duties looking forward to execution, and no new responsibilities can be submitted.

Question forty five. What Is A Scheduledexecutorservice?

Answer :

ScheduledExecutorService extends ExecutorService and offers methods that can time table instructions to run after a given delay, or to execute periodically.

It has techniques that execute a Runnable or Callable project after a designated postpone.

Schedule(Callable<V> callable, long postpone, TimeUnit unit) - Creates and executes a ScheduledFuture that becomes enabled after the given postpone.
Schedule(Runnable command, lengthy delay, TimeUnit unit) - Creates and executes a one-shot motion that turns into enabled after the given delay.
Question 46. What Is Executors Class?

Answer :

Executors class provide factory and utility strategies for Executors framework lessons like Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable.

Though you may use ThreadPoolExecutor and ScheduledThreadPoolExecutor at once, however the quality way to get an executor is to apply one of the static manufacturing facility techniques supplied through the Executors utility class.

Some of the factory methods -

static ExecutorService newCachedThreadPool() - Creates a thread pool that creates new threads as wanted, but will reuse formerly built threads whilst they are available.
Static ExecutorService newFixedThreadPool(int numThreads) - Creates a thread pool that reuses a set quantity of threads.
Static ScheduledExecutorService newScheduledThreadPool(int numThreads) - Creates a thread pool that could time table instructions to run after a given put off, or to execute periodically.
NewSingleThreadExecutor() - Creates an Executor that makes use of a single worker thread working off an unbounded queue.
As example -

ExecutorService ex = Executors.NewFixedThreadPool(2);

Question forty seven. What Is Threadpool In Java?

Answer :

In a big scale application if every task makes use of its personal thread then allocating and deallocating many thread items creates a full-size memory control overhead.

Thread pool as the call shows provides a hard and fast of threads, any project which must be performed get a thread from this pool.

// growing executor with pool of 2 threads
  ExecutorService ex = Executors.NewFixedThreadPool(2);
  // strolling 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 provider
  ex.Shutdown();

Even if we're running 6 tasks right here, a lot of these responsibilities could be run the use of the 2 threads from the pool.

Question 48. How To Construct A Thread Pool With 2 Threads That Executes Some Tasks That Return A Value?

Answer :

You can create a set thread pool using the newFixedThreadPool() technique of the Executors class.

// creating executor with pool of 2 threads
  ExecutorService ex = Executors.NewFixedThreadPool(2);
  // strolling responsibilities
  Future f1 = ex.Submit(new Task());
  Future f2 = ex.Put up(new Task());
  try 
   // getting the destiny cost
   System.Out.Println("Future f1 " + f1.Get());
   System.Out.Println("Future f1 " + f1.Get());
   seize (InterruptedException e) 
   // TODO Auto-generated capture block
   e.PrintStackTrace();
   trap (ExecutionException e) 
   // TODO Auto-generated trap block
   e.PrintStackTrace();
  
  ex.Shutdown();

Question 49. What Is Callable And Future In Java Concurrency?

Answer :

Callable, an interface, changed into introduced in Java five. It permits you to define a challenge to be finished by a thread asynchronously. The Callable interface has a call() technique, since it's far a everyday interface so it may go back any fee (Object, String, Integer etc.) primarily based on how it is initialized. Main function of the call() method furnished by using Callable interface is that it is able to go back value. 

Future interface - A Future represents the result of an asynchronous computation. When you put up a callable challenge the use of the submit() method of the ExecutorService, Future item is lower back.

Future affords strategies to check if the computation is whole, to await its final touch, and to retrieve the result of the computation.

Get() - get() approach retrieves the end result of the computation, blocking if essential for the computation to finish.

Question 50. What Is Atomic Variable In Java?

Answer :

In Java concurrency lessons like AtomicInteger, AtomicLong are provided with a int, long fee respectively that can be up to date atomically.

These atomic variable training in Java concurrency like AtomicInteger, AtomicLong makes use of non-blocking set of rules. These non-blocking off algorithms use low-degree atomic system commands together with compare-and-change instead of locks to make sure statistics integrity beneath concurrent access.




CFG