This section includes 7 InterviewSolutions, each offering curated multiple-choice questions to sharpen your Current Affairs knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What Is Readwritelock? |
|
Answer» It contains a pair of associated locks, one for read-only operations and another one for writing. The read LOCK may be held simultaneously by multiple reader THREADS as long as there are no WRITER threads. The WRITE lock is exclusive. It contains a pair of associated locks, one for read-only operations and another one for writing. The read lock may be held simultaneously by multiple reader threads as long as there are no writer threads. The write lock is exclusive. |
|
| 2. |
What Is Difference Between Lock Interface And Synchronized Keyword? |
|
Answer» The main differences between a LOCK and a synchronized block are:
The main differences between a Lock and a synchronized block are: |
|
| 3. |
How Countdownlatch Work In Java? |
|
Answer» Any thread, USUALLY main thread of application, which calls CountDownLatch.await() will wait until count REACHES zero or its interrupted by another Thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its not reusable once count reaches to zero you can not use CountDownLatch any more, but don't worry Java concurrency API has another concurrent UTILITY called CyclicBarrier for such requirements Java program requires 3 services namely CacheService, AlertService and ValidationService to be started and ready before application can handle any request and this is achieved by using CountDownLatch in Java. import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.logging.Level; import java.util.logging.Logger; public class CountDownLatchDemo { public static void main(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(); //another thread for AlertService initialization validationService.start(); // application should not start processing any thread until all service is up // and ready to do there job.main thread will start with count 3 // and wait until count reaches zero. Each thread once up and read will do // a count down. //count is 3 since we have 3 Threads try{ latch.await(); //main thread is waiting on CountDownLatch to finish System.out.println("All services are up, Application is starting now"); }catch(InterruptedException ie){ ie.printStackTrace(); } } } /** * Class executed by Thread using CountDownLatch synchronizer. */ class Service implements Runnable{ private final String name; private final int timeToStart; private final CountDownLatch latch; public Service(String name, int timeToStart, CountDownLatch latch){ this.name = name; this.timeToStart = timeToStart; this.latch = latch; } @Override public void run() { try { Thread.sleep(timeToStart); } catch (InterruptedException EX) { Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex); } System.out.println( name + " is Up"); latch.countDown(); //reduce count of CountDownLatch by 1 } } Output of Program: ValidationService is Up AlertService is Up CacheService is Up All services are up, Application is starting now Points To Remember
Any thread, usually main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its not reusable once count reaches to zero you can not use CountDownLatch any more, but don't worry Java concurrency API has another concurrent utility called CyclicBarrier for such requirements Java program requires 3 services namely CacheService, AlertService and ValidationService to be started and ready before application can handle any request and this is achieved by using CountDownLatch in Java. import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.logging.Level; import java.util.logging.Logger; public class CountDownLatchDemo { public static void main(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(); //another thread for AlertService initialization validationService.start(); // application should not start processing any thread until all service is up // and ready to do there job.main thread will start with count 3 // and wait until count reaches zero. Each thread once up and read will do // a count down. //count is 3 since we have 3 Threads try{ latch.await(); //main thread is waiting on CountDownLatch to finish System.out.println("All services are up, Application is starting now"); }catch(InterruptedException ie){ ie.printStackTrace(); } } } /** * Class executed by Thread using CountDownLatch synchronizer. */ class Service implements Runnable{ private final String name; private final int timeToStart; private final CountDownLatch latch; public Service(String name, int timeToStart, CountDownLatch latch){ this.name = name; this.timeToStart = timeToStart; this.latch = latch; } @Override public void run() { try { Thread.sleep(timeToStart); } catch (InterruptedException ex) { Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex); } System.out.println( name + " is Up"); latch.countDown(); //reduce count of CountDownLatch by 1 } } Output of Program: ValidationService is Up AlertService is Up CacheService is Up All services are up, Application is starting now Points To Remember |
|
| 4. |
What Is Cyclicbarrier And Countdownlatch? |
|
Answer» CyclicBarrier and CountDownLatch in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package.Both CyclicBarrier and CountDownLatch are USED to IMPLEMENT a scenario where one THREAD waits for one or more Thread to complete there job before starts PROCESSING but there is one Difference between CountDownLatch and CyclicBarrier in Java which separates them apart and that is, you can not reuse same CountDownLatch instance oncecount reaches to zero and latch is open, on the other hand CyclicBarrier can be reused by resetting Barrier, Once barrier is broken. CyclicBarrier and CountDownLatch in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package.Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete there job before starts processing but there is one Difference between CountDownLatch and CyclicBarrier in Java which separates them apart and that is, you can not reuse same CountDownLatch instance oncecount reaches to zero and latch is open, on the other hand CyclicBarrier can be reused by resetting Barrier, Once barrier is broken. |
|
| 5. |
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() { try { sendEmail(message); e.printStackTrace(); } } PRIVATE void sendEmail(String message2) { System.out.println("Sending Email" + message); } } public class TestThreadPool { public static void main(String[] args) { //Let us START the Worker Threads static final Integer NTHREDS=5; ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); for (int i = 0; i < 6; i++) { Runnable worker = new EmailSender("Hi Email from java"); executor.execute(worker); } // This will make the executor accept no new threads // and finish all existing threads in the queue executor.shutdoOWN(); // WAIT until all threads are finish while (!executor.isTerminated()) { } } } public class EmailSender implements Runnable { String message; EmailSender (String message) { this.message = message; } public void run() { try { sendEmail(message); } catch (Exception e) { e.printStackTrace(); } } private void sendEmail(String message2) { System.out.println("Sending Email" + message); } } public class TestThreadPool { public static void main(String[] args) { //Let us start the Worker Threads static final Integer NTHREDS=5; ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); for (int i = 0; i < 6; i++) { Runnable worker = new EmailSender("Hi Email from java"); executor.execute(worker); } // This will make the executor accept no new threads // and finish all existing threads in the queue executor.shutdoOWN(); // Wait until all threads are finish while (!executor.isTerminated()) { } } } |
|
| 6. |
How To Get Return Value Of A Callable Thread In Java Executor Framework? |
|
Answer» Using FUTURE, we can get the return value of callable thread. EXECUTORSERVICE exService = Executors.newCachedThreadPool(); Future<Integer> future=exService.submit(new CallableThread()); INT val=future.get(); Using Future, we can get the return value of callable thread. ExecutorService exService = Executors.newCachedThreadPool(); Future<Integer> future=exService.submit(new CallableThread()); int val=future.get(); |
|
| 7. |
What Are The Different Policy In Executor Framework? |
|
Answer» There are DIFFERENT policy within ThreadPoolExecutor in JAVA. ThreadPoolExecutor.AbortPolicy : AbortPolicy is a handler for rejected task. It handles those task which has been rejected. ThreadPoolExecutor.CallerRunsPolicy : This also handles the rejected task and RUNS the rejected task DIRECTLY. ThreadPoolExecutor.DiscardOldestPolicy : This handles those rejected task that is OLDEST and unhandled. It discards those that oldest task. ThreadPoolExecutor.DiscardPolicy : This is the handler for those rejected task that are rejected silently. There are different policy within ThreadPoolExecutor in java. ThreadPoolExecutor.AbortPolicy : AbortPolicy is a handler for rejected task. It handles those task which has been rejected. ThreadPoolExecutor.CallerRunsPolicy : This also handles the rejected task and runs the rejected task directly. ThreadPoolExecutor.DiscardOldestPolicy : This handles those rejected task that is oldest and unhandled. It discards those that oldest task. ThreadPoolExecutor.DiscardPolicy : This is the handler for those rejected task that are rejected silently. |
|
| 8. |
What Is The Role Of Executors.unconfigurable Executorservice In Executor Framework? |
|
Answer» unconfigurable ExecutorService RETURNS an OBJECT that delegates all methods of ExecutorService to the given executor so that any other METHOD cannot ACCESSED by cast. unconfigurable ExecutorService returns an object that delegates all methods of ExecutorService to the given executor so that any other method cannot accessed by cast. |
|
| 9. |
What Is The Role Of Executors.privileged Threadfactory() In Executor Framework? |
|
Answer» privileged ThreadFactory returns a thread FACTORY that CREATES thread with same PERMISSION as main thread. privileged ThreadFactory returns a thread factory that creates thread with same permission as main thread. |
|
| 10. |
How To Terminate A Thread In Executor Framework In Java? |
|
Answer» ExecutorService provides a method awaitTermination(LONG timeout, TIMEUNIT UNIT) that takes time and unit of time as an arguments. After that time thread pool is TERMINATED. Suppose we need to terminate a task just now, then we can do as ExecutorService.awaitTermination(0, TimeUnit.SECONDS) ExecutorService provides a method awaitTermination(long timeout, TimeUnit unit) that takes time and unit of time as an arguments. After that time thread pool is terminated. Suppose we need to terminate a task just now, then we can do as ExecutorService.awaitTermination(0, TimeUnit.SECONDS) |
|
| 11. |
What Is Difference Between Shutdownnow() And Shutdown() In Executor Framework In Java? |
|
Answer» shutdown() and shutdownNow() methods BELONGS to ExecutorService. shutdown() method tries to stop the threads and do not ACCEPT new task to execute but it completes the execution which has been SUBMITTED. shutdownNow() methods also tries to stop the running threads and will not execute any task which has been submitted but not STARTED. shutdown() and shutdownNow() methods belongs to ExecutorService. shutdown() method tries to stop the threads and do not accept new task to execute but it completes the execution which has been submitted. shutdownNow() methods also tries to stop the running threads and will not execute any task which has been submitted but not started. |
|
| 12. |
What Is The Role Of Futuretask And Future In Java? |
|
Answer» FutureTask is a cancellable asynchronous COMPUTATION in java. It can cancel the TASK which is RUNNING. Once the FutureTask will be cancelled, it cannot be restarted. Future is RESULT of asynchronous computation. Future checks if task is complete and if completed it gets the OUTPUT. FutureTask is a cancellable asynchronous computation in java. It can cancel the task which is running. Once the FutureTask will be cancelled, it cannot be restarted. Future is result of asynchronous computation. Future checks if task is complete and if completed it gets the output. |
|
| 13. |
What Is Executors In Java Executor Framework? |
|
Answer» Executors is a factory that PROVIDES the methods to return ExecutorService, ScheduledExecutorService, ThreadFactory. Find some method details. newFixedThreadPool(): It RETURNS the pool with fixed number of size. We need to pass the number of threads to this method. If concurrently task are submitted more than the pool size, then rest of task need to wait in QUEUE. It returns ExecutorService. newScheduledThreadPool: This also creates a fixed size pool but it can schedule the thread to run after some defined delay. It is useful to schedule the task. It returns ScheduledExecutorService. newCachedThreadPool(): There is no fixed size of this pool. Thread will be created at run time and if there is no task it will ALIVE for 60 second and then die. For short lived threads this pool WORKS good. It returns ExecutorService. Executors is a factory that provides the methods to return ExecutorService, ScheduledExecutorService, ThreadFactory. Find some method details. newFixedThreadPool(): It returns the pool with fixed number of size. We need to pass the number of threads to this method. If concurrently task are submitted more than the pool size, then rest of task need to wait in queue. It returns ExecutorService. newScheduledThreadPool: This also creates a fixed size pool but it can schedule the thread to run after some defined delay. It is useful to schedule the task. It returns ScheduledExecutorService. newCachedThreadPool(): There is no fixed size of this pool. Thread will be created at run time and if there is no task it will alive for 60 second and then die. For short lived threads this pool works good. It returns ExecutorService. |
|
| 14. |
What Is The Role Of Executorservice In Java? |
|
Answer» EXECUTORSERVICE provides different methods to START and TERMINATE thread. There are two methods execute() and submit() in ExecutorService. Execute() method is used for threads which is RUNNABLE and submit() method is used for Callable threads. ExecutorService provides different methods to start and terminate thread. There are two methods execute() and submit() in ExecutorService. Execute() method is used for threads which is Runnable and submit() method is used for Callable threads. |
|
| 15. |
What Do You Understand By Executor Framework In Java? |
|
Answer» EXECUTOR FRAMEWORK in java has been introduced in JDK 5. Executor Framework handles CREATION of thread, CREATING the thread pool and checking health while running and also terminates if needed. Executor Framework in java has been introduced in JDK 5. Executor Framework handles creation of thread, creating the thread pool and checking health while running and also terminates if needed. |
|