Java Multithreading & Concurrency MCQs

1 min read

Java multithreading and concurrency are core pillars for building high-performance, responsive applications that execute multiple tasks simultaneously. Utilizing the java.util.concurrent package, developers can manage thread lifecycles, leverage thread pools via Executor services, and implement thread-safe data structures without manual monitor synchronization. Mastery of concepts like synchronization, locks, volatile variables, and atomic operations is essential for avoiding race conditions, deadlocks, and memory inconsistency errors. These concepts form the bedrock of robust enterprise software development and technical interviews.

1. Which of the following is NOT a valid way to create a thread in Java?

a) Implementing the Runnable interface
b) Extending the Thread class
c) Implementing the Callable interface
d) Extending the Runnable class
Correct Answer: d) Extending the Runnable class
Explanation:
Runnable is an interface, not a class. Therefore, it must be implemented, not extended.

2. What is the correct method to start a new thread in Java?

a) run()
b) start()
c) execute()
d) init()
Correct Answer: b) start()
Explanation:
The start() method is used to begin execution of a thread. It internally calls the run() method in a new call stack.

3. What happens if you directly call the run() method instead of start()?

a) A new thread is created and started
b) A CompilationError is thrown
c) A RuntimeException is thrown
d) The run() method executes in the current thread
Correct Answer: d) The run() method executes in the current thread
Explanation:
Calling run() directly does not create a new thread. It simply executes the method within the current thread's call stack like a normal method call.

4. Which state is a thread in when it has been created but start() has not been called yet?

a) RUNNABLE
b) NEW
c) WAITING
d) BLOCKED
Correct Answer: b) NEW
Explanation:
A thread is in the NEW state after it is instantiated but before its start() method is invoked.

5. Which method can be used to pause the execution of the current thread for a specified duration?

a) Thread.pause()
b) Thread.stop()
c) Thread.sleep()
d) Thread.wait()
Correct Answer: c) Thread.sleep()
Explanation:
Thread.sleep(milliseconds) pauses the currently executing thread for the specified amount of time.

6. Which keyword is used to prevent multiple threads from accessing a block of code simultaneously?

a) volatile
b) synchronized
c) transient
d) atomic
Correct Answer: b) synchronized
Explanation:
The synchronized keyword ensures that only one thread can execute a block of code or method at a time for a given object lock.

7. What lock is acquired when a synchronized non-static method is executed?

a) The class lock
b) The method lock
c) The object instance lock
d) The thread lock
Correct Answer: c) The object instance lock
Explanation:
A synchronized non-static method acquires the intrinsic lock of the object instance it is invoked on.

8. What lock is acquired when a synchronized static method is executed?

a) The object instance lock
b) The Class object lock
c) The method lock
d) No lock is acquired
Correct Answer: b) The Class object lock
Explanation:
A synchronized static method acquires the lock of the Class object associated with the class, not the instance.

9. Which exception is thrown if Thread.sleep() is interrupted by another thread?

a) IllegalMonitorStateException
b) InterruptedException
c) IllegalThreadStateException
d) RuntimeException
Correct Answer: b) InterruptedException
Explanation:
Thread.sleep() throws a checked InterruptedException if the sleeping thread is interrupted.

10. What is the primary purpose of the volatile keyword in Java?

a) To make a variable constant
b) To ensure visibility of updates to variables across threads
c) To provide mutual exclusion
d) To serialize objects
Correct Answer: b) To ensure visibility of updates to variables across threads
Explanation:
The volatile keyword guarantees that changes made to a variable by one thread are immediately visible to other threads by reading directly from main memory.

11. Does volatile guarantee atomicity for compound operations like incrementing a counter?

a) Yes, completely
b) No, it only guarantees visibility
c) Yes, but only for primitive types
d) Yes, but only on single-core processors
Correct Answer: b) No, it only guarantees visibility
Explanation:
volatile ensures visibility but not atomicity. Operations like count++ involve read, update, and write, which can still be interleaved between threads.

12. Which method is used to wait for a thread to finish its execution?

a) yield()
b) wait()
c) join()
d) stop()
Correct Answer: c) join()
Explanation:
The join() method allows one thread to wait until another thread completes its execution.

13. What does the Thread.yield() method do?

a) Forces the thread to stop immediately
b) Puts the thread to sleep for 1 millisecond
c) Hints to the scheduler that the current thread is willing to yield its current use of a processor
d) Throws an InterruptedException
Correct Answer: c) Hints to the scheduler that the current thread is willing to yield its current use of a processor
Explanation:
yield() is a hint to the thread scheduler to pause the current thread and allow other threads of the same or higher priority to execute.

14. Which class contains the wait(), notify(), and notifyAll() methods?

a) Thread
b) Runnable
c) Object
d) Concurrency
Correct Answer: c) Object
Explanation:
These inter-thread communication methods are defined in the java.lang.Object class because they require acquiring the object monitor lock.

15. What must be true for a thread to call wait() on an object?

a) The thread must own the object monitor lock
b) The thread must be a daemon thread
c) The object must be volatile
d) The thread must be sleeping
Correct Answer: a) The thread must own the object monitor lock
Explanation:
A thread must have acquired the intrinsic lock of the object via a synchronized block or method before calling wait(), notify(), or notifyAll().

16. What exception is thrown if wait() is called without owning the monitor?

