Files
.circleci
.github
.mvn
abstract-document
abstract-factory
active-object
acyclic-visitor
adapter
aggregator-microservices
ambassador
api-gateway
arrange-act-assert
async-method-invocation
balking
bridge
builder
business-delegate
bytecode
caching
callback
etc
src
README.md
pom.xml
chain-of-responsibility
circuit-breaker
cloud-static-content-hosting
collection-pipeline
combinator
command
commander
composite
composite-entity
converter
cqrs
dao
data-bus
data-locality
data-mapper
data-transfer-object
decorator
delegation
dependency-injection
dirty-flag
domain-model
double-buffer
double-checked-locking
double-dispatch
eip-aggregator
eip-message-channel
eip-publish-subscribe
eip-splitter
eip-wire-tap
etc
event-aggregator
event-asynchronous
event-driven-architecture
event-queue
event-sourcing
execute-around
extension-objects
facade
factory
factory-kit
factory-method
fanout-fanin
feature-toggle
filterer
fluentinterface
flux
flyweight
front-controller
game-loop
guarded-suspension
half-sync-half-async
hexagonal
intercepting-filter
interpreter
iterator
layers
lazy-loading
leader-election
leader-followers
localization
lockable-object
marker
master-worker-pattern
mediator
memento
model-view-controller
model-view-presenter
model-view-viewmodel
module
monad
monostate
multiton
mute-idiom
naked-objects
null-object
object-mother
object-pool
observer
page-object
parameter-object
partial-response
pipeline
poison-pill
presentation
priority-queue
private-class-data
producer-consumer
promise
property
prototype
proxy
queue-load-leveling
reactor
reader-writer-lock
registry
repository
resource-acquisition-is-initialization
retry
role-object
saga
separated-interface
servant
serverless
service-layer
service-locator
sharding
singleton
spatial-partition
special-case
specification
state
step-builder
strangler
strategy
subclass-sandbox
table-module
template-method
thread-pool
throttling
tls
tolerant-reader
trampoline
transaction-script
twin
typeobjectpattern
unit-of-work
update-method
value-object
version-number
visitor
.all-contributorsrc
.gitignore
CONTRIBUTING.MD
LICENSE.md
PULL_REQUEST_TEMPLATE.md
README.md
checkstyle-suppressions.xml
gpl-3.0.txt
lgpl-3.0.txt
license-plugin-header-style.xml
lombok.config
mvnw
mvnw.cmd
pom.xml
java-design-patterns/callback/README.md
JackieNim f597fc1b07 fix: Fixed pages showing up in wrong language ()
* Fix languages

* Missed change for version number

* Add language field for presentation

* Revert change in README for double buffer

Co-authored-by: Jackie Nim <=>
2021-05-19 19:49:05 +03:00

2.1 KiB

layout, title, folder, permalink, categories, language, tags
layout title folder permalink categories language tags
pattern Callback callback /patterns/callback/ Idiom en
Reactive

Intent

Callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time.

Explanation

Real world example

We need to be notified after executing task has finished. We pass a callback method for the executor and wait for it to call back on us.

In plain words

Callback is a method passed to the executor which will be called at defined moment.

Wikipedia says

In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time.

Programmatic Example

Callback is a simple interface with single method.

public interface Callback {

  void call();
}

Next we define a task that will execute the callback after the task execution has finished.

public abstract class Task {

  final void executeWith(Callback callback) {
    execute();
    Optional.ofNullable(callback).ifPresent(Callback::call);
  }

  public abstract void execute();
}

@Slf4j
public final class SimpleTask extends Task {

  @Override
  public void execute() {
    LOGGER.info("Perform some important activity and after call the callback method.");
  }
}

Finally, here's how we execute a task and receive a callback when it's finished.

    var task = new SimpleTask();
    task.executeWith(() -> LOGGER.info("I'm done now."));

Class diagram

alt text

Applicability

Use the Callback pattern when

  • when some arbitrary synchronous or asynchronous action must be performed after execution of some defined activity.

Real world examples

  • CyclicBarrier constructor can accept a callback that will be triggered every time a barrier is tripped.