Skip to content

Instantly share code, notes, and snippets.

@jmora
Last active August 29, 2015 14:14
Show Gist options
  • Save jmora/68c5e6691d1a41620514 to your computer and use it in GitHub Desktop.
Save jmora/68c5e6691d1a41620514 to your computer and use it in GitHub Desktop.
An example of the modifications needed to parallelize something (using futures) in Java and Scala (check the diff).
package tests.javafuture;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Operations {
private final int cores = Runtime.getRuntime().availableProcessors();
private final ExecutorService pool = Executors.newFixedThreadPool(this.cores);
public int operations (int number) {
Future<Integer> futureNumber = this.pool.submit(new Operation1Runner(number));
int number1 = 1;
int number2 = this.operation2(number);
try {
number1 = futureNumber.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return number1 * number2;
}
private int operation1 (int number) {
return 1 + number;
}
private int operation2 (int number) {
return 2 + number;
}
private class Operation1Runner implements Callable<Integer> {
private int number;
public Operation1Runner(int number) {
this.number = number;
}
@Override
public Integer call () throws Exception {
return ParallelOperations.this.operation1(this.number);
}
}
}
package test.scalafuture
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration._
class Operations {
def operations(number: Int): Int = {
val op1 = future { operation1(number) }
operation2(number) * Await.result(op1, Inf)
}
private def operation1(number: Int): Int = number + 1
private def operation2(number: Int): Int = number + 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment