SlideShare une entreprise Scribd logo
1  sur  12
Two-Phase Termination  뒷정리를 하고 나서 자도록 해요 JAVA 언어로 배우는 디자인 패턴 입문 – 멀티쓰레드 편 <아키텍트를 꿈꾸는 사람들> 2008.06.14  현수명
2단계 종료! 작업중 종료 1단계 종료요구 종료 처리중 종료 2단계 종료처리완료
Main :CountupThread start isShutdownRequested false doWork isShutdownRequested false doWork shutdownRequest isShutdownRequested join true doShutdown
Two-Phase Termination Code Public final void run(){    try {       while ( !isShutdownRequested() ) { doWork();       }    } catch (InterruptedException e) {    } finally { doShutdown();    } 종료요구가  있었는가 ‘try...finally 사용’ 작업 처리 종료 처리
public class CountupThread extends Thread {    private long counter = 0;    private volatile boolean shutdownRequested = false;    public void shutdownRequest() {       shutdownRequested = true; interrupt();    }    public boolean isShutdownRequested() {       return shutdownRequested;    }    public final void run(){       try {          while ( !isShutdownRequested() ) { doWork();          }       } catch (InterruptedException e) {       } finally { doShutdown();       }    private void doWork() throws InterruptedException {       counter++;       System.out.println(“doWork: counter =“+counter);       Thread.sleep(500);    }    private void doShutdown() {        System.out.println(“doShutDown”);    } 예제소스 public class Main {    public static void main(String[] args) {       System.out.println(“main:BEGIN”);       try {          CountupThread t = new CountupThread(); t.start();          Thread.sleep(10000);          t.shutdownRequest();          t.join();       } catch (InterruptedException e) {          e.printStackTrace();       }    }
Two-Phase Termincation패턴 Terminator Requests shutdown -shutdownRequested TerminationRequester +shutdownRequest {concurrent} +isShutdownRequested {concurrent} +run { frozen } #doWork #doShutdown
우아하게 종료하는 쓰레드 안정성 “이제 그만 자야지”라는 엄마의 이야기에 황급히 치우다가 장난감을 망가뜨리는 일이 없도록 주의하자 생존성 장난감을 어질러 놓은채로 잠들지 않도록 하자 응답성 엄마가 “치우세요”라고 이야기하면  가능한 빨리 치우기 시작하자
생각의 폭을 넓히자 Stop 메소드를 사용하지말자    -> 안정성이 보장되지 않음 플래그 테스트만으로는 충분하지 않아요    -> sleep 중일때를 대비하여 interrupt 필요함 인터럽트 상태 테스트만으로도 충분하지 않아요    -> InterruptedException 을 무시하는경우 고려 무거운처리를 하기전에 종료요구를 체크    -> 응답성 Join 메소드와 isAlive 메소드    -> 쓰레드가 종료되기를 기다림 ExecutorService 인터페이스    -> Two-Phase Termination 패턴이 사용됨
보강 1. 쓰레드의 Interrupt 상태    Interrupt() 함수를 호출하면 대상 쓰레드는 항상                InterruptedException 을 통보하는게 아님. 2. concurrent 패키지    Java.util.concurrent.CountDownLatch       -> 10개의 일이 모두 끝나기를 기다린다.    Java.util.concurrent.CyclicBarrier       -> 3개의 쓰레드모두 N 단계를 종료할때까지 어떤 쓰레드도            N단계+1 로 나아가지 않는다. 3. Volatile    synchronized 는 배타제어와 동기화. Volatile 은 동기화만 이루어짐.    volatile 필드에 입력한 내용은 다른 쓰레드가 곧바로 볼수있음. reorder 가 일어나지 않음.
정리 종료하기전에 특정 종료처리를 실행. 종료요구 flag 를 이용하여 주기적으로 종료요청 여부판단 실행시 예외가 발생하더라도 확실하게 종료 처리를 시키기 위해서 try...finally 사용
Reference Java로 배우는 멀티쓰레드패턴 Ch.10
끝 감사합니다. soomong80@gmail.com 2008.06.14현수명

Contenu connexe

Tendances

242 naver-2
242 naver-2242 naver-2
242 naver-2NAVER D2
 
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요NAVER D2
 
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?내훈 정
 
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화sung ki choi
 
안드로이드 멀티스레딩 입문 송형주
안드로이드 멀티스레딩 입문 송형주안드로이드 멀티스레딩 입문 송형주
안드로이드 멀티스레딩 입문 송형주iamhjoo (송형주)
 
LockFree Algorithm
LockFree AlgorithmLockFree Algorithm
LockFree AlgorithmMerry Merry
 
Concurrency in action - chapter 7
Concurrency in action - chapter 7Concurrency in action - chapter 7
Concurrency in action - chapter 7JinWoo Lee
 
Concurrency in action - chapter 5
Concurrency in action - chapter 5Concurrency in action - chapter 5
Concurrency in action - chapter 5JinWoo Lee
 
[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현
[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현
[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현NAVER D2
 
11장 윈도우 스레드 풀
11장 윈도우 스레드 풀11장 윈도우 스레드 풀
11장 윈도우 스레드 풀홍준 김
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. JobHyosung Jeon
 
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요? (2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요? 내훈 정
 
7가지 동시성 모델-2장
7가지 동시성 모델-2장7가지 동시성 모델-2장
7가지 동시성 모델-2장Sunggon Song
 
함수형사고 3장 양도하라
함수형사고 3장 양도하라함수형사고 3장 양도하라
함수형사고 3장 양도하라Sunggon Song
 
[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)동욱 하
 

Tendances (20)

tcp ip study
tcp ip studytcp ip study
tcp ip study
 
242 naver-2
242 naver-2242 naver-2
242 naver-2
 
Thread
ThreadThread
Thread
 
Ndc12 2
Ndc12 2Ndc12 2
Ndc12 2
 
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
 
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
 
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
 
D2 Job Pool
D2 Job PoolD2 Job Pool
D2 Job Pool
 
190325 synchro
190325 synchro190325 synchro
190325 synchro
 
안드로이드 멀티스레딩 입문 송형주
안드로이드 멀티스레딩 입문 송형주안드로이드 멀티스레딩 입문 송형주
안드로이드 멀티스레딩 입문 송형주
 
LockFree Algorithm
LockFree AlgorithmLockFree Algorithm
LockFree Algorithm
 
Concurrency in action - chapter 7
Concurrency in action - chapter 7Concurrency in action - chapter 7
Concurrency in action - chapter 7
 
Concurrency in action - chapter 5
Concurrency in action - chapter 5Concurrency in action - chapter 5
Concurrency in action - chapter 5
 
[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현
[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현
[2D7]레기온즈로 살펴보는 확장 가능한 게임서버의 구현
 
11장 윈도우 스레드 풀
11장 윈도우 스레드 풀11장 윈도우 스레드 풀
11장 윈도우 스레드 풀
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. Job
 
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요? (2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
 
7가지 동시성 모델-2장
7가지 동시성 모델-2장7가지 동시성 모델-2장
7가지 동시성 모델-2장
 
함수형사고 3장 양도하라
함수형사고 3장 양도하라함수형사고 3장 양도하라
함수형사고 3장 양도하라
 
[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)
 

En vedette

Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Designhyun soomyung
 
Dependency Breaking Techniques
Dependency Breaking TechniquesDependency Breaking Techniques
Dependency Breaking Techniqueshyun soomyung
 
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍흥배 최
 
Distributed systems and scalability rules
Distributed systems and scalability rulesDistributed systems and scalability rules
Distributed systems and scalability rulesOleg Tsal-Tsalko
 
Promise 패턴 공부
Promise 패턴 공부Promise 패턴 공부
Promise 패턴 공부HongGun Yoo
 
Scalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed SystemsScalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed Systemshyun soomyung
 
Design principles of scalable, distributed systems
Design principles of scalable, distributed systemsDesign principles of scalable, distributed systems
Design principles of scalable, distributed systemsTinniam V Ganesh (TV)
 
Scalable Internet Architecture
Scalable Internet ArchitectureScalable Internet Architecture
Scalable Internet ArchitectureTheo Schlossnagle
 
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)내훈 정
 
High Scalability by Example – How can Web-Architecture scale like Facebook, T...
High Scalability by Example – How can Web-Architecture scale like Facebook, T...High Scalability by Example – How can Web-Architecture scale like Facebook, T...
High Scalability by Example – How can Web-Architecture scale like Facebook, T...Robert Mederer
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systemssumitjain2013
 
7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications7 Stages of Scaling Web Applications
7 Stages of Scaling Web ApplicationsDavid Mitzenmacher
 

En vedette (14)

Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Dependency Breaking Techniques
Dependency Breaking TechniquesDependency Breaking Techniques
Dependency Breaking Techniques
 
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
 
Distributed systems and scalability rules
Distributed systems and scalability rulesDistributed systems and scalability rules
Distributed systems and scalability rules
 
Promise 패턴 공부
Promise 패턴 공부Promise 패턴 공부
Promise 패턴 공부
 
Scalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed SystemsScalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed Systems
 
Scalable Web Architecture
Scalable Web ArchitectureScalable Web Architecture
Scalable Web Architecture
 
Design principles of scalable, distributed systems
Design principles of scalable, distributed systemsDesign principles of scalable, distributed systems
Design principles of scalable, distributed systems
 
Scalable Internet Architecture
Scalable Internet ArchitectureScalable Internet Architecture
Scalable Internet Architecture
 
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
 
High Scalability by Example – How can Web-Architecture scale like Facebook, T...
High Scalability by Example – How can Web-Architecture scale like Facebook, T...High Scalability by Example – How can Web-Architecture scale like Facebook, T...
High Scalability by Example – How can Web-Architecture scale like Facebook, T...
 
Scalability Design Principles - Internal Session
Scalability Design Principles - Internal SessionScalability Design Principles - Internal Session
Scalability Design Principles - Internal Session
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systems
 
7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications
 

Similaire à Design Pattern - Multithread Ch10

Multithread design pattern
Multithread design patternMultithread design pattern
Multithread design pattern종빈 오
 
android_thread
android_threadandroid_thread
android_threadhandfoot
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍NAVER D2
 
Effective unit testing ch3. 테스트더블
Effective unit testing   ch3. 테스트더블Effective unit testing   ch3. 테스트더블
Effective unit testing ch3. 테스트더블YongEun Choi
 
Spring Cloud Workshop
Spring Cloud WorkshopSpring Cloud Workshop
Spring Cloud WorkshopYongSung Yoon
 
[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성NAVER D2
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsSeok-joon Yun
 
11장 윈도우 스레드 풀 + 12장 파이버
11장 윈도우 스레드 풀 + 12장 파이버11장 윈도우 스레드 풀 + 12장 파이버
11장 윈도우 스레드 풀 + 12장 파이버홍준 김
 
C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기Heo Seungwook
 
.NET에서 비동기 프로그래밍 배우기
.NET에서 비동기 프로그래밍 배우기.NET에서 비동기 프로그래밍 배우기
.NET에서 비동기 프로그래밍 배우기Seong Won Mun
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
KGC2010 - 낡은 코드에 단위테스트 넣기
KGC2010 - 낡은 코드에 단위테스트 넣기KGC2010 - 낡은 코드에 단위테스트 넣기
KGC2010 - 낡은 코드에 단위테스트 넣기Ryan Park
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기jongho jeong
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Circulus
 
Easy gameserver
Easy gameserverEasy gameserver
Easy gameserver진상 문
 

Similaire à Design Pattern - Multithread Ch10 (20)

Multithread design pattern
Multithread design patternMultithread design pattern
Multithread design pattern
 
android_thread
android_threadandroid_thread
android_thread
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
Spring Boot 2
Spring Boot 2Spring Boot 2
Spring Boot 2
 
Effective unit testing ch3. 테스트더블
Effective unit testing   ch3. 테스트더블Effective unit testing   ch3. 테스트더블
Effective unit testing ch3. 테스트더블
 
Spring Cloud Workshop
Spring Cloud WorkshopSpring Cloud Workshop
Spring Cloud Workshop
 
[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threads
 
Clean code appendix 1
Clean code appendix 1Clean code appendix 1
Clean code appendix 1
 
Rx java essentials
Rx java essentialsRx java essentials
Rx java essentials
 
11장 윈도우 스레드 풀 + 12장 파이버
11장 윈도우 스레드 풀 + 12장 파이버11장 윈도우 스레드 풀 + 12장 파이버
11장 윈도우 스레드 풀 + 12장 파이버
 
C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기
 
.NET에서 비동기 프로그래밍 배우기
.NET에서 비동기 프로그래밍 배우기.NET에서 비동기 프로그래밍 배우기
.NET에서 비동기 프로그래밍 배우기
 
Gcd ppt
Gcd pptGcd ppt
Gcd ppt
 
MutiCore 19-20
MutiCore 19-20MutiCore 19-20
MutiCore 19-20
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
KGC2010 - 낡은 코드에 단위테스트 넣기
KGC2010 - 낡은 코드에 단위테스트 넣기KGC2010 - 낡은 코드에 단위테스트 넣기
KGC2010 - 낡은 코드에 단위테스트 넣기
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리
 
Easy gameserver
Easy gameserverEasy gameserver
Easy gameserver
 

Plus de hyun soomyung

아꿈사 매니저소개
아꿈사 매니저소개아꿈사 매니저소개
아꿈사 매니저소개hyun soomyung
 
HTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,AudioHTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,Audiohyun soomyung
 
The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조hyun soomyung
 
The Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 TreeThe Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 Treehyun soomyung
 
The Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXALThe Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXALhyun soomyung
 
The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5hyun soomyung
 
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)hyun soomyung
 
프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장hyun soomyung
 
[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술hyun soomyung
 
실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부hyun soomyung
 
xUnitTestPattern/chapter8
xUnitTestPattern/chapter8xUnitTestPattern/chapter8
xUnitTestPattern/chapter8hyun soomyung
 
예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법hyun soomyung
 
프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?hyun soomyung
 
5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)hyun soomyung
 

Plus de hyun soomyung (20)

아꿈사 매니저소개
아꿈사 매니저소개아꿈사 매니저소개
아꿈사 매니저소개
 
HTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,AudioHTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,Audio
 
Hybrid app
Hybrid appHybrid app
Hybrid app
 
MapReduce
MapReduceMapReduce
MapReduce
 
MongoDB
MongoDBMongoDB
MongoDB
 
The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조
 
The Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 TreeThe Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 Tree
 
The Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXALThe Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXAL
 
The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5
 
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
 
Clojure Chapter.6
Clojure Chapter.6Clojure Chapter.6
Clojure Chapter.6
 
프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장
 
[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술
 
실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부
 
xUnitTestPattern/chapter8
xUnitTestPattern/chapter8xUnitTestPattern/chapter8
xUnitTestPattern/chapter8
 
예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법
 
프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?
 
Erlang
ErlangErlang
Erlang
 
5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)
 
이산수학 Ch.5
이산수학 Ch.5이산수학 Ch.5
이산수학 Ch.5
 

Dernier

Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Wonjun Hwang
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)Tae Young Lee
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionKim Daeun
 
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Kim Daeun
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Wonjun Hwang
 
캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스
 

Dernier (6)

Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
 
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)
 
캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차
 

Design Pattern - Multithread Ch10

  • 1. Two-Phase Termination 뒷정리를 하고 나서 자도록 해요 JAVA 언어로 배우는 디자인 패턴 입문 – 멀티쓰레드 편 <아키텍트를 꿈꾸는 사람들> 2008.06.14 현수명
  • 2. 2단계 종료! 작업중 종료 1단계 종료요구 종료 처리중 종료 2단계 종료처리완료
  • 3. Main :CountupThread start isShutdownRequested false doWork isShutdownRequested false doWork shutdownRequest isShutdownRequested join true doShutdown
  • 4. Two-Phase Termination Code Public final void run(){ try { while ( !isShutdownRequested() ) { doWork(); } } catch (InterruptedException e) { } finally { doShutdown(); } 종료요구가 있었는가 ‘try...finally 사용’ 작업 처리 종료 처리
  • 5. public class CountupThread extends Thread { private long counter = 0; private volatile boolean shutdownRequested = false; public void shutdownRequest() { shutdownRequested = true; interrupt(); } public boolean isShutdownRequested() { return shutdownRequested; } public final void run(){ try { while ( !isShutdownRequested() ) { doWork(); } } catch (InterruptedException e) { } finally { doShutdown(); } private void doWork() throws InterruptedException { counter++; System.out.println(“doWork: counter =“+counter); Thread.sleep(500); } private void doShutdown() { System.out.println(“doShutDown”); } 예제소스 public class Main { public static void main(String[] args) { System.out.println(“main:BEGIN”); try { CountupThread t = new CountupThread(); t.start(); Thread.sleep(10000); t.shutdownRequest(); t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }
  • 6. Two-Phase Termincation패턴 Terminator Requests shutdown -shutdownRequested TerminationRequester +shutdownRequest {concurrent} +isShutdownRequested {concurrent} +run { frozen } #doWork #doShutdown
  • 7. 우아하게 종료하는 쓰레드 안정성 “이제 그만 자야지”라는 엄마의 이야기에 황급히 치우다가 장난감을 망가뜨리는 일이 없도록 주의하자 생존성 장난감을 어질러 놓은채로 잠들지 않도록 하자 응답성 엄마가 “치우세요”라고 이야기하면 가능한 빨리 치우기 시작하자
  • 8. 생각의 폭을 넓히자 Stop 메소드를 사용하지말자 -> 안정성이 보장되지 않음 플래그 테스트만으로는 충분하지 않아요 -> sleep 중일때를 대비하여 interrupt 필요함 인터럽트 상태 테스트만으로도 충분하지 않아요 -> InterruptedException 을 무시하는경우 고려 무거운처리를 하기전에 종료요구를 체크 -> 응답성 Join 메소드와 isAlive 메소드 -> 쓰레드가 종료되기를 기다림 ExecutorService 인터페이스 -> Two-Phase Termination 패턴이 사용됨
  • 9. 보강 1. 쓰레드의 Interrupt 상태 Interrupt() 함수를 호출하면 대상 쓰레드는 항상 InterruptedException 을 통보하는게 아님. 2. concurrent 패키지 Java.util.concurrent.CountDownLatch -> 10개의 일이 모두 끝나기를 기다린다. Java.util.concurrent.CyclicBarrier -> 3개의 쓰레드모두 N 단계를 종료할때까지 어떤 쓰레드도 N단계+1 로 나아가지 않는다. 3. Volatile synchronized 는 배타제어와 동기화. Volatile 은 동기화만 이루어짐. volatile 필드에 입력한 내용은 다른 쓰레드가 곧바로 볼수있음. reorder 가 일어나지 않음.
  • 10. 정리 종료하기전에 특정 종료처리를 실행. 종료요구 flag 를 이용하여 주기적으로 종료요청 여부판단 실행시 예외가 발생하더라도 확실하게 종료 처리를 시키기 위해서 try...finally 사용
  • 11. Reference Java로 배우는 멀티쓰레드패턴 Ch.10