Skip to content

Commit 2ee5789

Browse files
committed
iluwatar#590 explanation for Trampoline
1 parent d9ed8a5 commit 2ee5789

File tree

1 file changed

+111
-16
lines changed

1 file changed

+111
-16
lines changed

trampoline/README.md

Lines changed: 111 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,111 @@ tags:
99
---
1010

1111
## Intent
12-
Trampoline pattern is used for implementing algorithms recursively in Java without blowing the stack
13-
and to interleave the execution of functions without hard coding them together
14-
It is possible by representing a computation in one of 2 states : done | more
15-
(completed with result, or a reference to the reminder of the computation,
16-
something like the way a java.util.Supplier does).
12+
13+
Trampoline pattern is used for implementing algorithms recursively in Java without blowing the stack and to interleave
14+
the execution of functions without hard coding them together.
1715

1816
## Explanation
19-
Trampoline pattern allows to define recursive algorithms by iterative loop.
17+
18+
Recursion is a frequently adopted technique for solving algorithmic problems in a divide and conquer
19+
style. For example calculating fibonacci accumulating sum and factorials. In these kinds of problems recursion is
20+
more straightforward than their loop counterpart. Furthermore recursion may need less code and looks more concise.
21+
There is a saying that every recursion problem can be solved using a loop with the cost of writing code that is more
22+
difficult to understand.
23+
24+
However recursion type solutions have one big caveat. For each recursive call it typically needs an intermediate value
25+
stored and there is a limited amount of stack memory available. Running out of stack memory creates a stack overflow
26+
error and halts the program execution.
27+
28+
Trampoline pattern is a trick that allows us define recursive algorithms in Java without blowing the stack.
29+
30+
Real world example
31+
32+
> A recursive Fibonacci calculation without the stack overflow problem using the Trampoline pattern.
33+
34+
In plain words
35+
36+
> Trampoline pattern allows recursion without running out of stack memory.
37+
38+
Wikipedia says
39+
40+
> 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.
41+
42+
**Programmatic Example**
43+
44+
Here's the `Trampoline` implementation in Java.
45+
46+
When `get` is called on the returned Trampoline, internally it will iterate calling `jump` on the returned `Trampoline`
47+
as long as the concrete instance returned is `Trampoline`, stopping once the returned instance is `done`.
48+
49+
```java
50+
public interface Trampoline<T> {
51+
52+
T get();
53+
54+
default Trampoline<T> jump() {
55+
return this;
56+
}
57+
58+
default T result() {
59+
return get();
60+
}
61+
62+
default boolean complete() {
63+
return true;
64+
}
65+
66+
static <T> Trampoline<T> done(final T result) {
67+
return () -> result;
68+
}
69+
70+
static <T> Trampoline<T> more(final Trampoline<Trampoline<T>> trampoline) {
71+
return new Trampoline<T>() {
72+
@Override
73+
public boolean complete() {
74+
return false;
75+
}
76+
77+
@Override
78+
public Trampoline<T> jump() {
79+
return trampoline.result();
80+
}
81+
82+
@Override
83+
public T get() {
84+
return trampoline(this);
85+
}
86+
87+
T trampoline(final Trampoline<T> trampoline) {
88+
return Stream.iterate(trampoline, Trampoline::jump)
89+
.filter(Trampoline::complete)
90+
.findFirst()
91+
.map(Trampoline::result)
92+
.orElseThrow();
93+
}
94+
};
95+
}
96+
}
97+
```
98+
99+
Using the `Trampoline` to get Fibonacci values.
100+
101+
```java
102+
public static Trampoline<Integer> loop(int times, int prod) {
103+
if (times == 0) {
104+
return Trampoline.done(prod);
105+
} else {
106+
return Trampoline.more(() -> loop(times - 1, prod * times));
107+
}
108+
}
109+
110+
log.info("start pattern");
111+
var result = loop(10, 1).result();
112+
log.info("result {}", result);
113+
114+
// start pattern
115+
// result 3628800
116+
```
20117

21118
## Class diagram
22119
![alt text](./etc/trampoline.urm.png "Trampoline pattern class diagram")
@@ -27,18 +124,16 @@ Use the Trampoline pattern when
27124
* For implementing tail recursive function. This pattern allows to switch on a stackless operation.
28125
* For interleaving the execution of two or more functions on the same thread.
29126

30-
## Known uses(real world examples)
127+
## Known uses
31128

32-
* Trampoline refers to using reflection to avoid using inner classes, for example in event listeners.
33-
The time overhead of a reflection call is traded for the space overhead of an inner class.
34-
Trampolines in Java usually involve the creation of a GenericListener to pass events to an outer class.
129+
* [cyclops-react](https://github.com/aol/cyclops-react)
35130

36-
37-
## Tutorials
131+
## Credits
38132

39133
* [Trampolining: a practical guide for awesome Java Developers](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076)
40134
* [Trampoline in java ](http://mindprod.com/jgloss/trampoline.html)
41-
42-
## Credits
43-
44-
* [library 'cyclops-react' uses the pattern](https://github.com/aol/cyclops-react)
135+
* [Laziness, trampolines, monoids and other functional amenities: this is not your father's Java](https://www.slideshare.net/mariofusco/lazine)
136+
* [Trampoline implementation](https://github.com/bodar/totallylazy/blob/master/src/com/googlecode/totallylazy/Trampoline.java)
137+
* [What is a trampoline function?](https://stackoverflow.com/questions/189725/what-is-a-trampoline-function)
138+
* [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://www.amazon.com/gp/product/1617293563/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617293563&linkId=ad53ae6f9f7c0982e759c3527bd2595c)
139+
* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://www.amazon.com/gp/product/1617291994/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617291994&linkId=e3e5665b0732c59c9d884896ffe54f4f)

0 commit comments

Comments
 (0)