a) InterruptedException
b) IllegalMonitorStateException
c) IllegalThreadStateException
d) NullPointerException
Correct Answer: b) IllegalMonitorStateException
Explanation:
If a thread attempts to call wait() or notify() without holding the lock for the object, an IllegalMonitorStateException is thrown.

17. What is the main difference between wait() and sleep()?

a) wait() is static, sleep() is non-static
b) wait() releases the lock, sleep() holds the lock
c) wait() holds the lock, sleep() releases the lock
d) There is no difference
Correct Answer: b) wait() releases the lock, sleep() holds the lock
Explanation:
When wait() is called, the thread releases the lock it holds on the object. sleep() pauses the thread but keeps all locks acquired.

18. Why is it recommended to call wait() inside a while loop rather than an if statement?

a) To avoid a CompilationError
b) To improve CPU performance
c) To handle spurious wakeups
d) Because if statements cannot contain wait()
Correct Answer: c) To handle spurious wakeups
Explanation:
Threads can sometimes wake up without notify() being called due to spurious wakeups. The while loop ensures the condition is re-checked upon waking up.

19. Which of these is a daemon thread in Java?

a) The main thread
b) A thread created by extending Thread
c) The Garbage Collector thread
d) A thread with MAX_PRIORITY
Correct Answer: c) The Garbage Collector thread
Explanation:
Daemon threads run in the background. The JVM exits when all non-daemon user threads finish, regardless of daemon threads.

20. How do you make a user thread into a daemon thread?

a) By calling setDaemon(true) before starting the thread
b) By calling setDaemon(true) after starting the thread
c) By implementing the Daemon interface
d) By extending the DaemonThread class
Correct Answer: a) By calling setDaemon(true) before starting the thread
Explanation:
You must call setDaemon(true) on a Thread instance before calling start(). Doing it after throws an IllegalThreadStateException.

21. Which interface in java.util.concurrent returns a result from a background thread?

a) Runnable
b) Callable
c) Future
d) Executor
Correct Answer: b) Callable
Explanation:
Callable is similar to Runnable but its call() method returns a result and can throw a checked exception.

22. What is the return type of the call() method in the Callable interface?

a) void
b) Object
c) V (Generic Type)
d) int
Correct Answer: c) V (Generic Type)
Explanation:
The Callable interface is parameterized (Callable), and its call() method returns an object of type V.

23. Which interface is used to retrieve the result of a Callable task?

a) Executor
b) Result
c) Future
d) Promise
Correct Answer: c) Future
Explanation:
When an ExecutorService submits a Callable, it returns a Future object, which can be used to retrieve the result using the get() method.

24. What does the get() method of the Future interface do?

a) Returns the task immediately, or null if not done
b) Blocks the current thread until the result is available
c) Cancels the task
d) Returns a new ExecutorService
Correct Answer: b) Blocks the current thread until the result is available
Explanation:
Future.get() is a blocking call. It will halt the calling thread until the computation is complete and the result is available.

25. Which framework in Java is used to manage a pool of threads and assign tasks to them?

a) Collections Framework
b) Executor Framework
c) Fork/Join Framework
d) Stream API
Correct Answer: b) Executor Framework
Explanation:
The Executor Framework (java.util.concurrent) simplifies thread management by providing thread pools to execute tasks asynchronously.

26. Which factory class provides methods to create different types of thread pools?

a) ThreadPool
b) Executors
c) ExecutorService
d) ThreadFactory
Correct Answer: b) Executors
Explanation:
The Executors utility class provides factory methods like newFixedThreadPool, newCachedThreadPool, and newSingleThreadExecutor.

27. Which thread pool creates a pool that reuses a fixed number of threads operating off a shared unbounded queue?

a) newCachedThreadPool()
b) newScheduledThreadPool()
c) newFixedThreadPool()
d) newSingleThreadExecutor()
Correct Answer: c) newFixedThreadPool()
Explanation:
Executors.newFixedThreadPool(n) creates a pool with exactly n threads. Tasks wait in a queue if all threads are busy.

28. Which thread pool creates new threads as needed, but will reuse previously constructed threads when they are available?

a) newCachedThreadPool()
b) newFixedThreadPool()
c) newSingleThreadExecutor()
d) newWorkStealingPool()
Correct Answer: a) newCachedThreadPool()
Explanation:
newCachedThreadPool creates an expandable thread pool that kills idle threads after 60 seconds of inactivity.

29. What is the purpose of a ScheduledExecutorService?

a) To execute tasks immediately
b) To execute tasks after a given delay, or periodically
c) To sort threads based on priority
d) To force garbage collection periodically
Correct Answer: b) To execute tasks after a given delay, or periodically
Explanation:
ScheduledExecutorService provides methods like schedule(), scheduleAtFixedRate(), and scheduleWithFixedDelay() for timed executions.

30. What happens if an unhandled exception occurs inside a thread's run() method?

a) The JVM crashes
b) The thread terminates, but the application continues if other user threads are alive
c) The thread is restarted automatically
d) The exception is ignored
Correct Answer: b) The thread terminates, but the application continues if other user threads are alive
Explanation:
An unhandled exception terminates that specific thread. Other threads continue running normally.

31. How can you catch an unhandled exception thrown by a thread?

