2018-01-08 14:00:12 +03:00
---
layout: pattern
title: Trampoline
folder: trampoline
permalink: /patterns/trampoline/
2019-11-16 21:56:40 +02:00
categories: Behavioral
2018-01-08 14:00:12 +03:00
tags:
- Java
- Difficulty-Intermediate
- Performance
- Recursion
---
## Intent
2018-01-20 13:36:43 +03:00
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
It is possible by representing a computation in one of 2 states : done | more
2018-01-08 14:00:12 +03:00
(completed with result, or a reference to the reminder of the computation,
2018-01-20 13:36:43 +03:00
something like the way a java.util.Supplier does).
2018-01-08 14:00:12 +03:00
2018-01-20 13:36:43 +03:00
## Explanation
Trampoline pattern allows to define recursive algorithms by iterative loop.
2018-01-08 14:00:12 +03:00
## Applicability
Use the Trampoline pattern when
* For implementing tail recursive function. This pattern allows to switch on a stackless operation.
2018-01-08 14:45:38 +03:00
* For interleaving the execution of two or more functions on the same thread.
2018-01-08 14:00:12 +03:00
## Known uses(real world examples)
* 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.
2018-01-08 14:45:38 +03:00
2018-01-20 13:36:43 +03:00
## Tutorials
2018-01-08 14:00:12 +03:00
* [Trampolining: a practical guide for awesome Java Developers ](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076 )
* [Trampoline in java ](http://mindprod.com/jgloss/trampoline.html )
2018-01-20 13:36:43 +03:00
## Credits
* [library 'cyclops-react' uses the pattern ](https://github.com/aol/cyclops-react )
2018-01-08 14:00:12 +03:00