How to use Threads in Java

Java 11 Certification Practice Questions (For the complete list, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)

Section: Concurrency

Objective: Create worker threads using Runnable and Callable, and manage concurrency using an ExecutorService and java.util.concurrent API

Q1. Which statements are true about the ExecutorService? (Choose all that apply.)

A. ExecutorService will be automatically destroyed when there is no task to process
B. As ExecutorService is AutoCloseable, it will be automatically closed if used with a try-with-resources statement
C. shutdown() called on ExecutorService does not actually stop any tasks that have already been submitted to the thread executor
D. Once you have finished using the ExecutorService, you need to shut it down explicitly
E. If a new task is submitted to the thread executor while it is shutting down, it will be ignored, but there not be any exception thrown
F. All of these
G. None of these

Answers

Q1. Choices C and D are correct. The shutdown process for a thread executor involves first rejecting any new tasks submitted to the thread executor while continuing to execute any previously submitted tasks. Once you have finished using a thread executor, it is important to call the shutdown() so that memory leaks can be prevented.
Choice A is incorrect because ExecutorService will not be automatically shut down, it has to be done explicitly by calling the shutdown() method. ExecutorService interface does not extend the AutoCloseable interface, so you cannot use a try-with-resources statement. Thus choice B is also incorrect. If a new task is submitted to the thread executor while it is shutting down, a RejectedExecutionException will be thrown.So choice E is also incorrect.

Leave a Reply

Your email address will not be published. Required fields are marked *