Last active
September 10, 2015 06:15
-
-
Save itang/46c62749bcfaadf82e2c to your computer and use it in GitHub Desktop.
Parallel Stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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