📝 Java Threads in operating system (33 MCQs)
Java Thread Abstraction and JVM Execution
Java threads provide concurrent execution within a Java application through facilities defined by the Java platform. A Java program can create threads using the Thread class, implement Runnable or Callable tasks, or use higher-level concurrency utilities. The Java Virtual Machine coordinates application-level thread execution with the underlying operating system, where platform threads are generally supported by native operating system threads.
Why Java Applications Use Concurrent Execution
Java applications often perform independent activities such as processing requests, updating interfaces, accessing databases, and performing background calculations. Using a single execution path can cause delays when one activity blocks. Threading separates these activities and allows them to progress concurrently while sharing Java objects and heap memory, requiring proper synchronisation to protect shared mutable state.
Thread Creation, Runnable Tasks, and Synchronised Methods
A Java application creates a task by implementing Runnable or Callable and submits it to an execution facility. A Thread can execute a Runnable task, while ExecutorService manages task submission and worker execution. Java synchronisation mechanisms, including synchronized methods and blocks, coordinate access to shared objects. The JVM and operating system cooperate to schedule platform threads.
Running Two Java Worker Threads
Suppose a Java application creates two Runnable tasks to process separate halves of an array containing 20,000 elements. Each task calculates a partial sum and stores its result in a separate field. The main thread waits for both workers to complete, then combines their values. A thread pool could manage the workers without creating new threads for every task.
Thread Safety, JVM Overhead, and Execution Behaviour
Java threading supports responsive interfaces, server request handling, and parallel computations. Higher-level utilities simplify task management and synchronisation. However, shared mutable objects can produce race conditions, and excessive threads consume memory and scheduling resources. Java platform-thread behaviour depends on the JVM and operating system, while virtual threads use a different lightweight scheduling approach supported by modern Java versions.
Misconceptions About Java Threads and JVM Scheduling
'Every Java task requires creating a new Thread object' is incorrect because executors reuse worker threads. 'The synchronized keyword makes an entire application thread-safe' is incorrect because it protects only code using the relevant monitor correctly. 'Java threads are always scheduled independently by the JVM' is incorrect for platform threads, which generally correspond to native operating system threads.
Exam Focus: Java Thread APIs and Synchronisation
Compare Thread, Runnable, Callable, and ExecutorService by their responsibilities. Trace thread creation, start(), join(), and synchronized execution. Distinguish calling run() directly from invoking start(), which initiates separate thread execution. Questions may examine race conditions, monitor locks, task results, thread pools, and the relationship between the JVM and operating system scheduling.
Key Terms of Java Threading
- Thread - Java execution abstraction.
- Runnable - Interface defining executable tasks.
- Callable - Task interface capable of returning results.
- ExecutorService - Framework managing submitted tasks.
- Monitor - Object-based synchronisation mechanism.
- JVM - Runtime executing Java programs.
📝 All Java Threads in operating system MCQs
Q1. A Java application calls worker.start(), and the main thread continues before the worker finishes. What does start() actually do?
📖 Explanation: Calling start() requests a new thread of execution, allowing its run() method to proceed independently. It does not wait for completion, so use join() or another synchronization mechanism when later work depends on the worker's result.
Q2. A programmer invokes worker.run() directly instead of worker.start(). What happens?
📖 Explanation: Calling run() directly does not start a new thread. It executes on the calling thread like an ordinary method, so the caller performs the work synchronously. Calling start() requests separate thread execution.
Q3. A main thread must use a worker's computed result only after the worker finishes. Which Thread operation provides a completion point?
📖 Explanation: The join() method blocks the calling thread until the target terminates, establishing a clear completion point. The caller can then use the worker's result, provided its storage remains valid and the result is properly designed.
Q4. A Java Thread object has already been started and has terminated. The program calls start() on the same object again. What should it expect?
📖 Explanation: A Thread object can be started at most once. Termination does not reset it for reuse; another execution requires a new Thread object or a reusable task submitted to an executor.
Q5. A thread calls Thread.sleep(500) while holding an object's synchronized monitor. Another thread tries to enter a synchronized block using that same monitor. What happens?
📖 Explanation: Thread.sleep() pauses the current thread but does not release monitors it owns. A thread needing the same monitor remains blocked until the sleeping thread resumes and releases the monitor by leaving the synchronized region.
Q6. A Java thread owns object M's monitor and calls M.wait(). What happens before it waits for notification?
📖 Explanation: Object.wait() releases the monitor associated with that object and suspends the thread. Before returning, the thread must reacquire that monitor; locks on unrelated objects are not automatically released by the wait operation.
Q7. A consumer waits for a queue item using wait(), then proceeds after one notification without checking the queue again. What is the best correction?
📖 Explanation: A wake-up does not prove the queue condition is true; it may be spurious or another consumer may take the item first. Check the predicate in a loop while holding the same monitor, waiting while it remains false.
Q8. A Java worker periodically checks a shared volatile boolean stopRequested. What does volatile contribute to this design?
📖 Explanation: A volatile flag makes updates visible under Java's memory rules, but it does not forcibly terminate a thread or make unrelated compound operations atomic. The worker must check the flag and perform its own safe shutdown.
Q9. A worker is blocked in sleep() and another thread interrupts it. The worker catches InterruptedException and continues a long loop without restoring status or exiting. What is the main concern?
📖 Explanation: Methods such as sleep() clear the interrupted status when throwing InterruptedException. Ignoring the exception can discard a cancellation request, so the worker should normally exit, rethrow, or restore the interrupt status for higher-level handling.
Q10. A Java thread receives interrupt(), but it is performing a CPU calculation that never checks interruption. What is the likely result?
📖 Explanation: Thread interruption sets a request and affects interruptible operations, but it does not generally force arbitrary computation to stop. CPU-bound code should check interruption status periodically and respond with an orderly cleanup and exit.
Q11. Two Java threads update a shared bank balance inside synchronized methods on the same object. What does the object's intrinsic monitor provide?
📖 Explanation: Synchronized instance methods on the same object use its intrinsic monitor. The lock provides mutual exclusion and a happens-before relationship for properly synchronized accesses, but it does not protect code that accesses the balance outside that protocol.
Q12. A writer updates a shared field inside synchronized code, while a reader accesses it without synchronization or volatile semantics. What is the central concern?
📖 Explanation: The flawed design assumes the writer's synchronization protects unsynchronized readers. It does not: the reader needs a matching synchronization or suitable volatile/atomic protocol to establish visibility and ordering for the shared field.
Q13. A synchronized method on an object calls another synchronized method on that same object. Why does this not inherently deadlock the calling thread?
📖 Explanation: Java intrinsic monitors are reentrant, so a thread that already owns an object's monitor can acquire it again when entering another synchronized method on that object. The monitor remains owned until the nested and outer regions exit.
Q14. Thread A acquires lock X and then requests Y; Thread B acquires Y and then requests X. Neither proceeds. Which design change prevents this lock-order cycle?
📖 Explanation: The opposite acquisition orders allow each thread to hold one lock while waiting for the other. A consistent global lock order prevents this circular-wait pattern, removing the deadlock cycle rather than merely changing scheduling priority.
Q15. A Java statistics service increments one shared AtomicInteger from many threads. Which property distinguishes incrementAndGet() from an ordinary unsynchronized counter++?
📖 Explanation: AtomicInteger provides atomic read-modify-write operations such as incrementAndGet(). Concurrent increments are not lost through the ordinary interleaving of separate reads and writes, but the guarantee does not extend to unrelated variables or larger invariants.
Q16. A statistics collector receives increments from many Java threads. Which advantage can LongAdder provide over a single highly contended atomic counter?
📖 Explanation: LongAdder distributes updates across internal cells, often improving throughput under heavy contention. Its sum combines those cells and may not represent one linearizable instant during concurrent updates, so strict atomic snapshots may require another design.
Q17. A Java server stores a request identifier in a ThreadLocal variable. What is the main benefit?
📖 Explanation: ThreadLocal gives each thread its own value for the variable, which is useful for per-thread request context. It does not make referenced shared objects thread-safe, and pooled workers may need to remove stale values after tasks.
Q18. A pooled worker stores request data in ThreadLocal and then processes another user's request. What cleanup is important when the first task finishes?
📖 Explanation: Thread pools reuse worker threads, so a ThreadLocal value can remain associated with a worker after its task ends. Removing task-specific data prevents stale request context from leaking into later tasks handled by that same thread.
Q19. A Java application marks a background thread as daemon before starting it. What does daemon status mean for JVM shutdown?
📖 Explanation: Daemon threads are background threads that do not by themselves prevent JVM shutdown once all started non-daemon threads have terminated. Important work requiring guaranteed completion should use an orderly lifecycle rather than relying only on daemon status.
Q20. A fixed ExecutorService has four workers. Each worker runs a task that blocks waiting for a follow-up task queued in the same pool. What can happen?
📖 Explanation: If all fixed-pool workers block while waiting for follow-up tasks queued in that same pool, no worker remains to run those tasks. This can cause thread-starvation deadlock; avoid blocking dependencies on an exhausted executor.
Q21. A Java program submits a Callable to an ExecutorService and needs its eventual result. Which object normally represents the submitted task's completion and result?
📖 Explanation: Submitting a Callable through an ExecutorService normally returns a Future. The caller can inspect completion, wait for the result, or request cancellation where supported, separating task submission from result collection.
Q22. During an external-service outage, a cached Java thread pool records time and active worker count: (0 s, 4) ; (1 s, 8) ; (2 s, 12) ; (3 s, 16) ; (4 s, 20). Which concern is most directly indicated?
📖 Explanation: The active worker count rises from four to twenty while the external service is unavailable. This is consistent with a cached pool adding workers as existing ones block, potentially increasing memory and scheduling pressure.
Q23. A CompletableFuture pipeline includes slow blocking network calls and CPU-heavy transformations. Which executor design is generally preferable?
📖 Explanation: Blocking I/O can occupy workers while waiting, whereas CPU-heavy stages need processor time. Separate or carefully configured executors reduce the risk that blocked operations exhaust workers needed for computation and delay unrelated pipeline stages.
Q24. A Java thread calls Thread.sleep(1000). Which statement about resumption is correct?
📖 Explanation: Thread.sleep() requests a waiting interval but does not guarantee exact resumption at its end. Timer precision and scheduling affect when execution resumes, and the sleeping thread retains monitors it already owns.
Q25. A worker writes a result and terminates. The main thread successfully returns from join() before reading that result. What ordering guarantee is relevant?
📖 Explanation: The Java memory model defines a happens-before relationship from a thread's actions to another thread's successful return from joining it. This makes the worker's completed writes visible to the joiner, assuming the result remains valid.
Q26. A Java service constructs a configuration object and assigns it to a shared non-volatile field while worker threads read it without synchronization. What is the safest assessment?
📖 Explanation: Safe publication needs a happens-before mechanism so readers reliably observe the constructed object's state. Synchronization, a volatile reference, or suitable concurrent utilities can provide ordering; an unsynchronized shared assignment may not.
Q27. A worker captures a mutable object reference and reads it while the main thread modifies the same object without synchronization. Which statement is correct?
📖 Explanation: Passing or capturing an object reference does not normally clone its target. Both threads may access the same mutable object; without synchronization, immutable design, or a suitable concurrent structure, their accesses may race.
Q28. A Java method performs independent computation inside a long synchronized block, causing many other threads to wait. Which change can improve concurrency without discarding protection?
📖 Explanation: A long critical section prevents other threads from entering code guarded by the same monitor. Moving independent work outside reduces lock hold time while retaining synchronization around state changes that must remain mutually consistent.
Q29. A benchmark records worker count and completed requests per second: (1, 40), (2, 72), (4, 110), (6, 118), and (8, 119). Which conclusion is best supported?
📖 Explanation: Throughput rises from 40 to 119 requests per second, but the gain from six to eight workers is only one. The measurements suggest saturation or another bottleneck, so adding workers provides little further benefit.
Q30. A Java benchmark records worker count and speedup: (1, 1.0) ; (2, 1.7) ; (4, 2.9) ; (6, 3.5) ; (8, 3.7). Which interpretation best fits the measurements?
📖 Explanation: Speedup rises from 1.0 to 3.7, but successive gains become smaller. The pattern is consistent with serial work, synchronization, or resource limits; extra workers do not guarantee linear performance improvement.
Q31. A library method synchronizes on this, and unrelated application code also locks the same public object. What design improvement reduces unintended lock contention?
📖 Explanation: Using a public object as an internal monitor lets unrelated code contend for the same lock and unexpectedly delay library operations. A private lock object confines the synchronization mechanism and reduces interference from external callers.
Q32. A CountDownLatch is initialized to four. Four workers each call countDown() once after finishing, while the main thread calls await(). When can the main thread proceed?
📖 Explanation: CountDownLatch releases waiting threads when its count reaches zero. Starting at four and receiving one countDown() from each of four workers reduces the count to zero, allowing the main thread's await() to return.
Q33. A Java worker calls Thread.yield() while waiting for another thread to update a shared flag. The programmer assumes the call both transfers execution and makes the new flag value visible. What is wrong?
📖 Explanation: The assumption combines two guarantees that yield() does not provide. The scheduler may ignore the hint, and yield() has no synchronization semantics; use an appropriate volatile, atomic, or locking protocol for shared-state visibility.