Command Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Command Pattern runs in O(1) time and O(n) space, in Java as in every other language.
- ✓Runnable and Callable are the two built-in command interfaces and the difference matters: Runnable.run returns nothing and cannot throw a checked exception, while Callable.call returns a value and may throw, which is why ExecutorService.submit takes either but only Callable can report a failure through the returned Future.
- ✓Prefer Callable to Runnable for anything that can fail, so the exception surfaces through Future.get rather than vanishing.
- ✓The Java trap: An exception thrown inside a task submitted with ExecutorService.submit is captured in the Future and NEVER surfaces unless someone calls get, so a fire-and-forget submit swallows every failure silently and the task simply appears not to have run.
- ✓A lambda command is linked once by invokedynamic and then dispatches as a plain virtual call the JIT can inline; a non-capturing one is allocated once and reused.
What Command Pattern actually is
Command Pattern in Java: what you actually reach for
Java implementation
import java.util.*;
import java.util.concurrent.*;
interface Command {
void execute() throws Exception; // Callable-like: failures are NOT swallowed
void undo();
}
class SetValue implements Command {
private final Map<String, Integer> store;
private final String key; private final int value;
private Integer prev; private boolean ran;
SetValue(Map<String, Integer> store, String key, int value) {
this.store = store; this.key = key; this.value = value;
}
public void execute() { prev = store.put(key, value); ran = true; }
public void undo() {
if (!ran) throw new IllegalStateException("undo before execute");
if (prev == null) store.remove(key); else store.put(key, prev);
}
}
class Invoker {
private final Deque<Command> history = new ArrayDeque<>(); // not the legacy Stack
void run(Command c) throws Exception { c.execute(); history.push(c); }
void undoLast() { if (!history.isEmpty()) history.pop().undo(); }
}
// submit() SWALLOWS the exception into the Future; execute() reports it.
class Demo {
static void run(ExecutorService pool, Runnable r) {
pool.execute(r); // uncaught handler sees failures
// pool.submit(r); // silent unless someone calls Future.get()
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Command Pattern?
Runnable and Callable are the two built-in command interfaces and the difference matters: Runnable.run returns nothing and cannot throw a checked exception, while Callable.call returns a value and may throw, which is why ExecutorService.submit takes either but only Callable can report a failure through the returned Future. Deque is the undo stack. CompletableFuture composes asynchronous commands, and java.util.concurrent.BlockingQueue is the classic command queue between producer and worker threads.
What is the most common Java mistake when implementing Command Pattern?
An exception thrown inside a task submitted with ExecutorService.submit is captured in the Future and NEVER surfaces unless someone calls get, so a fire-and-forget submit swallows every failure silently and the task simply appears not to have run. Using execute instead routes it to the thread uncaught-exception handler, which at least logs it. The related trap is that a task submitted to a fixed pool whose queue is unbounded will grow that queue until the heap is exhausted, because the pool never rejects; a bounded queue plus a rejection policy is what makes back-pressure real.
How does Command Pattern actually perform in Java?
A lambda command is linked once by invokedynamic and then dispatches as a plain virtual call the JIT can inline; a non-capturing one is allocated once and reused. The cost that dominates is scheduling: submitting to an executor involves a queue operation and potentially a thread wake-up, which is a microsecond-scale cost per command and far larger than executing a trivial command inline. Batch small commands rather than submitting each one. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.