a) Wrap the start() call in a try-catch block
b) Use Thread.setDefaultUncaughtExceptionHandler()
c) You cannot catch it
d) Use the throws keyword on run()
Correct Answer: b) Use Thread.setDefaultUncaughtExceptionHandler()
Explanation:
Uncaught exceptions in a thread can be handled by setting an UncaughtExceptionHandler on the thread or globally.

32. What is a race condition?

a) When threads compete for the highest priority
b) When two or more threads access shared data concurrently and the outcome depends on thread scheduling
c) When a thread enters an infinite loop
d) When the CPU overheats from too many threads
Correct Answer: b) When two or more threads access shared data concurrently and the outcome depends on thread scheduling
Explanation:
A race condition occurs when concurrent threads perform interleaved operations on shared data, leading to unpredictable and incorrect results.

33. What is deadlock in Java?

a) When all threads are blocked waiting for a lock that is held by another thread in the cycle
b) When a thread dies unexpectedly
c) When a thread is waiting for user input
d) When the JVM runs out of memory
Correct Answer: a) When all threads are blocked waiting for a lock that is held by another thread in the cycle
Explanation:
Deadlock happens when two or more threads hold locks and wait for locks held by each other, forming a cyclic dependency where none can proceed.

34. Which of these is NOT a condition required for deadlock?

a) Mutual Exclusion
b) Hold and Wait
c) No Preemption
d) Thread Starvation
Correct Answer: d) Thread Starvation
Explanation:
The four Coffman conditions for deadlock are: Mutual Exclusion, Hold and Wait, No Preemption, and Circular Wait. Starvation is a different issue.

35. What is thread starvation?

a) A thread is unable to gain regular access to shared resources and is unable to make progress
b) A thread runs out of memory
c) A thread throws an exception
d) A thread is stuck in a wait() loop forever
Correct Answer: a) A thread is unable to gain regular access to shared resources and is unable to make progress
Explanation:
Starvation occurs when a thread is constantly skipped by the scheduler or cannot acquire locks because other threads keep acquiring them first.

36. What is livelock?

a) Threads are stuck waiting for each other passively
b) Threads constantly change state in response to each other without making any real progress
c) A thread is waiting for an event that never happens
d) Threads run extremely fast without utilizing CPU
Correct Answer: b) Threads constantly change state in response to each other without making any real progress
Explanation:
In a livelock, threads are actively running and responding to each other, but they fall into a repetitive loop and make no actual progress.

37. Which class provides thread-local variables?

a) LocalThread
b) ThreadLocal
c) ThreadVariable
d) IsolatedThread
Correct Answer: b) ThreadLocal
Explanation:
The ThreadLocal class enables you to create variables that can only be read and written by the same thread, preventing shared state issues.

38. What does the method shutdown() do in an ExecutorService?

a) Immediately kills all running threads
b) Initiates an orderly shutdown where previously submitted tasks are executed, but no new tasks will be accepted
c) Pauses the execution of all threads
d) Returns the results of all tasks instantly
Correct Answer: b) Initiates an orderly shutdown where previously submitted tasks are executed, but no new tasks will be accepted
Explanation:
shutdown() allows currently running and queued tasks to finish, but rejects new task submissions.

39. What does shutdownNow() do in an ExecutorService?

a) Waits for tasks to finish before shutting down
b) Attempts to stop all actively executing tasks and halts processing of waiting tasks
c) Restarts the ExecutorService
d) Ignores running tasks but empties the queue
Correct Answer: b) Attempts to stop all actively executing tasks and halts processing of waiting tasks
Explanation:
shutdownNow() returns a list of tasks that were waiting to execute and attempts to interrupt threads that are currently executing tasks.

40. Which package contains the ReentrantLock class?

a) java.lang.reflect
b) java.util.concurrent
c) java.util.concurrent.locks
d) java.util.concurrent.atomic
Correct Answer: c) java.util.concurrent.locks
Explanation:
ReentrantLock, ReadWriteLock, and Condition are located in the java.util.concurrent.locks package.

41. What does a ReentrantLock provide that the synchronized keyword does not?

a) Visibility guarantees
b) Mutual exclusion
c) Fairness parameter, tryLock(), and interruptible lock acquisition
d) Faster execution times
Correct Answer: c) Fairness parameter, tryLock(), and interruptible lock acquisition
Explanation:
ReentrantLock provides advanced features like polling via tryLock, interruptible lock waits, and fairness policies.

42. What does the fairness policy do in a ReentrantLock?

a) Ensures the longest-waiting thread gets the lock next
b) Randomly selects a thread to get the lock
c) Prioritizes threads based on Thread priority levels
d) Allows multiple threads to hold the lock simultaneously
Correct Answer: a) Ensures the longest-waiting thread gets the lock next
Explanation:
If a ReentrantLock is instantiated with fair set to true, it favors granting access to the thread that has been waiting the longest.

43. Which method attempts to acquire a ReentrantLock but returns immediately if the lock is not available?

a) lock()
b) tryLock()
c) acquire()
d) lockInterruptibly()
Correct Answer: b) tryLock()
Explanation:
tryLock() attempts to get the lock. If it is free, it acquires it and returns true. If held by another thread, it immediately returns false.

44. What is a ReadWriteLock used for?

a) To allow multiple threads to write simultaneously
b) To allow concurrent access for read-only operations, while write operations require exclusive access
c) To convert readable streams to writable streams
d) To lock files on the operating system
Correct Answer: b) To allow concurrent access for read-only operations, while write operations require exclusive access
Explanation:
ReadWriteLock improves performance for read-heavy operations by allowing multiple reader threads to hold the read lock concurrently.

45. Which method of the Condition interface is the equivalent of Object.wait()?

a) sleep()
b) pause()
c) await()
d) yield()
Correct Answer: c) await()
Explanation:
Condition.await() serves the same purpose as Object.wait(), allowing a thread to wait for a specific condition within a ReentrantLock.

46. Which method of the Condition interface is the equivalent of Object.notifyAll()?

a) signalAll()
b) notifyGroup()
c) wakeAll()
d) releaseAll()
Correct Answer: a) signalAll()
Explanation:
Condition.signalAll() wakes up all threads waiting on that specific Condition instance.

47. Which of the following classes is inherently thread-safe?

a) HashMap
b) ArrayList
c) Vector
d) StringBuilder
Correct Answer: c) Vector
Explanation:
Vector is a legacy collection class where all of its core methods are synchronized, making it inherently thread-safe.

48. Which collection provides a thread-safe, highly concurrent implementation of a Map?

a) Hashtable
b) HashMap
c) ConcurrentHashMap
d) SynchronizedMap
Correct Answer: c) ConcurrentHashMap
Explanation:
ConcurrentHashMap partitions the map and locks only specific segments or bins, providing thread safety with very high concurrency compared to Hashtable.

49. What is the primary characteristic of a CopyOnWriteArrayList?

a) It copies data to a file on every write
b) It is read-only
c) Mutative operations create a new copy of the underlying array
d) It requires manual synchronization for iteration
Correct Answer: c) Mutative operations create a new copy of the underlying array
Explanation:
CopyOnWriteArrayList creates a fresh copy of the internal array for every write operation, making it ideal when reads vastly outnumber writes.

50. Which interface represents a thread-safe queue that supports blocking operations on insert and retrieval?

a) PriorityQueue
b) ConcurrentLinkedQueue
c) BlockingQueue
d) Deque
Correct Answer: c) BlockingQueue
Explanation:
BlockingQueue provides methods like put() and take() that block the thread if the queue is full or empty.

51. Which BlockingQueue method inserts an element, waiting if necessary for space to become available?

a) add()
b) offer()
c) put()
d) insert()
Correct Answer: c) put()
Explanation:
The put() method blocks the calling thread until space becomes available in a bounded BlockingQueue.

52. Which BlockingQueue method retrieves and removes an element, waiting if necessary until an element becomes available?

a) remove()
b) poll()
c) take()
d) get()
Correct Answer: c) take()
Explanation:
The take() method blocks the calling thread until an element is available to be removed from the BlockingQueue.

53. What is a CountDownLatch used for?

a) To count the number of active threads
b) To allow threads to wait until a set of operations in other threads completes
c) To limit the maximum number of threads executing simultaneously
d) To act as a recurring barrier for a set of threads
Correct Answer: b) To allow threads to wait until a set of operations in other threads completes
Explanation:
CountDownLatch is initialized with a count. Threads call await() to wait until the count reaches zero after other threads call countDown().

54. What is the difference between CountDownLatch and CyclicBarrier?

a) CyclicBarrier can be reused after it trips, CountDownLatch cannot
b) CountDownLatch is for multi-threading, CyclicBarrier is for single-threading
c) CountDownLatch can be reused, CyclicBarrier cannot
d) There is no difference
Correct Answer: a) CyclicBarrier can be reused after it trips, CountDownLatch cannot
Explanation:
A CyclicBarrier allows threads to wait for each other to reach a common barrier point and can be reset. CountDownLatch is used once.

55. Which class is used to restrict the number of threads that can access a physical or logical resource?

a) Mutex
b) Semaphore
c) Exchanger
d) Phaser
Correct Answer: b) Semaphore
Explanation:
A Semaphore maintains a set of permits. Threads call acquire() to get a permit and release() to return it, limiting concurrent access.

56. What does Semaphore.acquire() do?

a) Increments the permit count
b) Creates a new thread
c) Blocks until a permit is available, then takes it
d) Returns a boolean immediately indicating if a permit was available
Correct Answer: c) Blocks until a permit is available, then takes it
Explanation:
acquire() blocks the calling thread if no permits are available. Once available, it decrements the permit count and proceeds.

57. Which concurrency utility allows two threads to exchange objects at a synchronization point?

a) Exchanger
b) CyclicBarrier
c) TransferQueue
d) SwapManager
Correct Answer: a) Exchanger
Explanation:
Exchanger is a synchronization point where two threads can swap data. The first thread waits until the second arrives.

58. Which concurrency utility is a flexible alternative to CountDownLatch and CyclicBarrier that supports dynamic numbers of parties?

a) ForkJoinPool
b) Phaser
c) Semaphore
d) CompletableFuture
Correct Answer: b) Phaser
Explanation:
Phaser allows parties to dynamically register and deregister, and supports synchronization over multiple phases.

59. In the java.util.concurrent.atomic package, how is thread safety achieved?

a) Using the synchronized keyword
b) Using ReentrantLocks
c) Using Compare-And-Swap instructions
d) Using ThreadLocals
Correct Answer: c) Using Compare-And-Swap instructions
Explanation:
Atomic classes use low-level native Compare-And-Swap operations to perform lock-free, thread-safe variable updates.

