Runnable versus Callable and a thread-safe singleton
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Jan 2026. It tests java, concurrency and design patterns.
Two Java concurrency questions. First compare Runnable and Callable. Then write a singleton that stays correct when several threads ask for it at the same moment, and explain why it is safe.
Part 1: Runnable versus Callable
Explain:
- What each interface's method returns and whether it can throw checked exceptions.
- How each is submitted to an
ExecutorService, and how you get a result or an exception back through aFuture. - When you would pick one over the other.
Part 2: the singleton
Unless you agree on a different interface with the interviewer, assume:
-
Config.getInstance(): returns the oneConfigobject, creating it on first use. Creation is expensive, so it should happen once and only when needed.
Write it, then compare the alternatives: eager initialization, a synchronized method, double-checked locking, the holder-class idiom and an enum.
What a strong answer covers
-
Runnable.run()returns nothing and can't throw checked exceptions;Callable.call()returns a value and can.Future.get()wraps a task's exception inExecutionException. - Why the naive lazy singleton creates two instances under a race.
- Double-checked locking needs a
volatilefield, and why: without it another thread can see a reference to a partly constructed object. - The holder class gives lazy, thread-safe creation without locks because class initialization is guaranteed to happen once.
- The
enumsingleton and how it also resists serialization and reflection.
Follow-ups
- How would you test that
getInstance()creates exactly one object under contention? - The singleton holds state that changes. What new problems appear?
- Why are singletons often discouraged, and what would you use instead (dependency injection)?
Where it's asked
- Apple · Technical phone screen · Last asked Jan 2026
What it tests
java · concurrency · design patterns
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
