🎓 BookMCQ
← Back to 4. Threads in Operating System

📝 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.
11
Easy
11
Medium
11
Hard

📝 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?

A.It starts a separate thread that executes the run() method when scheduled ✅
B.It executes run() synchronously before returning
C.It waits until the worker has completed its entire task
D.It merges the worker into the main thread
💡 Difficulty: easy | ✅ Correct: A

📖 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?

A.The JVM creates a second thread automatically
B.The method executes as an ordinary call on the current thread ✅
C.The method runs on a separate core if one is idle
D.The worker becomes terminated before entering the method
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.yield()
B.sleep()
C.join() ✅
D.interrupt()
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.The same thread restarts from the beginning
B.The JVM silently creates a replacement thread
C.The second call joins the terminated thread
D.The call fails with IllegalThreadStateException ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.The other thread generally waits because sleep() does not release the monitor ✅
B.The sleeping thread automatically releases every monitor it owns
C.The other thread acquires the monitor immediately
D.The JVM transfers the monitor to the waiting thread
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.It releases every lock held by the thread
B.It releases M's monitor but retains unrelated locks ✅
C.It keeps M's monitor until it is notified
D.It terminates and is recreated after notification
💡 Difficulty: medium | ✅ Correct: B

📖 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?

A.Use sleep() instead because it guarantees an item is present
B.Call notify() from the consumer after every wake-up
C.Check the queue predicate in a synchronized loop and wait while it remains false ✅
D.Assume notification reserves the next item for that consumer
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.It forcibly terminates the worker at the next instruction
B.It makes every operation on all shared variables atomic
C.It creates a private copy of the flag for each thread
D.It supports visibility of flag updates, while the worker must stop cooperatively ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.The interrupt request may be lost because InterruptedException clears the interrupted status ✅
B.The worker is guaranteed to restart its loop from the beginning
C.The exception automatically terminates the entire JVM
D.The interrupt status is always preserved after the exception
💡 Difficulty: hard | ✅ Correct: A

📖 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?

A.The JVM forcibly stops it at the next bytecode
B.The thread may continue because interruption is generally cooperative ✅
C.The thread automatically becomes a daemon
D.All writes made by the thread are rolled back
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.A separate address space for every method
B.A dedicated processor core for the balance owner
C.Mutual exclusion and memory-visibility ordering for code using that same monitor ✅
D.Automatic atomicity for every variable in the application
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.The reader automatically waits for the writer
B.The field becomes immutable after the first update
C.The JVM copies the field separately for every reader
D.The reader has no matching synchronization guarantee for visibility and ordering ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.Java intrinsic monitors are reentrant for their owning thread ✅
B.The second method runs in a separate process
C.The first synchronized method releases the monitor automatically before calling another
D.Nested synchronized methods are ignored by the JVM
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.Increase both threads' priorities
B.Require all threads to acquire locks in one consistent global order ✅
C.Add sleep() between the two lock operations
D.Allow each thread to wait indefinitely for its second lock
💡 Difficulty: hard | ✅ Correct: B

📖 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++?

A.It makes all application objects thread-safe
B.It prevents the JVM from scheduling concurrent workers
C.The counter update is atomic, so increments do not overwrite one another through a read-modify-write race ✅
D.It guarantees that threads finish in creation order
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.It guarantees a single linearizable snapshot with every sum() call
B.It spreads updates across internal cells to reduce contention, though a concurrent sum is not necessarily one instantaneous snapshot ✅
C.It makes every variable in the application atomic
D.It prevents workers from executing at the same time
💡 Difficulty: medium | ✅ Correct: B

📖 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?

A.Each thread maintains its own value without sharing one mutable identifier ✅
B.All threads update a single automatically locked value
C.The variable becomes a process-wide constant
D.ThreadLocal prevents worker threads from being reused
💡 Difficulty: easy | ✅ Correct: A

📖 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?

A.Call start() on the same Thread object
B.Remove the task-specific ThreadLocal value when it is no longer needed ✅
C.Mark the worker as a daemon
D.Call yield() until the pool replaces the worker
💡 Difficulty: medium | ✅ Correct: B

📖 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?

A.The thread receives the highest priority
B.The thread is guaranteed to complete before shutdown
C.Daemon threads alone do not keep the JVM alive after all started non-daemon threads finish ✅
D.The thread runs in a separate JVM process
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.The executor always creates replacement workers beyond its fixed size
B.All queued follow-up tasks execute inside the blocked workers automatically
C.The JVM converts the tasks into asynchronous callbacks
D.The pool can stall because every worker is occupied waiting for work that no worker remains to execute ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.Future ✅
B.ThreadLocal
C.CountDownLatch only
D.volatile boolean
💡 Difficulty: easy | ✅ Correct: A

📖 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?

A.The pool is reducing its worker count as tasks block
B.The pool is limiting concurrency to four workers
C.The pool may be creating more workers as existing ones block, increasing resource consumption ✅
D.The measurements prove that all 20 workers are executing on separate cores
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.Run every stage on one unbounded pool with no limits
B.Use Thread.sleep() between stages to control CPU allocation
C.Separate or appropriately configure executors so blocking I/O does not starve CPU-bound work ✅
D.Create a permanent thread for every possible future continuation
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.It must resume exactly 1,000 milliseconds later
B.It releases all monitors before sleeping
C.It is guaranteed to run before every other runnable thread after the delay
D.It waits at least the requested interval subject to timing, then still depends on scheduling to run ✅
💡 Difficulty: medium | ✅ Correct: D

📖 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?

A.The worker's actions happen-before the successful return from the join in the main thread ✅
B.join() makes the result immutable
C.join() duplicates the result into a new process
D.The main thread must also join every unrelated thread
💡 Difficulty: hard | ✅ Correct: A

📖 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?

A.Construction alone guarantees every field is immediately visible to all threads
B.Workers automatically receive independent copies of the configuration
C.Without safe publication, workers may not reliably observe the fully constructed state ✅
D.The shared reference becomes volatile after the first read
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.Capturing the reference always creates a deep copy
B.The worker and main thread may access the same object, creating a data race or inconsistent observations ✅
C.Only primitive values can be shared between Java threads
D.The JVM automatically locks every object passed to a thread
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.Remove synchronization around all shared updates
B.Increase the block duration so each thread works in larger batches
C.Move independent computation outside the critical section and keep required shared-state changes protected ✅
D.Have waiting threads repeatedly call yield() while holding the same monitor
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.Throughput increases in exact proportion to worker count
B.Throughput falls whenever workers exceed two
C.Eight workers provide eight times the one-worker throughput
D.Throughput improves initially but approaches a plateau as worker count increases ✅
💡 Difficulty: medium | ✅ Correct: D

📖 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?

A.Speedup increases exactly in proportion to worker count
B.Speedup declines whenever more than two workers are used
C.Eight workers provide eight times the single-worker performance
D.Speedup improves but shows diminishing returns as more workers are added ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.Replace synchronization with sleep()
B.Make every application method synchronized on this
C.Use a private lock object for internal synchronization when appropriate ✅
D.Expose the lock and require callers to acquire it first
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.When the first worker starts
B.When any worker calls notify() on its Thread object
C.Only after the main thread also calls countDown()
D.When the latch count reaches zero after all four decrements ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.yield() guarantees the next thread runs and flushes every shared write
B.yield() releases every monitor held by the caller
C.yield() is only a scheduling hint and provides no memory-synchronization guarantee ✅
D.yield() terminates the calling thread after one scheduling interval
💡 Difficulty: hard | ✅ Correct: C

📖 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.

🔗 Related Topics (MCQs)