Skip to content

Instantly share code, notes, and snippets.

@itang
Last active September 10, 2015 06:15
Show Gist options
  • Save itang/46c62749bcfaadf82e2c to your computer and use it in GitHub Desktop.
Save itang/46c62749bcfaadf82e2c to your computer and use it in GitHub Desktop.
Parallel Stream
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
time(() -> {
List<String> strs = Arrays.asList("hello", "world", "google");
int sum = strs.parallelStream().map(x -> {
try {
TimeUnit.SECONDS.sleep(x.length());
// Thread.sleep(TimeUnit.SECONDS.toMillis(x.length()));
} catch (Exception e) {
e.printStackTrace();
}
return x;
}).collect(Collectors.summingInt(x -> x.length()));
System.out.println("ret: " + sum);
});
}
private static void time(Runnable r) {
long start = System.currentTimeMillis();
r.run();
System.out.println("cost time:" + (System.currentTimeMillis() - start));
}
}
/* output
ret: 16
cost time:6009
*/
import concurrent.duration._
import concurrent.Future
import concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
object Main extends App {
val strs = List("hello", "world", "google")
val ret1 = time {
parCollVersion()
}
println(s"par collection ret: $ret1")
val ret2 = time {
futureVersion()
}
println(s"future ret: $ret2")
def parCollVersion(): Integer =
strs.par.map { x =>
val len = x.length
Thread.sleep(len.second.toMillis)
len
}.sum
def futureVersion(): Integer =
strs.map { x =>
Future {
val len = x.length
Thread.sleep(len.second.toMillis)
len
}
}.map { x =>
Await.result(x, 50.second)
}.sum
def time[T](block: => T): T = {
val start = System.currentTimeMillis()
val t = block
println(s"cost time:${(System.currentTimeMillis() - start)}")
t
}
}
/**
cost time:6033
par collection ret: 16
cost time:6003
future ret: 16
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment