YouTube Icon

Interview Questions.

Top 100+ Executors Java Interview Questions And Answers - May 30, 2020

fluid

Top 100+ Executors Java Interview Questions And Answers

Question 1. What Do You Understand By Executor Framework In Java?

Answer :

Executor Framework in java has been added in JDK 5. Executor Framework handles creation of thread, creating the thread pool and checking health while going for walks and also terminates if wished.

Question 2. What Is The Role Of Executorservice In Java?

Answer :

ExecutorService affords distinct methods to start and terminate thread. There are  techniques execute() and publish() in ExecutorService. Execute() method is used for threads that is Runnable and publish() technique is used for Callable threads.

Adv Java Interview Questions
Question 3. What Is Executors In Java Executor Framework?

Answer :

Executors is a factory that offers the strategies to return ExecutorService, ScheduledExecutorService, ThreadFactory. Find some approach information. 

NewFixedThreadPool(): It returns the pool with constant quantity of length. We want to bypass the number of threads to this technique. If concurrently venture are submitted greater than the pool size, then rest of task need to wait in queue. It returns ExecutorService. 

NewScheduledThreadPool: This additionally creates a fixed length pool but it can schedule the thread to run after some described delay. It is beneficial to schedule the task. It returns ScheduledExecutorService. 

NewCachedThreadPool(): There isn't any constant length of this pool. Thread can be created at run time and if there is no undertaking it'll alive for 60 2d after which die. For brief lived threads this pool works exact. It returns ExecutorService.

Question 4. What Is The Role Of Futuretask And Future In Java?

Answer :

FutureTask is a cancellable asynchronous computation in java. It can cancel the undertaking that is running. Once the FutureTask may be cancelled, it can't be restarted. Future is end result of asynchronous computation. Future tests if challenge is complete and if completed it receives the output.

Adv Java Tutorial
Question 5. What Is Difference Between Shutdownnow() And Shutdown() In Executor Framework In Java?

Answer :

shutdown() and shutdownNow() methods belongs to ExecutorService. Shutdown() approach attempts to stop the threads and do no longer be given new project to execute but it completes the execution which has been submitted. ShutdownNow() strategies also attempts to forestall the going for walks threads and will not execute any challenge which has been submitted however now not started.

J2EE Interview Questions
Question 6. How To Terminate A Thread In Executor Framework In Java?

Answer :

ExecutorService gives a way awaitTermination(long timeout, TimeUnit unit) that takes time and unit of time as an arguments. After that time thread pool is terminated. Suppose we want to terminate a mission just now, then we will do as

ExecutorService.AwaitTermination(0, TimeUnit.SECONDS)

Question 7. What Is The Role Of Executors.Privileged Threadfactory() In Executor Framework?

Answer :

privileged ThreadFactory returns a thread manufacturing facility that creates thread with identical permission as principal thread.

J2EE Tutorial Core Java Interview Questions
Question 8. What Is The Role Of Executors.Unconfigurable Executorservice In Executor Framework?

Answer :

unconfigurable ExecutorService returns an item that delegates all strategies of ExecutorService to the given executor in order that some other approach can't accessed via solid.

Question nine. What Are The Different Policy In Executor Framework?

Answer :

There are exceptional policy within ThreadPoolExecutor in java. 

ThreadPoolExecutor.AbortPolicy : AbortPolicy is a handler for rejected venture. It handles the ones task which has been rejected. 

ThreadPoolExecutor.CallerRunsPolicy : This also handles the rejected venture and runs the rejected project at once. 

ThreadPoolExecutor.DiscardOldestPolicy : This handles those rejected task this is oldest and unhandled. It discards those that oldest project. 

ThreadPoolExecutor.DiscardPolicy : This is the handler for those rejected assignment that are rejected silently.

JSP Interview Questions
Question 10. How To Get Return Value Of A Callable Thread In Java Executor Framework?

Answer :

Using Future, we are able to get the return price of callable thread.

ExecutorService exService = Executors.NewCachedThreadPool();

Future<Integer> destiny=exService.Submit(new CallableThread());

int val=destiny.Get();

Core Java Tutorial
Question eleven. Write A Program Using Executor In Java Or Example Of Thread Pool In Java?

Answer :

public class EmailSender  implements Runnable 

        String message;

        EmailSender  (String message) 

                this.Message = message;

        

        public void run() 

                attempt 

                        sendEmail(message);

                 seize (Exception e) 

                        e.PrintStackTrace();

                

        

       private void sendEmail(String message2)  

          System.Out.Println("Sending Email" + message);

    

public class TestThreadPool   

     public static void major(String[] args)   

 //Let us start the Worker Threads

       static final Integer NTHREDS=five;

                ExecutorService executor = Executors.NewFixedThreadPool(NTHREDS);

for (int i = 0; i < 6; i++) 

     Runnable employee = new EmailSender("Hi Email from java");

                        executor.Execute(employee);

                

                // This will make the executor receive no new threads

                // and finish all present threads inside the queue

                executor.ShutdoOWN();

 // Wait till all threads are finish

                at the same time as (!Executor.IsTerminated()) 

 

Java-Springs Interview Questions
Question 12. What Is Semaphore?

Answer :

Semaphore may be used to create a fixed of Children Threads even if the scale of the Threads to be created isn't recognised fore hand. This is due to the fact a Semaphore can wait until some of releases have been made however that quantity is not required to initialize the Semaphore. Semaphores can be used in different situations such as Synchronizing between unique threads which include Publisher, Subscriber state of affairs. Semaphore is a way used to control get right of entry to to common resource for competeing more than one tactics. Semaphore keeps a counter which maintains music of the wide variety of assets to be had. When a procedure requests access to aid, semaphore assessments the variable remember and if it's far less than total be counted then presents access and finally reduces the available be counted.

Semaphore is only a gatekeeper guarding the resources. If available grants get entry to and otherwise asks the methods to wait. When the resource count is bigoted then that is known as counting semaphore. If aid count number is handiest one and the state value is restricted to on/off, then it's miles referred to as binary semaphore.

Adv Java Interview Questions
Question 13. What Is Cyclicbarrier And Countdownlatch?

Answer :

CyclicBarrier and CountDownLatch in Java is a synchronizer added in JDK five on java.Util.Concurrent package deal.Both CyclicBarrier and CountDownLatch are used to enforce a state of affairs in which one Thread waits for one or greater Thread to finish there process earlier than starts processing but there may be one Difference between CountDownLatch and CyclicBarrier in Java which separates them apart and this is, you can't reuse equal CountDownLatch example oncecount reaches to 0 and latch is open, however CyclicBarrier can be reused with the aid of resetting Barrier, Once barrier is broken.

JSP Tutorial
Question 14. How Countdownlatch Work In Java?

Answer :

Any thread, commonly main thread of utility,  which calls CountDownLatch.Wait for() will wait until remember reaches 0 or its interrupted by way of every other Thread. All other thread are required to do rely down with the aid of calling CountDownLatch.CountDown() once they may be finished or equipped to the job. As quickly as matter reaches 0, Thread looking ahead to starts going for walks. One of the disadvantage of CountDownLatch is that its now not reusable as soon as be counted reaches to 0

you can not use CountDownLatch any greater, however don't worry Java concurrency API has every other concurrent software known as CyclicBarrier for such requirements Java software requires 3 offerings particularly CacheService, AlertService  and ValidationService to be started out and geared up before software can cope with any request and that is achieved by way of 

the use of CountDownLatch in Java.

Import java.Util.Date;

import java.Util.Concurrent.CountDownLatch;

import java.Util.Logging.Level;

import java.Util.Logging.Logger;

public elegance CountDownLatchDemo 

 public static void major(String args[]) 

       final CountDownLatch latch = new CountDownLatch(3);

       Thread cacheService = new Thread(new Service("CacheService", 1000, latch));

       Thread alertService = new Thread(new Service("AlertService", 1000, latch));

       Thread validationService = new Thread(new Service("ValidationService", 1000, latch));

       cacheService.Start(); //separate thread will initialize CacheService

       alertService.Start(); //every other thread for AlertService initialization

       validationService.Start();

       // utility should now not start processing any thread until all service is up

       // and equipped to do there task.Principal thread will start with count number three

       // and wait until be counted reaches 0. Each thread once up and read will do

       // a rely down.

       //matter is three because we've got three Threads

      attempt

            latch.Look ahead to();  //important thread is ready on CountDownLatch to complete

            System.Out.Println("All services are up, Application is beginning now");

       seize(InterruptedException ie)

           ie.PrintStackTrace();

       

/**

 * Class carried out by means of Thread the usage of CountDownLatch synchronizer.

 */

class Service implements Runnable

    private very last String call;

    private final int timeToStart;

    private very last CountDownLatch latch;

    public Service(String name, int timeToStart, CountDownLatch latch)

        this.Call = call;

        this.TimeToStart = timeToStart;

        this.Latch = latch;

    

   @Override

    public void run() 

        strive 

            Thread.Sleep(timeToStart);

         seize (InterruptedException ex) 

            Logger.GetLogger(Service.Magnificence.GetName()).Log(Level.SEVERE, null, ex);

        

        System.Out.Println( name + " is Up");

        latch.CountDown(); //lessen remember of CountDownLatch by means of 1

    

 

Output of Program:

ValidationService is Up

AlertService is Up

CacheService is Up

All services are up, Application is starting now

Points To Remember

You cannot reuse CountDownLatch once remember is reaches to zero, that is the main distinction between CountDownLatch and CyclicBarrier.
Main Thread wait on Latch by means of calling CountDownLatch.Look ahead to() approach even as other thread calls CountDownLatch.CountDown() to tell that they've finished.
Question 15. What Is Difference Between Lock Interface And Synchronized Keyword?

Answer :

The principal differences between a Lock and a synchronized block are:

Having a timeout trying to get access to a synchronized block is not possible. Using Lock.TryLock(long timeout, TimeUnit timeUnit), it's far feasible.
The synchronized block should be absolutely contained within a single technique. A Lock will have it is calls to fasten() and release() in separate techniques.
JMS(Java Message Service) Interview Questions
Question sixteen. What Is Condition?

Answer :

Condition gadgets are just like Object wait-notify version with extra feature to create specific units of wait. A Condition item is constantly created by means of Lock object. Some of the vital methods are look ahead to() that is much like wait() and signal(), signalAll() this is much like notify() and notifyAll() techniques.

Java-Springs Tutorial
Question 17. What Is Readwritelock?

Answer :

It consists of a couple of related locks, one for read-best operations and every other one for writing. The study lock may be held simultaneously through multiple reader threads as long as there aren't any writer threads. The write lock is one of a kind.

Java applet Interview Questions




CFG