InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
Is it possible that each thread can have its stack in multithreaded programming? |
|
Answer» Of course, it is possible. In MULTITHREADED programming, each THREAD maintains its own separate stack area in memory because of which every thread is independent of each other RATHER than DEPENDENT. |
|
| 2. |
Is it possible to call the run() method directly to start a new thread? |
|
Answer» No, it's not possible at all. You need to CALL the start METHOD to create a new THREAD OTHERWISE run method won't create a new thread. Instead, it will execute in the CURRENT thread. |
|
| 3. |
What is the lock interface? Why is it better to use a lock interface rather than a synchronized block.? |
|
Answer» Lock interface was introduced in Java 1.5 and is generally used as a synchronization mechanism to provide important OPERATIONS for BLOCKING.
|
|
| 4. |
What will happen if we don’t override the thread class run() method? |
|
Answer» Nothing will happen as such if we don’t OVERRIDE the run() method. The compiler will not show any error. It will EXECUTE the run() method of thread CLASS and we will just don’t get any output because the run() method is with an EMPTY implementation. Output: Started Main. Ended Main. |
|
| 5. |
What is the ExecutorService interface? |
|
Answer» ExecutorService interface is basically a sub-interface of Executor interface with some additional methods or features that help in managing and controlling the execution of threads. It enables us to execute tasks asynchronously on threads. Example: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class TestThread { public static void MAIN(final String[] arguments) throws InterruptedException { ExecutorService e = Executors.newSingleThreadExecutor(); try { e.submit(new Thread()); System.out.println("SHUTDOWN executor"); e.shutdown(); e.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { System.err.println("tasks interrupted"); } finally { if (!e.isTerminated()) { System.err.println("cancel non-finished tasks"); } e.shutdownNow(); System.out.println("shutdown finished"); } } static class Task implements RUNNABLE { public void run() { try { Long DURATION = (long) (Math.random() * 20); System.out.println("Running Task!"); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException ex) { ex.printStackTrace(); } } } }Output: Shutdown executor shutdown finished |
|
| 6. |
Explain Thread Group. Why should we not use it? |
|
Answer» ThreadGroup is a class that is used to create multiple groups of THREADS in a single object. This group of threads is present in the form of three structures in which every THREAD group has a parent except the initial thread. Thread groups can contain other thread groups also. A thread is only allowed to have ACCESS to information about its own thread group, not other thread groups. |
|
| 7. |
What is semaphore? |
|
Answer» Semaphore is REGARDED as a thread synchronization construct that is usually required to CONTROL and manage the access to the SHARED resource USING counters. It simply sets the limit of the thread. The semaphore class is defined within the package java.util.concurrent and can be used to send signals between threads to avoid missed signals or to guard critical SECTIONS. It can also be used to implement resource pools or bounded collection. |
|
| 8. |
What do you mean by the ThreadLocal variable in Java? |
|
Answer» ThreadLocal variables are special KINDS of variables created and provided by the Java ThreadLocal class. These variables are only allowed to be read and written by the same thread. Two threads cannot be able to see each other’s ThreadLocal variable, so even if they will execute the same code, then there won't be any race condition and the code will be thread-safe. Output: 10 33 10 33 |
|
| 9. |
Explain thread priority. |
|
Answer» THREAD priority SIMPLY means that THREADS with the highest priority will get a chance for execution prior to low-priority threads. One can specify the priority but it's not necessary that the highest priority thread will get executed before the lower-priority thread. Thread scheduler ASSIGNS processor to thread on the BASIS of thread priority. The range of priority changes between 1-10 from lowest priority to highest priority. |
|
| 10. |
What is ConcurrentHashMap and Hashtable? In java, why is ConcurrentHashMap considered faster than Hashtable? |
|
Answer» ConcurrentHashMap: It was introduced in Java 1.5 to store data using multiple buckets. As the name SUGGESTS, it allows CONCURRENT READ and writes operations to the map. It only locks a certain portion of the map while doing iteration to provide thread safety so that other readers can still have access to the map WITHOUT waiting for iteration to complete. |
|
| 11. |
What is busy spinning? |
|
Answer» Busy Spinning, also known as Busy-waiting, is a technique in which one thread WAITS for some condition to happen, without calling wait or sleep methods and releasing the CPU. In this condition, one can pause a thread by MAKING it run an empty loop for a CERTAIN time period, and it does not even give CPY CONTROL. Therefore, it is used to preserve CPU CACHES and avoid the cost of rebuilding cache. |
|
| 12. |
What is a shutdown hook? |
|
Answer» A shutdown hook is simply a thread that is invoked implicitly before JVM shuts down. It is one of the most important FEATURES of JVM because it provides the capacity to do RESOURCE cleanup or SAVE APPLICATION state JVM shuts down. By calling the halt(INT) method of the Runtime class, the shutdown hook can be stopped. Using the following method, one can add a shutdown hook. public void addShutdownHook(Thread hook){} Runtime r=Runtime.getRuntime(); r.addShutdownHook(new MyThread()); |
|
| 13. |
What is Thread Scheduler and Time Slicing? |
|
Answer» Thread Scheduler: It is a component of JVM that is used to decide which thread will execute next if multiple threads are waiting to get the chance of execution. By looking at the PRIORITY assigned to each thread that is READY, the thread scheduler selects the next run to execute. To schedule the threads, it mainly uses two mechanisms: Preemptive Scheduling and Time slicing scheduling. |
|
| 14. |
What do you mean by inter-thread communication? |
|
Answer» Inter-thread communication, as the name suggests, is a process or mechanism using which multiple threads can communicate with each other. It is especially USED to AVOID thread polling in JAVA and can be obtained using wait(), notify(), and NOTIFYALL() methods. |
|
| 15. |
What is CyclicBarrier and CountDownLatch? |
|
Answer» CyclicBarrier and CountDownLatch, both are required for managing multithreaded programming. But there is some difference between them as given below: CyclicBarrier: It is a tool to synchronize threads processing using some algorithm. It enables a set of threads to wait for each other till they reach a common EXECUTION point or common barrier points, and then let them further continue execution. One can reuse the same CyclicBarrier even if the barrier is BROKEN by SETTING it. CountDownLatch: It is a tool that enables main threads to wait until mandatory operations are performed and completed by other threads. In simple WORDS, it MAKES sure that a thread waits until the execution in another thread completes before it starts its execution. One cannot reuse the same CountDownLatch once the count reaches 0. |
|
| 16. |
Explain context switching. |
|
Answer» Context switching is BASICALLY an important feature of multithreading. It is referred to as switching of CPU from one thread or process to another one. It allows multiple processes to share the same CPU. In context switching, the STATE of thread or process is stored so that the execution of the thread can be RESUMED later if REQUIRED. |
|
| 17. |
Can you start a thread twice? |
|
Answer» No, it's not at all possible to restart a thread once a thread gets started and completes its execution. Thread only runs once and if you try to run it for a SECOND time, then it will throw a runtime exception i.e., java.lang.IllegalThreadStateException. Output: thread is executing now........ Exception in thread "main" java.lang.IllegalThreadStateException |
|
| 18. |
What is BlockingQueue? |
|
Answer» BlockingQueue basically represents a queue that is thread-safe. Producer thread inserts resource/element into the queue using put() method unless it gets full and consumer thread takes resources from the queue using take() method until it gets empty. But if a thread tries to dequeue from an empty queue, then a PARTICULAR thread will be blocked until some other thread inserts an item into the queue, or if a thread tries to insert an item into a queue that is already full, then a particular thread will be blocked until some threads take away an item from the queue. Example: package org.arpit.java2blog; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; PUBLIC class BlockingQueuePCExample { public static void main(String[] args) { BlockingQueue<String> queue=NEW ArrayBlockingQueue<>(5); Producer producer=new Producer(queue); Consumer consumer=new Consumer(queue); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); } static class Producer implements Runnable { BlockingQueue<String> queue=null; public Producer(BlockingQueue queue) { super(); this.queue = queue; } @OVERRIDE public void run() { try { System.out.println("Producing element 1"); queue.put("Element 1"); Thread.sleep(1000); System.out.println("Producing element 2"); queue.put("Element 2"); Thread.sleep(1000); System.out.println("Producing element 3"); queue.put("Element 3"); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Consumer implements Runnable { BlockingQueue<String> queue=null; public Consumer(BlockingQueue queue) { super(); this.queue = queue; } @Override public void run() { while(true) { try { System.out.println("Consumed "+queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } } } }Output: Producing element 1 Consumed Element 1 Producing element 2 Consumed Element 2 Producing element 3 Consumed Element 3 |
|
| 19. |
What is Livelock? What happens when it occurs? |
|
Answer» Similar to deadlock, livelock is ALSO another CONCURRENCY problem. In this case, the state of THREADS changes between ONE another without making any progress. Threads are not blocked but their execution is stopped due to the unavailability of RESOURCES. |
|
| 20. |
What is thread starvation? |
|
Answer» Thread starvation is BASICALLY a situation or CONDITION where a thread won’t be ABLE to have regular access to shared resources and therefore is unable to proceed or make PROGRESS. This is because other threads have high PRIORITY and occupy the resources for too long. This usually happens with low-priority threads that do not get CPU for its execution to carry on. |
|
| 21. |
What is synchronized method and synchronized block? Which one should be preferred? |
|
Answer» Synchronized Method: In this method, the thread acquires a lock on the object when they enter the synchronized method and releases the lock either normally or by THROWING an exception when they leave the method. No other thread can use the whole method UNLESS and until the current thread finishes its execution and release the lock. It can be used when one WANTS to lock on the entire functionality of a particular method. |
|
| 22. |
What is the synchronization process? Why use it? |
|
Answer» Synchronization is basically a process in java that enables a SIMPLE strategy for avoiding thread interference and memory consistency errors. This process makes sure that resource will be only used one thread at a time when one thread tries to access a SHARED resource. It can be achieved in three different WAYS as given below:
Syntax: synchronized (object) { //STATEMENT to be synchronized } |
|