Skip to content

Golang like concurrency in Java

aburkov edited this page Jun 27, 2015 · 1 revision

Concurrency in xpresso is inspired by Go and, as a consequence, is extremely simple. First, define a worker as an instance of Predicate:

Predicate<Channel<Integer>> worker = new Predicate<Channel<Integer>>() {
	public Boolean apply(Channel<Integer> channel) {
		while (some_condition_true) {
			Integer value = computeValue();	//compute something in parallel
			channel.send(value);			//send the computed value to the channel
		}
		return true;						//everything went as expected
	}
};

Then, define the channel to where the workers should send the computed values as soon as those values are ready:

Channel<Integer> channel = x.Channel(Integer.class);//this channel only accepts Integer values

Then, start as many concurrent workers as needed:

x.go(worker, channel);
x.go(worker, channel);
x.go(worker, channel);
...

Finally, retrieve from the channel the values concurrently computed by the workers when those values are needed:

for (Integer value : channel) {
	x.print(value);
}