SlideShare a Scribd company logo
JDK 7 출시 기념 (2011.7)JDK 7 소개 #4 ConcurrentyFork & Join (jsr166y)김용환knight76.tistory.comKnight76 at gmail.com1
Fork          &         Join2
Multicore-friendly lightweight parallel frameworkJSR166y (maintenance)목적놀고 있는 여러 개의 processor를 최대한 활용을 위해서 디자인됨병렬처리 필요MapReduce와 비슷하지만, 더 세분화할 수 있다. Work-stealing 알고리즘을 기반.3
Fork/JoinForkRecursively큰 단위의 작업을 작은 단위로 쪼갬Join결과를 Recursive하게모음Doug Lee(뉴욕 주립대 교수)http://gee.cs.oswego.edu/dl/papers/fj.pdfhttp://g.oswego.edu/dl/concurrency-interest/4
Map Reduce와 비교Map ReduceNode 기반의 Cluster 기반Single forkFork / Join하나의장비안에서 여러 개의 CPU를 사용하려는 하나의 JVMRecursive forkWork Stealing5
Work StealingCilk에서개념을 채용 (논문)MIT에서 만든 멀티쓰레드 프로그래밍 언어예약어 조금 + C언어(http://supertech.csail.mit.edu/cilk/manual-5.4.6.pdf)특징각 worker 는 DeQueue(double-ended queue)를 가지고 있음  worker가 idle일 때, 바쁜 Worker의 Queue에 쌓인 task 를 steal.왜?여러 개의 processor(core)에서 동작 가능로드 밸런스 (작은 task로 나눌 수 있도록 함)6
Work Stealing7ForkJoinPool클래스에구현되어 있음출처 : http://karlsenchoi.blogspot.com/2011/02/threadpool-work-stealing.html
jsr166y추가된 APIhttp://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/8
Pseudo code9if (my portion of the work is small enough)dothe work directlyelsesplit my work into two piecesinvokethe two pieces and wait for the results
Java pseudo code 10class OOOTaskextends RecursiveTask {    @Override    public void compute() {// small enough        if (problem.size< THRESHOLD) {              // do directlyproblem.solve();                 } else {// split            Task worker1 = new OOOTask(new Problem(problem.size - 1));            Task worker2 = new OOOTask(new Problem(problem.size- 2));// invokeinvokeAll(worker1, worker2);        }    }}
예제피보나치 계산Fib(7) 계산CPU는 411
FibonacciProblem12class FibonacciProblem {public int n;	public FibonacciProblem(int n) {this.n = n;	}	public long solve() {		return fibonacci(n);	}	private long fibonacci(int n) {System.out.println("Thread: " + Thread.currentThread().getName()				+ " calculates " + n);		if (n <= 1) {			return n;} else {return fibonacci(n - 1) + fibonacci(n - 2);                         }	}}
FibonacciTask13@SuppressWarnings("serial")class FibonacciTask extends RecursiveTask<Long> {	private static final intTHRESHOLD = 5;	private FibonacciProblem problem;	public long result;	public FibonacciTask(FibonacciProblem problem) {this.problem = problem;	}	@Override	public Long compute() {		if (problem.n < THRESHOLD) {			result = problem.solve();		} else {FibonacciTask worker1 = new FibonacciTask(                                                           new FibonacciProblem(problem.n - 1));FibonacciTask worker2 = new FibonacciTask(                                                           new FibonacciProblem(problem.n - 2));worker1.fork();			result = worker2.compute() + worker1.join();		}		return result;	}}
Main14public static void main(String[] args) throws Exception {System.out.println("Number of processors: " + Runtime.getRuntime().availableProcessors());intn = 7;StopWatchstopWatch = new StopWatch();   FibonacciProblembigProblem = new FibonacciProblem(n);FibonacciTasktask = new FibonacciTask(bigProblem);ForkJoinPool pool = new ForkJoinPool();pool.invoke(task);long result = task.result;System.out.println("Computed Result: " + result);stopWatch.stop();System.out.println("Elapsed Time: " + stopWatch.getTotalTimeMillis());System.out.println("Steal Count : " + pool.getStealCount());}
실행 결과15No of processors: 4Thread: ForkJoinPool-1-worker-1 calculates 3Thread: ForkJoinPool-1-worker-2 calculates 4Thread: ForkJoinPool-1-worker-3 calculates 4Thread: ForkJoinPool-1-worker-3 calculates 3Thread: ForkJoinPool-1-worker-3 calculates 2Thread: ForkJoinPool-1-worker-3 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 3Thread: ForkJoinPool-1-worker-4 calculates 2Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 3Thread: ForkJoinPool-1-worker-2 calculates 2Thread: ForkJoinPool-1-worker-1 calculates 2Thread: ForkJoinPool-1-worker-1 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 0Thread: ForkJoinPool-1-worker-3 calculates 0Thread: ForkJoinPool-1-worker-3 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 0Thread: ForkJoinPool-1-worker-1 calculates 0Thread: ForkJoinPool-1-worker-2 calculates 1Thread: ForkJoinPool-1-worker-3 calculates 2Thread: ForkJoinPool-1-worker-2 calculates 2Thread: ForkJoinPool-1-worker-1 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 1Thread: ForkJoinPool-1-worker-3 calculates 1Thread: ForkJoinPool-1-worker-3 calculates 0Thread: ForkJoinPool-1-worker-2 calculates 0Thread: ForkJoinPool-1-worker-4 calculates 4Thread: ForkJoinPool-1-worker-4 calculates 3Thread: ForkJoinPool-1-worker-4 calculates 2Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 0Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 2Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 0Computed Result: 13Elapsed Time: 4Steal Count : 4
RecursiveTask & RecursiveAction16FutureForkJoinTaskRecursiveTaskRecursiveAction
API (RecursiveAction)17public abstract class RecursiveAction<V> extends ForkJoinTask<V> {    private static final long serialVersionUID = 5232453952276485270L;    protected abstract V compute();    public final void getRawResult() {        return null;    }    protected final void setRawResult(V value) {    }    protected final boolean exec() {        compute();        return true;    }}
API (RecursiveTask)18public abstract class RecursiveTaskextends ForkJoinTask<Void> {    private static final long serialVersionUID = 5232453952276485270L;    V result;    protected abstract V compute();    public final V getRawResult() {        return result;    }    protected final void setRawResult(V value) {        result = value;    }    protected final boolean exec() {        result = compute();        return true;    }}
API (ForkJoinTask)19
API (ForkJoinPool)20ExecutorExecutorServiceAbstractExecutorServiceForkJoinPool
ForkJoinPool21
기타22
ThreadLocalRandom멀티쓰레드상에서Random 은 contention과 overhead가 존재. Random 내부에서 thread를 isolation을 함ForkJoinPool에서 Random 사용시 이슈가 속도가 저하되기 때문에 이를 해결할 수 있는 클래스23long f = ThreadLocalRandom.current().nextLong();System.out.println("1 : " + f);f = ThreadLocalRandom.current().nextLong();System.out.println("2 : " + f);1 : 42322372 : 767956431209526212
Phaser특징쓰레드를 동시 시작/종료시킬 수 있도록 함CyclicBarrier와 CountDownLatch클래스를 보다 유연함좋은 자료http://download.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.htmlhttp://olegignatenko.livejournal.com/16771.html24
Phaser예제25public static void main(String[] args) {runDevelopment(Arrays.asList(new Developer(), new Developer(),                             new Developer(), new Developer()));}private static void runDevelopment(Iterable<Developer> team) {        final Phasermanager = new Phaser(1); //"1" to register selfSystem.out.println("mgr: assign all developers, then start coding");        for (final Developer developer : team) {            final String dev = developer.toString();System.out.println("mgr: assigns a new unarrived " + dev + " to the project");manager.register();            new Thread() {                public void run() {System.out.println("mgr: " + dev + ", please await all developers");manager.arriveAndAwaitAdvance(); // await all creationSystem.out.println("mgr: " + dev + ", OK to start coding");developer.run();}            }.start();}System.out.println("mgr: all assigned, start coding after all arrive");manager.arriveAndDeregister();}class Developer implements Runnable {    private final static AtomicIntegeridSource = new AtomicInteger();    private final int id = idSource.incrementAndGet();    public void run() { System.out.println(toString() + ": coding"); }    public String toString() { return "developer #" + id; }}
Phaser결과26mgr: assign all developers, then start codingmgr: assigns a new unarrived developer #1 to the projectmgr: assigns a new unarrived developer #2 to the projectmgr: developer #1, please await all developersmgr: assigns a new unarrived developer #3 to the projectmgr: assigns a new unarrived developer #4 to the projectmgr: developer #3, please await all developersmgr: all assigned, start coding after all arrivemgr: developer #4, please await all developersmgr: developer #2, please await all developersmgr: developer #2, OK to start codingdeveloper #2: codingmgr: developer #1, OK to start codingdeveloper #1: codingmgr: developer #3, OK to start codingdeveloper #3: codingmgr: developer #4, OK to start codingdeveloper #4: coding
To be continued #527
Ad

More Related Content

What's hot (20)

Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
Rafael Winterhalter
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
julien.ponge
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 
JVM
JVMJVM
JVM
Murali Pachiyappan
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
Anton Arhipov
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java Agents
Anton Arhipov
 
Server1
Server1Server1
Server1
FahriIrawan3
 
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
ikikko
 
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
Danny Preussler
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
Andrei Pangin
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
DoHyun Jung
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011
Anton Arhipov
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
Rafael Winterhalter
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
Anton Arhipov
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With Javassist
Anton Arhipov
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
Anton Arhipov
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java Agents
Anton Arhipov
 
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
ikikko
 
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
Danny Preussler
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
Andrei Pangin
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
DoHyun Jung
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011
Anton Arhipov
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
Rafael Winterhalter
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
Anton Arhipov
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With Javassist
Anton Arhipov
 

Viewers also liked (14)

Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
Henri Tremblay
 
구글크롬Os
구글크롬Os구글크롬Os
구글크롬Os
knight1128
 
하이브리드앱
하이브리드앱하이브리드앱
하이브리드앱
knight1128
 
Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
knight1128
 
2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법
2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법
2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법
Hancom Haansoft
 
Jdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamicJdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamic
knight1128
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
knight1128
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
knight1128
 
데이터 바인딩 ( Binding )
데이터 바인딩 ( Binding )데이터 바인딩 ( Binding )
데이터 바인딩 ( Binding )
대열 김
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
Henri Tremblay
 
구글크롬Os
구글크롬Os구글크롬Os
구글크롬Os
knight1128
 
하이브리드앱
하이브리드앱하이브리드앱
하이브리드앱
knight1128
 
Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
knight1128
 
2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법
2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법
2014년 3월호_미니 이그나이트 한컴 - 망하는 세가지 방법
Hancom Haansoft
 
Jdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamicJdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamic
knight1128
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
knight1128
 
데이터 바인딩 ( Binding )
데이터 바인딩 ( Binding )데이터 바인딩 ( Binding )
데이터 바인딩 ( Binding )
대열 김
 
Ad

Similar to Jdk 7 4-forkjoin (20)

JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
Dustin Graham
 
Global Interpreter Lock: Episode I - Break the Seal
Global Interpreter Lock: Episode I - Break the SealGlobal Interpreter Lock: Episode I - Break the Seal
Global Interpreter Lock: Episode I - Break the Seal
Tzung-Bi Shih
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
Roger Xia
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
Thierry Wasylczenko
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
Minh Tran
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Appsterdam Milan
 
Os lab final
Os lab finalOs lab final
Os lab final
LakshmiSarvani6
 
Microkernel Development
Microkernel DevelopmentMicrokernel Development
Microkernel Development
Rodrigo Almeida
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
Alexey Fyodorov
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
HongAnhNguyn285885
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
Adil Jafri
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
Shalabh Chaudhary
 
Tools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in AndroidTools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in Android
Intel® Software
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Global Interpreter Lock: Episode I - Break the Seal
Global Interpreter Lock: Episode I - Break the SealGlobal Interpreter Lock: Episode I - Break the Seal
Global Interpreter Lock: Episode I - Break the Seal
Tzung-Bi Shih
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
Roger Xia
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
Minh Tran
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
Alexey Fyodorov
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
Adil Jafri
 
Tools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in AndroidTools and Techniques for Understanding Threading Behavior in Android
Tools and Techniques for Understanding Threading Behavior in Android
Intel® Software
 
Ad

More from knight1128 (7)

Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
knight1128
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin
knight1128
 
공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction
knight1128
 
아마존 Aws 서비스_연구
아마존 Aws 서비스_연구아마존 Aws 서비스_연구
아마존 Aws 서비스_연구
knight1128
 
속도체크
속도체크속도체크
속도체크
knight1128
 
오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유
knight1128
 
Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상
knight1128
 
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
knight1128
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin
knight1128
 
공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction
knight1128
 
아마존 Aws 서비스_연구
아마존 Aws 서비스_연구아마존 Aws 서비스_연구
아마존 Aws 서비스_연구
knight1128
 
오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유
knight1128
 
Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상
knight1128
 

Recently uploaded (20)

Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 

Jdk 7 4-forkjoin

  • 1. JDK 7 출시 기념 (2011.7)JDK 7 소개 #4 ConcurrentyFork & Join (jsr166y)김용환knight76.tistory.comKnight76 at gmail.com1
  • 2. Fork & Join2
  • 3. Multicore-friendly lightweight parallel frameworkJSR166y (maintenance)목적놀고 있는 여러 개의 processor를 최대한 활용을 위해서 디자인됨병렬처리 필요MapReduce와 비슷하지만, 더 세분화할 수 있다. Work-stealing 알고리즘을 기반.3
  • 4. Fork/JoinForkRecursively큰 단위의 작업을 작은 단위로 쪼갬Join결과를 Recursive하게모음Doug Lee(뉴욕 주립대 교수)http://gee.cs.oswego.edu/dl/papers/fj.pdfhttp://g.oswego.edu/dl/concurrency-interest/4
  • 5. Map Reduce와 비교Map ReduceNode 기반의 Cluster 기반Single forkFork / Join하나의장비안에서 여러 개의 CPU를 사용하려는 하나의 JVMRecursive forkWork Stealing5
  • 6. Work StealingCilk에서개념을 채용 (논문)MIT에서 만든 멀티쓰레드 프로그래밍 언어예약어 조금 + C언어(http://supertech.csail.mit.edu/cilk/manual-5.4.6.pdf)특징각 worker 는 DeQueue(double-ended queue)를 가지고 있음 worker가 idle일 때, 바쁜 Worker의 Queue에 쌓인 task 를 steal.왜?여러 개의 processor(core)에서 동작 가능로드 밸런스 (작은 task로 나눌 수 있도록 함)6
  • 7. Work Stealing7ForkJoinPool클래스에구현되어 있음출처 : http://karlsenchoi.blogspot.com/2011/02/threadpool-work-stealing.html
  • 9. Pseudo code9if (my portion of the work is small enough)dothe work directlyelsesplit my work into two piecesinvokethe two pieces and wait for the results
  • 10. Java pseudo code 10class OOOTaskextends RecursiveTask { @Override public void compute() {// small enough if (problem.size< THRESHOLD) { // do directlyproblem.solve(); } else {// split Task worker1 = new OOOTask(new Problem(problem.size - 1)); Task worker2 = new OOOTask(new Problem(problem.size- 2));// invokeinvokeAll(worker1, worker2); } }}
  • 12. FibonacciProblem12class FibonacciProblem {public int n; public FibonacciProblem(int n) {this.n = n; } public long solve() { return fibonacci(n); } private long fibonacci(int n) {System.out.println("Thread: " + Thread.currentThread().getName() + " calculates " + n); if (n <= 1) { return n;} else {return fibonacci(n - 1) + fibonacci(n - 2); } }}
  • 13. FibonacciTask13@SuppressWarnings("serial")class FibonacciTask extends RecursiveTask<Long> { private static final intTHRESHOLD = 5; private FibonacciProblem problem; public long result; public FibonacciTask(FibonacciProblem problem) {this.problem = problem; } @Override public Long compute() { if (problem.n < THRESHOLD) { result = problem.solve(); } else {FibonacciTask worker1 = new FibonacciTask( new FibonacciProblem(problem.n - 1));FibonacciTask worker2 = new FibonacciTask( new FibonacciProblem(problem.n - 2));worker1.fork(); result = worker2.compute() + worker1.join(); } return result; }}
  • 14. Main14public static void main(String[] args) throws Exception {System.out.println("Number of processors: " + Runtime.getRuntime().availableProcessors());intn = 7;StopWatchstopWatch = new StopWatch(); FibonacciProblembigProblem = new FibonacciProblem(n);FibonacciTasktask = new FibonacciTask(bigProblem);ForkJoinPool pool = new ForkJoinPool();pool.invoke(task);long result = task.result;System.out.println("Computed Result: " + result);stopWatch.stop();System.out.println("Elapsed Time: " + stopWatch.getTotalTimeMillis());System.out.println("Steal Count : " + pool.getStealCount());}
  • 15. 실행 결과15No of processors: 4Thread: ForkJoinPool-1-worker-1 calculates 3Thread: ForkJoinPool-1-worker-2 calculates 4Thread: ForkJoinPool-1-worker-3 calculates 4Thread: ForkJoinPool-1-worker-3 calculates 3Thread: ForkJoinPool-1-worker-3 calculates 2Thread: ForkJoinPool-1-worker-3 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 3Thread: ForkJoinPool-1-worker-4 calculates 2Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 3Thread: ForkJoinPool-1-worker-2 calculates 2Thread: ForkJoinPool-1-worker-1 calculates 2Thread: ForkJoinPool-1-worker-1 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 0Thread: ForkJoinPool-1-worker-3 calculates 0Thread: ForkJoinPool-1-worker-3 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 0Thread: ForkJoinPool-1-worker-1 calculates 0Thread: ForkJoinPool-1-worker-2 calculates 1Thread: ForkJoinPool-1-worker-3 calculates 2Thread: ForkJoinPool-1-worker-2 calculates 2Thread: ForkJoinPool-1-worker-1 calculates 1Thread: ForkJoinPool-1-worker-2 calculates 1Thread: ForkJoinPool-1-worker-3 calculates 1Thread: ForkJoinPool-1-worker-3 calculates 0Thread: ForkJoinPool-1-worker-2 calculates 0Thread: ForkJoinPool-1-worker-4 calculates 4Thread: ForkJoinPool-1-worker-4 calculates 3Thread: ForkJoinPool-1-worker-4 calculates 2Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 0Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 2Thread: ForkJoinPool-1-worker-4 calculates 1Thread: ForkJoinPool-1-worker-4 calculates 0Computed Result: 13Elapsed Time: 4Steal Count : 4
  • 17. API (RecursiveAction)17public abstract class RecursiveAction<V> extends ForkJoinTask<V> { private static final long serialVersionUID = 5232453952276485270L; protected abstract V compute(); public final void getRawResult() { return null; } protected final void setRawResult(V value) { } protected final boolean exec() { compute(); return true; }}
  • 18. API (RecursiveTask)18public abstract class RecursiveTaskextends ForkJoinTask<Void> { private static final long serialVersionUID = 5232453952276485270L; V result; protected abstract V compute(); public final V getRawResult() { return result; } protected final void setRawResult(V value) { result = value; } protected final boolean exec() { result = compute(); return true; }}
  • 23. ThreadLocalRandom멀티쓰레드상에서Random 은 contention과 overhead가 존재. Random 내부에서 thread를 isolation을 함ForkJoinPool에서 Random 사용시 이슈가 속도가 저하되기 때문에 이를 해결할 수 있는 클래스23long f = ThreadLocalRandom.current().nextLong();System.out.println("1 : " + f);f = ThreadLocalRandom.current().nextLong();System.out.println("2 : " + f);1 : 42322372 : 767956431209526212
  • 24. Phaser특징쓰레드를 동시 시작/종료시킬 수 있도록 함CyclicBarrier와 CountDownLatch클래스를 보다 유연함좋은 자료http://download.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.htmlhttp://olegignatenko.livejournal.com/16771.html24
  • 25. Phaser예제25public static void main(String[] args) {runDevelopment(Arrays.asList(new Developer(), new Developer(), new Developer(), new Developer()));}private static void runDevelopment(Iterable<Developer> team) { final Phasermanager = new Phaser(1); //"1" to register selfSystem.out.println("mgr: assign all developers, then start coding"); for (final Developer developer : team) { final String dev = developer.toString();System.out.println("mgr: assigns a new unarrived " + dev + " to the project");manager.register(); new Thread() { public void run() {System.out.println("mgr: " + dev + ", please await all developers");manager.arriveAndAwaitAdvance(); // await all creationSystem.out.println("mgr: " + dev + ", OK to start coding");developer.run();} }.start();}System.out.println("mgr: all assigned, start coding after all arrive");manager.arriveAndDeregister();}class Developer implements Runnable { private final static AtomicIntegeridSource = new AtomicInteger(); private final int id = idSource.incrementAndGet(); public void run() { System.out.println(toString() + ": coding"); } public String toString() { return "developer #" + id; }}
  • 26. Phaser결과26mgr: assign all developers, then start codingmgr: assigns a new unarrived developer #1 to the projectmgr: assigns a new unarrived developer #2 to the projectmgr: developer #1, please await all developersmgr: assigns a new unarrived developer #3 to the projectmgr: assigns a new unarrived developer #4 to the projectmgr: developer #3, please await all developersmgr: all assigned, start coding after all arrivemgr: developer #4, please await all developersmgr: developer #2, please await all developersmgr: developer #2, OK to start codingdeveloper #2: codingmgr: developer #1, OK to start codingdeveloper #1: codingmgr: developer #3, OK to start codingdeveloper #3: codingmgr: developer #4, OK to start codingdeveloper #4: coding