Member-only story
Java: How command pattern is used in popular libraries
Real-World Library Implementations
Published in
3 min readJan 28, 2025
Many well-known Java libraries and frameworks use the Command Pattern internally to facilitate the construction of complex objects. Below are five commonly cited examples in the standard Java libraries that illustrate the Command Pattern (encapsulating an action — or “command” — as an object).
1) Executor.execute(Runnable command)
(Concurrency Framework)
Where it appears
- Package:
java.util.concurrent
- Key Interfaces/Classes:
Executor
,Runnable
How it demonstrates the Command pattern
- The
Runnable
interface represents a command—its singlerun()
method captures the action to be performed. - By passing a
Runnable
to anExecutor
(e.g., aThreadPoolExecutor
), you are scheduling or queuing the execution of that command. - The
execute(Runnable command)
method tells the executor to “run this command object at some point.”
Executor executor = Executors.newSingleThreadExecutor();
Runnable command = () -> System.out.println("Hello from a command!");
executor.execute(command); // Schedules the command's execution