Explain Runnable vs Callable and thread-safe Singleton
AppleSoftware Engineer · Technical ScreenLast updated
This question tests the conceptual differences between Java concurrency interfaces and the practical implementation of thread-safe creational design patterns.
Part 1: Runnable vs. Callable
In Java, both Runnable and Callable are functional interfaces used to define tasks for concurrent execution. Compare and contrast them based on the following criteria:
- Return values (how does each handle results?)
- Exception handling (what happens if the task throws a checked exception?)
- Method signatures (
run()vscall())
Part 2: Thread-Safe Singleton
Consider a scenario where you must implement a Singleton class that manages a shared resource.
public class ResourceManager {
// Implementation needed
}
- Write a thread-safe implementation of the
ResourceManagerusing the "Double-Checked Locking" pattern. - Explain why the
volatilekeyword is critical in this specific implementation. What specific problem does it solve regarding the Java Memory Model and instruction reordering? - Describe an alternative, simpler way to implement a thread-safe Singleton in Java that avoids explicit synchronization or locking.
Hints
Hint 1
Consider that Runnable's method returns void, whereas Callable allows for a generic return type.
Hint 2
For the Singleton pattern, remember that the goal is to prevent multiple threads from initializing the instance simultaneously.
Hint 3
The volatile keyword prevents the compiler and CPU from reordering the memory write that initializes the object and the reference assignment.
Follow-up questions
- How does the use of an ExecutorService impact your choice between Runnable and Callable?
- What are the performance implications of the 'synchronized' keyword on the getInstance() method compared to the double-checked locking approach?
- Can you explain how Enum-based singletons solve the thread-safety and serialization issues automatically?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.