60. Which method in AtomicInteger increments the value and returns the updated value?

a) getAndIncrement()
b) incrementAndGet()
c) addAndGet()
d) update()
Correct Answer: b) incrementAndGet()
Explanation:
incrementAndGet() atomically increments by one the current value and returns the new value.

61. What does CAS stand for in the context of concurrent programming?

a) Concurrent And Synchronized
b) Compare And Swap
c) Compute And Store
d) Copy And Set
Correct Answer: b) Compare And Swap
Explanation:
Compare-And-Swap is an atomic operation used in multithreading to achieve synchronization without traditional locks.

62. What is the Fork/Join framework designed for?

a) Executing simple I/O tasks
b) Connecting to remote databases
c) Taking advantage of multiple processors by recursively splitting tasks into smaller subtasks
d) Replacing the ExecutorService entirely
Correct Answer: c) Taking advantage of multiple processors by recursively splitting tasks into smaller subtasks
Explanation:
Fork/Join is tailored for CPU-intensive workloads that can be divided into smaller chunks and whose results can be combined.

63. Which algorithm is utilized by the ForkJoinPool to maintain high performance?

a) Round-robin scheduling
b) Work-stealing algorithm
c) Shortest job first
d) MapReduce
Correct Answer: b) Work-stealing algorithm
Explanation:
In ForkJoinPool, idle threads steal tasks from the queues of busy threads, ensuring all CPU cores remain fully utilized.

64. Which class is the base type for tasks executed in a ForkJoinPool?

a) ForkJoinTask
b) RecursiveThread
c) CallableTask
d) SplitTask
Correct Answer: a) ForkJoinTask
Explanation:
ForkJoinTask is the base class. Developers typically extend its abstract subclasses RecursiveAction or RecursiveTask.

65. Which subclass of ForkJoinTask is used when the task does NOT return a result?

a) RecursiveTask
b) RecursiveAction
c) ForkJoinAction
d) VoidTask
Correct Answer: b) RecursiveAction
Explanation:
RecursiveAction represents a computation that does not return a result, similar to Runnable.

66. Which method must be overridden when implementing a RecursiveTask or RecursiveAction?

a) run()
b) call()
c) compute()
d) execute()
Correct Answer: c) compute()
Explanation:
The compute() method contains the main computation logic and the rules for splitting the task.

67. What is CompletableFuture in Java 8?

a) A thread pool for executing tasks
b) An extension of Future that supports functional, asynchronous, non-blocking programming
c) A synchronized block implementation
d) A collection that prevents deadlocks
Correct Answer: b) An extension of Future that supports functional, asynchronous, non-blocking programming
Explanation:
CompletableFuture implements Future and CompletionStage, allowing you to chain callbacks and compose asynchronous operations.

68. Which method in CompletableFuture executes a Runnable asynchronously?

a) supplyAsync()
b) runAsync()
c) executeAsync()
d) doAsync()
Correct Answer: b) runAsync()
Explanation:
CompletableFuture.runAsync(Runnable) executes the task in a background thread and returns a CompletableFuture of type Void.

69. Which method in CompletableFuture executes a task asynchronously and returns a result?

a) runAsync()
b) callAsync()
c) supplyAsync()
d) computeAsync()
Correct Answer: c) supplyAsync()
Explanation:
CompletableFuture.supplyAsync(Supplier) executes a task asynchronously and returns a CompletableFuture holding the result.

70. How do you chain a callback that consumes the result of a CompletableFuture without returning a new value?

a) thenApply()
b) thenAccept()
c) thenRun()
d) thenConsume()
Correct Answer: b) thenAccept()
Explanation:
thenAccept(Consumer) takes the result of the previous stage, processes it, and returns a CompletableFuture of type Void.

71. How do you transform the result of a CompletableFuture and pass it to the next stage?

a) thenApply()
b) thenAccept()
c) thenMap()
d) mapAsync()
Correct Answer: a) thenApply()
Explanation:
thenApply(Function) takes the result of the previous stage, applies a function, and returns a CompletableFuture with the transformed result.

72. What is the purpose of ThreadLocalRandom?

a) To generate secure cryptographic hashes
b) To provide high-performance concurrent random number generation without contention
c) To ensure random numbers are the same across all threads
d) To limit the pool of random numbers
Correct Answer: b) To provide high-performance concurrent random number generation without contention
Explanation:
ThreadLocalRandom isolates the state to each thread, avoiding synchronization overhead associated with java.util.Random.

73. Which statement about java.util.Timer and ExecutorService is true?

a) Timer is preferred over ScheduledExecutorService in modern Java
b) Timer handles multiple threads, ScheduledExecutorService is single-threaded
c) Timer can be killed by an unchecked exception in a task, killing all scheduled tasks
d) There is no functional difference
Correct Answer: c) Timer can be killed by an unchecked exception in a task, killing all scheduled tasks
Explanation:
Timer relies on a single background thread. If one task throws an unchecked exception, the Timer thread dies, cancelling all other scheduled tasks.

74. Which interface represents an object that creates new threads on demand?

a) Executor
b) ThreadFactory
c) Runnable
d) Callable
Correct Answer: b) ThreadFactory
Explanation:
ThreadFactory provides a method to construct new threads, often used to set custom names, daemon status, or priorities.

75. How do you interrupt a thread gracefully in Java?

a) Call thread.stop()
b) Call thread.interrupt() and handle InterruptedException or check isInterrupted()
c) Call thread.destroy()
d) Set a boolean flag directly inside the Thread class
Correct Answer: b) Call thread.interrupt() and handle InterruptedException or check isInterrupted()
Explanation:
The interrupt() method sets the thread interrupt status. The thread should routinely check Thread.interrupted() or catch InterruptedException to terminate gracefully.

76. What is the difference between interrupted() and isInterrupted()?

a) They do the exact same thing
b) interrupted() is a static method that clears the interrupt flag; isInterrupted() is non-static and does not clear it
c) isInterrupted() clears the flag; interrupted() does not
d) interrupted() throws an exception; isInterrupted() returns a boolean
Correct Answer: b) interrupted() is a static method that clears the interrupt flag; isInterrupted() is non-static and does not clear it
Explanation:
Thread.interrupted() checks the current thread status and clears the flag. instance.isInterrupted() checks a specific thread status but leaves the flag untouched.

77. What causes an IllegalThreadStateException?

a) Calling start() on a thread that has already been started or has finished
b) Interrupting a sleeping thread
c) Calling wait() without acquiring the lock
d) Accessing a thread variable from another thread
Correct Answer: a) Calling start() on a thread that has already been started or has finished
Explanation:
Once a thread is started, it cannot be started again. Doing so throws an IllegalThreadStateException.

78. Which block ensures that a lock is always released when using ReentrantLock?

a) try-catch
b) try-finally
c) synchronize block
d) lock-finally
Correct Answer: b) try-finally
Explanation:
When using explicit locks like ReentrantLock, unlock() must be placed in a finally block to ensure the lock is released even if an exception is thrown.

79. Is it possible for a thread to acquire a ReentrantLock multiple times without releasing it first?

a) No, it will cause a deadlock
b) No, an exception will be thrown
c) Yes, because the lock is reentrant, but it must be released the same number of times
d) Yes, and releasing it once is sufficient
Correct Answer: c) Yes, because the lock is reentrant, but it must be released the same number of times
Explanation:
A ReentrantLock allows the thread that currently owns the lock to re-acquire it multiple times. A hold count is maintained, so unlock() must be called an equal number of times.

80. In Java Memory Model (JMM), what is a happens-before relationship?

a) A guarantee that thread A executes before thread B
b) A guarantee that memory writes by one specific statement are visible to another specific statement
c) A guarantee that the JVM will compile code sequentially
d) A rule stating that variables must be declared before use
Correct Answer: b) A guarantee that memory writes by one specific statement are visible to another specific statement
Explanation:
The happens-before relation in JMM guarantees memory visibility. If action A happens-before action B, changes made by A are visible to B.

81. Which action establishes a happens-before relationship?

a) Writing to a non-volatile variable
b) Calling Thread.sleep()
c) Unlocking a monitor lock happens-before every subsequent locking of that same monitor
d) System.out.println()
Correct Answer: c) Unlocking a monitor lock happens-before every subsequent locking of that same monitor
Explanation:
The JMM specifies that an unlock operation on a monitor happens-before any subsequent lock operation on that same monitor.

82. What is the Double-Checked Locking idiom typically used for?

a) To prevent deadlocks
b) To efficiently implement a thread-safe Singleton design pattern
c) To acquire two locks simultaneously
d) To detect race conditions
Correct Answer: b) To efficiently implement a thread-safe Singleton design pattern
Explanation:
Double-checked locking checks if an instance is initialized without acquiring a lock first, optimizing the thread-safe initialization of a Singleton.

83. Which Atomic class is best suited for maintaining a thread-safe true or false flag?

a) AtomicFlag
b) AtomicBoolean
c) AtomicInteger
d) AtomicReference
Correct Answer: b) AtomicBoolean
Explanation:
AtomicBoolean provides lock-free, atomic operations on a boolean value, making it perfect for concurrent flags.

84. How is thread priority represented in Java?

a) An integer from 1 to 10
b) An integer from 0 to 100
c) An enum value
d) An integer from -1 to 1
Correct Answer: a) An integer from 1 to 10
Explanation:
Thread priorities are integers from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10).

85. Is thread priority guaranteed by the JVM scheduler?

a) Yes, strictly enforced
b) No, it is merely a hint to the underlying OS scheduler
c) Yes, but only on Windows OS
d) Yes, but only for daemon threads
Correct Answer: b) No, it is merely a hint to the underlying OS scheduler
Explanation:
Thread priorities are mapped to OS-level priorities, and the JVM cannot guarantee that a higher priority thread will execute before a lower priority one.

86. What does a ThreadGroup do in Java?

a) Runs multiple threads in parallel on a single core
b) Allows grouping of threads to manage them collectively
c) Provides a pool of reusable threads
d) Ensures mutual exclusion for a group of threads
Correct Answer: b) Allows grouping of threads to manage them collectively
Explanation:
ThreadGroup provides a way to manage threads as a collective set, though its use is largely discouraged in favor of the Executor framework.

87. Which synchronization structure allows threads to lock conditionally with multiple wait-sets per lock?

a) synchronized keyword
b) ReentrantLock with multiple Condition objects
c) Semaphore
d) AtomicInteger
Correct Answer: b) ReentrantLock with multiple Condition objects
Explanation:
Unlike the intrinsic lock which has a single wait-set, a ReentrantLock can create multiple Condition objects, each providing its own wait-set.

88. What does ConcurrentModificationException indicate?

a) Two threads attempted to lock the same object
b) A thread modified a collection while it was being iterated using a fail-fast iterator
c) A thread pool rejected a task
d) A volatile variable was modified incorrectly
Correct Answer: b) A thread modified a collection while it was being iterated using a fail-fast iterator
Explanation:
This runtime exception occurs when an object is concurrently modified while an iterator is iterating over it, without using the iterator own modification methods.

89. Which concurrent collection does not throw ConcurrentModificationException during iteration?

a) ArrayList
b) HashMap
c) CopyOnWriteArrayList
d) HashSet
Correct Answer: c) CopyOnWriteArrayList
Explanation:
Collections in java.util.concurrent like CopyOnWriteArrayList use fail-safe iterators that operate on a snapshot and do not throw this exception.

90. What is the primary difference between Runnable and Callable?

a) Runnable runs synchronously, Callable runs asynchronously
b) Runnable can return a value and throw checked exceptions, Callable cannot
c) Callable can return a value and throw checked exceptions, Runnable cannot
d) There is no difference
Correct Answer: c) Callable can return a value and throw checked exceptions, Runnable cannot
Explanation:
Runnable run method has a void return type and cannot throw checked exceptions. Callable call method returns a generic value and throws Exception.

91. Which method on an ExecutorService submits a Callable for execution?

a) execute()
b) submit()
c) run()
d) invoke()
Correct Answer: b) submit()
Explanation:
The submit() method accepts a Callable or Runnable and returns a Future object representing the pending results of the task.

92. What does the invokeAll() method of ExecutorService do?

a) Executes a collection of Callables and returns a list of Futures when all complete
b) Executes one task and cancels the rest
c) Shuts down the executor after running all tasks
d) Invokes the main method asynchronously
Correct Answer: a) Executes a collection of Callables and returns a list of Futures when all complete
Explanation:
invokeAll() executes a collection of Callable tasks, blocking until all tasks have completed, and returns a list of Future objects.

93. What does the invokeAny() method of ExecutorService do?

a) Returns the result of the last task to finish
b) Executes tasks sequentially until one succeeds, then returns its result
c) Executes a collection of tasks and returns the result of the first one to successfully complete, cancelling the others
d) Throws an exception if multiple tasks are submitted
Correct Answer: c) Executes a collection of tasks and returns the result of the first one to successfully complete, cancelling the others
Explanation:
invokeAny() blocks until at least one task completes successfully, returns that result, and cancels remaining tasks.

94. Which interface allows tasks to be canceled after submission?

a) Runnable
b) Callable
c) Future
d) Thread
Correct Answer: c) Future
Explanation:
The Future interface provides a cancel method to attempt to cancel execution of a submitted task.

95. In the Future.cancel method, what does true mean for the mayInterruptIfRunning parameter?

a) The task is guaranteed to stop immediately
b) The thread executing the task should be interrupted if it is already running
c) The task is removed from the queue without execution
d) The JVM is shut down
Correct Answer: b) The thread executing the task should be interrupted if it is already running
Explanation:
If true, the executor will call interrupt() on the thread currently executing the task.

96. What is LongAdder used for?

a) Concatenating long strings
b) Storing large arrays of long values
c) Maintaining a sum efficiently under high contention
d) A replacement for BigInteger
Correct Answer: c) Maintaining a sum efficiently under high contention
Explanation:
LongAdder provides much better performance than AtomicLong when updated concurrently by many threads.

97. What is StampedLock?

a) A lock used for file operations
b) An enhanced ReadWriteLock that supports optimistic reading
c) A lock that timestamps every thread interaction
d) A legacy lock from Java 1.0
Correct Answer: b) An enhanced ReadWriteLock that supports optimistic reading
Explanation:
StampedLock provides an optimistic read mode that does not block writers, which can highly optimize read-heavy scenarios.

98. Which StampedLock method is used for optimistic reading?

a) tryOptimisticRead()
b) readLock()
c) optimisticLock()
d) tryRead()
Correct Answer: a) tryOptimisticRead()
Explanation:
tryOptimisticRead() returns a stamp that can later be validated to check if a write lock was acquired in the meantime.

99. What is a thread dump?

a) A stack trace of a single thread
b) A snapshot of the state of all threads running in a JVM at a given time
c) A file that stores deleted threads
d) A memory leak caused by unclosed threads
Correct Answer: b) A snapshot of the state of all threads running in a JVM at a given time
Explanation:
A thread dump lists every active thread in the JVM along with its stack trace and state, essential for diagnosing deadlocks.

100. How can you trigger a thread dump via the command line for a Java process?

a) Using the jmap command
b) Using the jstack command
c) Using java -dump
d) Using the ping command
Correct Answer: b) Using the jstack command
Explanation:
The jstack command-line utility prints Java thread stack traces for a given Java process ID.

101. What is context switching?

