Katkat

Explain Runnable vs Callable and thread-safe Singleton

AppleSoftware Engineer · Technical Screen

Last 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:

  1. Return values (how does each handle results?)
  2. Exception handling (what happens if the task throws a checked exception?)
  3. Method signatures (run() vs call())

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
}
  1. Write a thread-safe implementation of the ResourceManager using the "Double-Checked Locking" pattern.
  2. Explain why the volatile keyword is critical in this specific implementation. What specific problem does it solve regarding the Java Memory Model and instruction reordering?
  3. 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?