Reactive programming with Java 8 and simple-react : pooling reactors

John McClean
1 min readMar 24, 2015

--

Creating an ExecutorService in Java is expensive, and the garbage collector often refuses to collect them, even when all references have been removed.

You can use ReactPool to pool instances of simple-react builders (reactors).

List<String> files = Arrays.asList(“/tmp/1.data”,”/tmp/2.data”);List<Status> data = SequentialElasticPools.lazyReact
.react(er -> er.reactToCollection(files)
.map(this::loadData)
.peek(System.out::println)
.map(this::saveData)
.collect(Collectors.toList()));

System.out.println(“Loaded and saved “ + data.size());

If you need to do heavy processing on a per user request basis passing a reactive function into a ReactPool and letting it handle the request is a potential solution.

Function<EagerReact,List<Status>> 
fn = er -> er.reactToCollection(data)
.map(this::loadData)
.map(this::processData)
.map(this::saveData)
.allOf(data ->
asyncResponse.respond(data));
ParallelElasticPools.eagerReact.react(fn);

In this case the user data is handed asynchronously to the ReactPool for processing. If no REACTOR is available a new one is created — but if one exists in the pool already that is free, it is reused.

bounded pools

simple-react also provides a pooling mechanism where by you can limit the number of Reactors in active operation at one time. You can do this with a bounded pool.

To create a bounded pool pass in a collection of Reactors

EagerReact react1 = new EagerReact(new ForkJoinPool(4));
EagerReact react2 = new EagerReact(new ForkJoinPool(4));
ReactPool<EagerReact> pool = ReactPool.boundedPool
(Arrays.asList(react1,react2));

Note that we are giving each Reactor it’s own ForkJoinPool to keep execution completely separate. If Reactors where to share a ForkJoinPool, then using a ReactPool would be equivalent to sharing a single Reactor.

To make use of the bounded pool, try

pool.react( (er) -> er.react(()->”hello”,()->”world”));

The Tutorial : Reactive programming with Java 8

--

--

John McClean

Architecture @ Verizon Media. Maintainer of Cyclops. Twitter @johnmcclean_ie