a) Changing a variable from int to String
b) The OS process of storing the state of a thread and restoring the state of another thread to run on the CPU
c) Switching from Java to native code
d) Changing a thread from daemon to non-daemon
Correct Answer: b) The OS process of storing the state of a thread and restoring the state of another thread to run on the CPU
Explanation:
Context switching is how an OS multitasking system shares a single CPU among multiple threads, which carries a performance cost.

102. Which condition causes a thread to enter the BLOCKED state?

a) Calling Thread.sleep()
b) Waiting to acquire an intrinsic monitor lock to enter a synchronized block
c) Calling LockSupport.park()
d) Calling Object.wait()
Correct Answer: b) Waiting to acquire an intrinsic monitor lock to enter a synchronized block
Explanation:
The BLOCKED state strictly means the thread is waiting for a monitor lock to enter or re-enter a synchronized block or method.

103. What state is a thread in if it called Object.wait() with no timeout?

a) BLOCKED
b) WAITING
c) TIMED_WAITING
d) RUNNABLE
Correct Answer: b) WAITING
Explanation:
A thread is in the WAITING state when it is waiting indefinitely for another thread to perform a particular action.

104. What state is a thread in if it called Thread.sleep()?

a) BLOCKED
b) WAITING
c) TIMED_WAITING
d) SLEEPING
Correct Answer: c) TIMED_WAITING
Explanation:
Methods that put a thread in a waiting state for a specified amount of time put the thread in the TIMED_WAITING state.

105. What does a ThreadGroup uncaughtException() method do?

a) Throws the exception back to the JVM
b) Handles unchecked exceptions thrown by threads within that group
c) Silently ignores the exception
d) Shuts down the JVM
Correct Answer: b) Handles unchecked exceptions thrown by threads within that group
Explanation:
If a thread does not have a specific UncaughtExceptionHandler, the JVM forwards the exception to its ThreadGroup uncaughtException method.

106. Are primitive variable assignments atomic in Java?

a) Yes, for all primitive types
b) No, for no primitive types
c) Yes, except for long and double unless declared volatile
d) Yes, but only inside a synchronized block
Correct Answer: c) Yes, except for long and double unless declared volatile
Explanation:
64-bit primitives like long and double are written in two 32-bit operations, meaning they are not atomic unless declared volatile.

107. What does the LockSupport class do?

a) Provides basic thread blocking and unblocking primitives
b) Manages a pool of ReentrantLocks
c) Automatically detects deadlocks
d) A utility to encrypt lock files
Correct Answer: a) Provides basic thread blocking and unblocking primitives
Explanation:
LockSupport provides low-level utility methods park() and unpark() to block and unblock a thread.

108. Can a constructor be synchronized in Java?

a) Yes, by adding the synchronized keyword to the signature
b) No, constructors cannot be synchronized
c) Yes, but only for static constructors
d) Yes, but only for private constructors
Correct Answer: b) No, constructors cannot be synchronized
Explanation:
Constructors cannot be synchronized because the object being constructed is only accessible by the thread creating it until the constructor completes.

109. If Thread A is executing a synchronized instance method, can Thread B execute a non-synchronized instance method on the same object?

a) No, Thread B is blocked
b) Yes, because the non-synchronized method does not require a lock
c) Yes, but only if Thread B has a higher priority
d) No, a ConcurrentModificationException is thrown
Correct Answer: b) Yes, because the non-synchronized method does not require a lock
Explanation:
The intrinsic lock only restricts access to other synchronized methods or blocks. Non-synchronized methods can be executed freely.

110. If Thread A is executing a synchronized instance method, can Thread B execute a synchronized static method of the same class?

a) No, Thread B must wait for the object lock
b) Yes, because they acquire different locks
c) No, Thread A holds all locks for the class
d) Yes, but it causes a race condition
Correct Answer: b) Yes, because they acquire different locks
Explanation:
Instance synchronized methods acquire the object instance lock, while static synchronized methods acquire the Class object lock. They do not block each other.

111. Which executor service creates a pool of threads that can schedule commands to run after a given delay?

a) FixedThreadPool
b) CachedThreadPool
c) WorkStealingPool
d) ScheduledThreadPool
Correct Answer: d) ScheduledThreadPool
Explanation:
Executors.newScheduledThreadPool() returns a ScheduledExecutorService specifically designed for delayed or periodic task execution.

112. What happens if a thread pool is shut down but tasks are still waiting in its queue?

a) The waiting tasks are deleted
b) Using shutdown(), the waiting tasks are executed before the pool terminates completely
c) An exception is immediately thrown
d) The application hangs forever
Correct Answer: b) Using shutdown(), the waiting tasks are executed before the pool terminates completely
Explanation:
shutdown() allows both currently running tasks and tasks queued up to execute. Only new task submissions are rejected.
← Previous: Java Interview Questions MCQs
Next →: Java Operators MCQs
Latest C++ Basics MCQs

Latest C++ Basics MCQs

Created by Bjarne Stroustrup as an extension of the C programming language, C++ is a powerful, high-performance, statically typed language…

By MCQs Generator
C++ Variables & Data Types MCQs

C++ Variables & Data Types MCQs

Variables and data types form the core building blocks of any C++ application, defining how data is stored, represented, and…

By MCQs Generator
C++ Constructors and Destructors MCQs

C++ Constructors and Destructors MCQs

In C++, constructors and destructors are special member functions critical for the Resource Acquisition Is Initialization (RAII) paradigm and safe…

By MCQs Generator