* Changed database implementation. Removed static objects. * Fix Logs * Fix 40 errors from checkstyle plugin run. 139 left)) * Fix CacheStore errors from checkstyle plugin 107 left * Fix last errors in checkstyle. * Fix sonar issues * Fix issues in VALIDATE phase * Fix Bug with mongo connection. Used "Try with resources" * Add test * Added docker-compose for mongo db. MongoDb db work fixed. * Provided missing tests * Comments to start Application with mongo. * Fix some broken links * Remove extra space * Update filename * Fix some links in localization folders * Fix link * Update frontmatters * Work on patterns index page * Work on index page * Fixes according PR comments. Mainly Readme edits. * fix frontmatter * add missing png * Update pattern index.md * Add index.md for Chinese translation * update image paths * update circuit breaker image paths * Update image paths for localizations * add generated puml * Add missing image * Update img file extensions * Update the rest of the EN and ZH patterns to conform with the new website Co-authored-by: Victor Zalevskii <zvictormail@gmail.com>
title, category, language, tags
| title | category | language | tags | |
|---|---|---|---|---|
| Trampoline | Behavioral | en |
|
Intent
Trampoline pattern is used for implementing algorithms recursively in Java without blowing the stack and to interleave the execution of functions without hard coding them together.
Explanation
Recursion is a frequently adopted technique for solving algorithmic problems in a divide and conquer style. For example, calculating Fibonacci accumulating sum and factorials. In these kinds of problems, recursion is more straightforward than its loop counterpart. Furthermore, recursion may need less code and looks more concise. There is a saying that every recursion problem can be solved using a loop with the cost of writing code that is more difficult to understand.
However, recursion-type solutions have one big caveat. For each recursive call, it typically needs an intermediate value stored and there is a limited amount of stack memory available. Running out of stack memory creates a stack overflow error and halts the program execution.
Trampoline pattern is a trick that allows defining recursive algorithms in Java without blowing the stack.
Real-world example
A recursive Fibonacci calculation without the stack overflow problem using the Trampoline pattern.
In plain words
Trampoline pattern allows recursion without running out of stack memory.
Wikipedia says
In Java, trampoline refers to using reflection to avoid using inner classes, for example in event listeners. The time overhead of a reflection call is traded for the space overhead of an inner class. Trampolines in Java usually involve the creation of a GenericListener to pass events to an outer class.
Programmatic Example
Here's the Trampoline implementation in Java.
When get is called on the returned Trampoline, internally it will iterate calling jump on the
returned Trampoline as long as the concrete instance returned is Trampoline, stopping once the
returned instance is done.
public interface Trampoline<T> {
T get();
default Trampoline<T> jump() {
return this;
}
default T result() {
return get();
}
default boolean complete() {
return true;
}
static <T> Trampoline<T> done(final T result) {
return () -> result;
}
static <T> Trampoline<T> more(final Trampoline<Trampoline<T>> trampoline) {
return new Trampoline<T>() {
@Override
public boolean complete() {
return false;
}
@Override
public Trampoline<T> jump() {
return trampoline.result();
}
@Override
public T get() {
return trampoline(this);
}
T trampoline(final Trampoline<T> trampoline) {
return Stream.iterate(trampoline, Trampoline::jump)
.filter(Trampoline::complete)
.findFirst()
.map(Trampoline::result)
.orElseThrow();
}
};
}
}
Using the Trampoline to get Fibonacci values.
public static void main(String[] args) {
LOGGER.info("Start calculating war casualties");
var result = loop(10, 1).result();
LOGGER.info("The number of orcs perished in the war: {}", result);
}
public static Trampoline<Integer> loop(int times, int prod) {
if (times == 0) {
return Trampoline.done(prod);
} else {
return Trampoline.more(() -> loop(times - 1, prod * times));
}
}
Program output:
19:22:24.462 [main] INFO com.iluwatar.trampoline.TrampolineApp - Start calculating war casualties
19:22:24.472 [main] INFO com.iluwatar.trampoline.TrampolineApp - The number of orcs perished in the war: 3628800
Class diagram
Applicability
Use the Trampoline pattern when
- For implementing tail-recursive functions. This pattern allows to switch on a stackless operation.
- For interleaving execution of two or more functions on the same thread.
Known uses
Credits
- Trampolining: a practical guide for awesome Java Developers
- Trampoline in java
- Laziness, trampolines, monoids and other functional amenities: this is not your father's Java
- Trampoline implementation
- What is a trampoline function?
- Modern Java in Action: Lambdas, streams, functional and reactive programming
- Java 8 in Action: Lambdas, Streams, and functional-style programming
