SCJP Java Threads and Concurrency 2 — Questions and Answers
Question 1: What does the `volatile` keyword guarantee for a variable in Java?
- Mutual exclusion during updates
- Visibility — all threads see the most recent write to the variable (Correct answer)
- The variable is stored only in RAM
- The variable cannot be modified
Correct answer: Visibility — all threads see the most recent write to the variable
`volatile` ensures that reads and writes to a variable go directly to main memory, guaranteeing visibility of changes across threads.
Question 2: Which method is used to start a thread's execution in Java?
- run()
- execute()
- start() (Correct answer)
- init()
Correct answer: start()
Calling `start()` on a `Thread` object creates a new OS thread and schedules the `run()` method for execution.
Question 3: What is a race condition in Java concurrency?
- Two threads competing for CPU speed
- Unpredictable behavior caused by multiple threads accessing shared data without proper synchronization (Correct answer)
- A thread running faster than expected
- A deadlock between three threads
Correct answer: Unpredictable behavior caused by multiple threads accessing shared data without proper synchronization
A race condition occurs when the program's outcome depends on the non-deterministic ordering of unsynchronized thread operations.
Question 4: Which Java class provides a thread-safe, atomic integer that supports compound operations like increment?
- synchronized int
- ThreadSafeInteger
- AtomicInteger (Correct answer)
- volatile int
Correct answer: AtomicInteger
`AtomicInteger` in `java.util.concurrent.atomic` provides atomic compound operations like `incrementAndGet()` without explicit synchronization.
Question 5: In Java, which method pair is used for inter-thread communication?
- send() and receive()
- notify() and wait() (Correct answer)
- signal() and pause()
- resume() and suspend()
Correct answer: notify() and wait()
`wait()` and `notify()` (with `notifyAll()`) on an `Object` are used for coordinating thread communication through a shared monitor.
Question 6: What is the role of the `Executor` framework in Java concurrency?
- To create threads using the Thread class
- To manage and reuse thread pools, decoupling task submission from execution (Correct answer)
- To replace synchronized blocks
- To schedule threads at fixed intervals only
Correct answer: To manage and reuse thread pools, decoupling task submission from execution
The `Executor` framework (in `java.util.concurrent`) manages thread pools, allowing efficient task submission without manual thread lifecycle management.
What does the `volatile` keyword guarantee for a variable in Java?