Quick revision
The short answer
The command pattern wraps a request as an object, so it can be passed around, queued, logged, retried or undone instead of being executed immediately as a method call. Runnable and Callable are the everyday Java commands, handed to executors to run later. For undo, each command has an execute method and either stores what it needs to reverse its effect or knows its inverse command, and an undo stack keeps executed commands so that undo calls them in reverse order; writing commands as records makes the request data explicit and easy to serialise.
What to remember
In this answer, we saw that the command pattern turns a request into an object, so it can be queued, logged, retried or undone. Runnable and Callable are the commands we give to executors every day. For undo, each command stores what it needs to reverse itself or has an inverse, and an undo stack reverses commands in the opposite order of execution, with a redo stack cleared by new commands. Records make command data explicit, immutable and easy to serialise.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The command pattern wraps a request as an object, so it can be passed around, queued, logged, retried or undone instead of being executed immediately as a method call. Runnable and Callable are the everyday Java commands, handed to executors to run later. For undo, each command has an execute method and either stores what it needs to reverse its effect or knows its inverse command, and an undo stack keeps executed commands so that undo calls them in reverse order; writing commands as records makes the request data explicit and easy to serialise.
Why this question is asked
Most code calls methods directly: we want something done, so we do it now. The command pattern asks a different question: what if the request itself were a thing we could hold? Once a request is an object, we can put it in a queue, store it in a database, send it to another thread, log it, try it again, or undo it. Interviewers ask about the command pattern because it is behind executors, job queues, editors with undo and event-sourced systems, and the undo part shows whether we can think about state changes precisely. In this answer, we will recap the idea, see Runnable and Callable as commands, build a text editor with undo and redo, and look at records as commands.
1A Quick Recap of the Command Pattern
The command pattern has a few roles. The command is an object that represents one request, such as insert this text at position 5, with a method to perform it, usually execute(). The receiver is the object that actually does the work, here the document. The invoker is whatever triggers commands, such as a button, a menu or a scheduler; it knows only the command interface, not what the command does. The client creates commands and hands them to the invoker.
The power comes from separating deciding what to do from doing it. The invoker can run the command now, later, on another thread, several times, or not at all, and it can keep a history of what it ran.
2Runnable and Callable: Commands We Already Use
Every time we submit work to an executor, we use the command pattern. A Runnable is a command with no result; a Callable<V> is one that returns a value and may throw a checked exception. The ExecutorService is the invoker: it stores the command in its queue and runs it on one of its threads when one is free. The code that submitted the command does not need to know which thread will run it or when.
Notice that sendReport is created on one line and run on another thread at another time. That separation, a request turned into a value, is the whole pattern. Scheduled executors add when to run, and Timer, CompletableFuture.runAsync and Spring's TaskExecutor are all invokers of the same kind of command.
3Adding Undo to Commands
To undo a command, we need to reverse its effect, and there are two ways. A command can store what it needs to reverse itself: a delete command remembers the text it deleted, so undo can put it back. Or it can produce an inverse command: the inverse of insert hello at 5 is delete 5 characters at 5. The first is simpler when the command knows the old state at the moment it runs; the second is natural when operations already come in pairs.
The invoker then keeps an undo stack of executed commands. Undo pops the most recent command and reverses it, so commands are undone in the reverse order of execution, which is essential: undoing an older command first would apply its reversal to a state it never saw.
| Action | Document | Undo stack (top first) | Redo stack |
|---|---|---|---|
run Insert(0, Hello world) | Hello world | Insert | empty |
run Delete(5, 6) | Hello | Delete, Insert | empty |
run Insert(5, !) | Hello! | Insert!, Delete, Insert | empty |
| undo | Hello | Delete, Insert | Insert! |
| undo | Hello world | Insert | Delete, Insert! |
| redo | Hello | Delete, Insert | Insert! |
Notice why Delete is a class and not a record: it must remember the removed text, which it only knows after it runs. Notice also that running a new command clears the redo stack. After undoing twice and typing something new, the old future no longer applies to the new document, so redoing it would be wrong.
4Commands as Records
Records fit commands well when the command is pure data plus behaviour that depends only on that data, like Insert above. The record's components make the request explicit: anyone reading Insert(int pos, String text) knows exactly what the command carries. Records are immutable, so a command cannot change after it has been queued or logged, and they have value-based equals and a readable toString, which helps in tests and logs.
That explicitness also makes commands easy to serialise. A command record can be written as JSON, stored in a database table or put on a message queue, and turned back into an object by a worker in another process. That is the basis of database-backed job queues, of command buses in CQRS systems, and of logs that let us replay what users did. With a sealed interface, a switch over the command types is checked by the compiler, so a handler cannot forget a type.
5Follow-up questions
What makes undo hard in real systems?
Side effects outside our control. An editor can undo an insert exactly, but a command that sent an email or charged a card cannot be reversed by restoring state. There we need a compensating command, such as a refund, which is a new action with its own effects, and some commands are simply marked as not undoable.
How is command different from strategy?
Both wrap behaviour in an object. A strategy is a way of doing something, chosen and used by its context, like a Comparator. A command is a specific request to do something, with its data, that can be stored and executed later. A Comparator has no meaning without the sort; a Deposit command is meaningful on its own.
Could undo be done with snapshots instead?
Yes, the memento pattern stores a copy of the state before each change and restores it on undo. It is simpler to write but costs memory proportional to the state for each step, so editors and drawing tools usually prefer commands that store only the small reverse information.
6Conclusion
In this answer, we saw that the command pattern turns a request into an object, so it can be queued, logged, retried or undone. Runnable and Callable are the commands we give to executors every day. For undo, each command stores what it needs to reverse itself or has an inverse, and an undo stack reverses commands in the opposite order of execution, with a redo stack cleared by new commands. Records make command data explicit, immutable and easy to serialise.
Open with
The command pattern wraps a request as an object. Instead of calling a method right away, I create an object that carries everything needed to perform the request and has an execute method.
Then, if they want more
Because it is an object, I can queue it, log it, send it to another thread, retry it, or undo it.
In Java, Runnable and Callable are the everyday commands: I create a task and submit it to an ExecutorService, which acts as the invoker and runs it later on a pool thread, and the caller does not care which thread or when. For undo, each command needs a way to reverse its effect.
Either it stores what it needs while executing, like a delete command remembering the text it removed, or it has an inverse command, like insert being reversed by a delete of the same length at the same position.
The invoker keeps an undo stack: after executing a command it pushes it, and undo pops the latest and reverses it, so commands are undone in reverse order, which matters because each reversal assumes the state right after that command. A redo stack works the other way, and it gets cleared when a new command runs.
I like modelling commands as records, maybe under a sealed interface, because the request data is explicit and immutable, the toString is readable in logs, and they serialise easily to JSON, which is what lets us store commands in a database or send them on a queue.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Explain the command pattern with Java examples, and describe how it supports undo.": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/14e5af4a8b/