SlideShare a Scribd company logo
Java 사흘째
TmaxSoft R&D Center
1
113년	 10월	 10일	 목
자바 교육 계획
1일 : Language, String,
ClassLoader, Proxy
2일 : GC, Collections
3일 : Thread, Java Memory
Model
4일 : AQS, ForkJoin,
Concurrent Utils
5일 : IO, Generics, Annotation,
RMI
6일 : Unsafe, Lambda (Java 8)
2
213년	 10월	 10일	 목
오늘 내용
GC Review
Thread and Locks
park/unpark
Java Memory Model
volatile, final
3
313년	 10월	 10일	 목
지난 시간 리뷰 : Hotspot GC
4
413년	 10월	 10일	 목
GC 종류별 JVM Heap 형태
Generational Heap
Young (Eden, two survivor spaces)
Old (Tenured Areas, permanent)
새로운 G1 GC : 2~32MB 크기의 Region들로 구성
하지만 각 region은 generation 개념을 가진다
5
513년	 10월	 10일	 목
Generational Heaps
6
PERMANENT
613년	 10월	 10일	 목
G1 GC Regions
7
713년	 10월	 10일	 목
Hotspot Collector 종류
mark-sweep-compact collector :
serial 혹은 parallel. young이든 old든 짧고 긴 STW pause가 필요
mark & sweep collector : pause time이 짧다.
CMS(Concurrent Mark & Sweep) collector는 compaction을 하
지 않는다. fragmentation 이슈가 발생.
G1 collector (JDK 7u4 버전부터 지원)
CMS와 유사하지만, 대부분 reclaimable한 region들에 대해서
compaction 수행 (마지막 단계가 compaction)
8
813년	 10월	 10일	 목
Thread and Locks
9
913년	 10월	 10일	 목
Thread 실행
10
“main” thread : java launcher에 의해 실행되는 사용자 쓰레드
public static void main(String[ ]);
java.lang.Thread 객체를 사용한 사용자 쓰레드 실행
public synchronized void start();
Thread 객체의 이 메소드를 호출하면 JVM이 새 쓰레드를 만
들어 해당 쓰레드에서 run() 메소드를 호출
하나의 Thread 객체에서 두번 start()를 호출하면
IllegalStateException 발생
1013년	 10월	 10일	 목
java.lang.Thread
Constructor parameters
String name : 쓰레드 이름 명시할 때
ThreadGroup group : 쓰레드 그룹을 지정할 때
Runnable runnable : run()에서 실행할 내용을 다른 객체에서 구현했을 때
public final void setDaemon(boolean);
사용자가 만든 쓰레드를 daemon thread와 user thread 두가지로 구분.
JVM은 user thread가 모두 종료하면 프로세스를 종료시킴.
public long getId();
JVM에서 thread를 만들 때 발급하는 고유 id. OS의 tid와 아무 관련없음.
11
1113년	 10월	 10일	 목
Thread의 종료
run() 메소드가 끝나면 해당 Thread가 종료
프로세스를 종료하는 System.exit() 외에 유일하게 안전한 방법
JVM 구현상 이슈로 아래 메소드들은 모두 금지
public final void stop()
public void destroy()
public final void suspend()
public final void resume()
12
1213년	 10월	 10일	 목
Why not stop/suspend/...??
쓰레드가 임의의 lock을 잡은 상태에서 강제로 stop하거나 suspend시켰을 때
practical한 방법으로 안전하게 구현할 수가 없기 때문
즉, 해당 쓰레드는 기존의 lock들을 놓아야 하고, 해당 lock을 기다리던 다른 쓰레
드들이 이 lock을 잡아서 실행하게 되는데 stop과 suspend는 임의의 시점에서 호
출될 수 있기 때문에 semantic하게 critical section의 역할을 처리해줄 수가 없음
원래 stop 구현은 호출되면 JVM에서 해당 thread 문맥에서 ThreadDeath 객
체를 만들어 throw하는 방식
논리적으로 불가능하지 않지만 너무 복잡해지고 효율적이지 않음
모든 user code에서 ThreadDeath 객체를 catch해야 하지만 그 catch나
finally 안에서 또 ThreadDeath가 발생할 수 있음을 고려해야 함.
13
1313년	 10월	 10일	 목
Then, 어떻게???
다른 쓰레드에서 종료/일시중지하려는 해당 쓰레드에
interrupt 를 사용하여 해당 thread에 notification을 보낼 수
는 있으므로 사용자 코드에서 flag를 사용하여 직접 종료/일시
중지/재개 등을 구현해야 함
14
1413년	 10월	 10일	 목
Thread의 interrupt
public void interrupt();
Thread 객체가 가리키는 쓰레드를 interrupt하는 동작
해당 쓰레드가 Object 객체의 wait이나, Thread 객체의 sleep, join 등
을 수행 중이었으면 InterruptedException이 발생되고 해당 쓰레드의
interrupted 플래그가 clear
다른 blocking operation이 진행 중이었으면 interrupted 플래그가 set
blocking op가 interruptible channel이었으면 바로 종료하면서
ClosedByInterruptedException를 리턴하나(이 경우에도 flag는
set), 그렇지 않은 경우는 플래그만 바뀐 채 계속 block되어 있음
15
1513년	 10월	 10일	 목
interrupt 상태 체크
java.lang.Thread의 다음 두 메소드 동작이 다름
public static boolean interrupted();
현재 실행 쓰레드의 interrupted 플래그를 알려주고
reset
public boolean isInterrupted();
Thread 객체가 가리키는 쓰레드의 현재 interrupted 플
래그를 알려줌
16
1613년	 10월	 10일	 목
Thread 상태 (JDK 5)
NEW : start 호출 전
RUNNABLE : run 실행 상태
BLOCKED : synchronized lock을 기다리는 상태
WAITING : Object.wait, Thread.join 혹은 LockSupport.park를
실행 중인 상태
TIMED_WAITING : time 인자를 줘서 wait, join, park를 실행하였
거나 Thread.sleep을 실행 중인 상태
TERMINATED : thread가 종료한 상태
17
1713년	 10월	 10일	 목
ContextClassLoader?
public ClassLoader getContextClassLoader();
public void setContextClassLoader(ClassLoader cl);
쓰레드별로 특별한 의미를 가진 classloader를 지정하기 위함
쓰레드를 만들 때 creator thread로부터 상속받음
main thread의 context classloader는 null
같은 로직을 수행하는 worker thread들(thread pool)을 고려한 API
Java EE 환경에서 주로 많이 사용
18
1813년	 10월	 10일	 목
Locks and Conditions
synchronized block (or method)
monitor object
lock/unlock의 대상 개념
모든 객체가 monitor가 될 수 있음
java.lang.Object의 wait, notify, notifyAll
lock을 획득한 monitor 객체에 대해 condition 기능 사
용하는 API
19
1913년	 10월	 10일	 목
spurious wakeup
Object.wait
A thread can also wake up without being notified,
interrupted, or timing out, a so-called spurious wakeup
예를 들어 내부적으로 signal handler 루틴 내에서 system call
을 처리하는 중에 전달된 notify를 놓칠 수가 있으므로 kernel
내부에서 다시 wait하는 형태로 처리할 수가 없다.
항상 user code에서 spurious wakeup의 가능성을 고려하
여 guarded condition을 체크하는 loop 안에서 wait해야
20
2013년	 10월	 10일	 목
notify/notifyAll
Notify
Wake up only one thread if any was waiting
less overhead (better performance)
Applicable on limited cases
NotifyAll
All the waiting threads can check its guard condition
waiting thread들이 많을 때엔 큰 오버헤드
21
2113년	 10월	 10일	 목
Hotspot JVM에서 lock 구현
2-word object header (array인 경우는 3-word)
1st word : mark word
used by sync and gc, caches hashCode
2bit를 sync state로 사용 (monitor object)
01 unlocked, 00 light-weight locked,
10 heavy-weight locked, 11 marked for GC
2nd word : metadata word
22
2213년	 10월	 10일	 목
Hotspot JVM에서 lock 구현
CAS를 사용한 lightweight lock
1. 먼저 mark word를 execution stack의 lock record에 copy한다
2. AtomicCAS를 사용하여 mark word를 stack에 copy된 주소 pointer로 변경
한다.
3. 성공하면 이 object가 해당 execution thread의 lock monitor가 됨
4. 실패하면 (contention이 생길 때) heavyweight lock 시도
unlock
1. lock record에 mark word를 object의 word로 CAS
recursive lock : lock record에 0을 저장
23
2313년	 10월	 10일	 목
Hotspot JVM에서 lock 구현
CAS latency를 줄이기 위한 biased locking도 현재 버전에 구현
하나의 object가 하나의 thread의 monitor로 사용될 경우 atomic CAS 없이 lock,
unlock을 수행할 수 있는 알고리즘. 즉, 같은 쓰레드가 reacquire할 때를 위한
optimization
mark word에 앞의 2bit 외에 1bit를 추가적으로 사용
001 => unlocked
101 => biased or biasable (thread ID == 0 == unlocked)
Bias obtained via CAS
Subsequent locks / unlocks by owner very cheap
Test-and-branch, no atomics
24
2413년	 10월	 10일	 목
park/unpark 모델 (JDK 5)
java.util.concurrent.locks.LockSupport
public static void park();
blocks current thread if unpark is not (yet) called or until
unpark is called
parked thread can be spuriously waken and can be waken
by interrupt() call
public static void unpark(Thread thread);
unblock currently parked thread. multiple unpark doesn’t
count but the unparked state is remembered
25
2513년	 10월	 10일	 목
Java Memory Model
Atomicity
Java에서 long과 double을 제외한 모든 data field에 대한 update는 atomic
volatile로 선언되면 모든 field update가 atomic
Visibility
한 쓰레드에서 이루어진 data field update를 다른 쓰레드에서 보는 걸 보장하려면 (1) 두 쓰레드가
lock을 공유하거나 (2) 해당 필드가 volatile로 선언되거나 (3) 읽는 쓰레드가 해당 필드를 처음 접근
할 때
한 쓰레드가 종료할 때에는 메모리에 flush가 되므로 Thread.join을 통해 기다리는 쓰레드는 해당
종료 쓰레드의 write를 모두 읽을 수 있다.
Ordering
lock 혹은 volatile을 제외하면 컴파일러에 의해 어떤 reordering도 가능 (물론 같은 쓰레드 내에서
는 동일한 효과가 있어야 함)
26
2613년	 10월	 10일	 목
volatile
Java Memory Model (JSR-133)에 의하면 같은 volatile 필드에 접근하는 서로 다
른 쓰레드들 간에서 happens-before 관계가 성립해야 함 (visibility, ordering 보장)
volatile 필드에 write하면 해당 쓰레드의 모든 변수들을 flush하는 효과가 있어야
하며 (sync 블럭을 벗어날때와 동일)
volatile 필드에 read할 때에도 cache 값이 invalidate되어야 한다 (sync 블럭을
시작할 때와 동일)
JVM은 volatile을 monitor와 마찬가지로 barrier를 사용해서 구현 (memory 변수로
구현해서는 JMM을 위반하게 된다)
실제 구현은 앞 op가 write 이고 다음 op가 read일 경우에만 mfence (x86) 등의
instruction으로 구현할 수 있다. (다른 case는 x86에서는 no-op)
27
2713년	 10월	 10일	 목
volatile 예제
int x = 0; volatile boolean v = false;
public void writer() { // Thread t1
x = 42; v = true;
}
public void reader() { // Thread t2
if (v == true) {
// uses x - guaranteed to see 42 (not 0!)
}}
28
2813년	 10월	 10일	 목
Double-checked Locking
엄격해진 JMM의 volatile 정의로 DCL이 동작
private static volatile Something instance = null;
public Something getInstance() {
if (instance == null) {
synchronized (this) {
if (instance == null)
instance = new Something();
}
}
return instance;
}
29
Lazy Initialization Holder를 사용하면
volatile도 불필요 (static field는 visibility가 보
장)
private static class LazySomethingHolder
{
public static Something something =
new Something();
}
public static Something getInstance() {
return LazySomethingHolder.something;
}
2913년	 10월	 10일	 목
final field
final field cannot be modified once it has been initialized
final fields are initialized in its constructor or its initializer
correct value of any final fields will be visible to other threads without
synchronization if constructor follows a rule
rule : the this reference must not be released from the constructor
before the constructor returns
즉, final field 값이 될 객체가 생성자가 리턴하기 전에 이 필드를 액세스하면
초기화되기 전의 값이 보인다.
final static field나 final method는 컴파일러가 optimize할 여지가 많지만 final
field는 별로 그렇지 않다. (초기화 시 컴파일러가 reordering 제약만 적용)
30
3013년	 10월	 10일	 목
ThreadLocal
thread 객체에 threadLocals라는 ThreadLocalMap을 들고 있음 (since JDK 1.5)
별도의 Overhead는 없으며, access할 때에도 lock을 전혀 쓰지 않음
WeakReference를 쓰고 있어서 Memory 부족 현상이 있을 때 정보가 소실될 수
있음
InheritedThreadLocal
thread 객체에 inheritableThreadLocals라는 ThreadLocalMap을 들고 있음
생성할 때 parent thread의 inheritableThreadLocals 정보를 모두 복사하여
child의 inherited thread local에 넣어줌
parent의 것이 동적으로 반영되지는 않음 (생성 시에 복사로 상속)
31
3113년	 10월	 10일	 목
다음 시간 예정
java.util.concurrent
Atomic CAS
AbstractQueueSynchronizer, Lock & Condition
Concurrent Collections
Fork-Join framework
32
3213년	 10월	 10일	 목

More Related Content

What's hot

[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스종빈 오
 
Java 8 고급 (1/6)
Java 8 고급 (1/6)Java 8 고급 (1/6)
Java 8 고급 (1/6)
Kyung Koo Yoon
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. Job
Hyosung Jeon
 
Jvm
JvmJvm
Windows via C/C++ 06 스레드의 기본
Windows via C/C++ 06 스레드의 기본Windows via C/C++ 06 스레드의 기본
Windows via C/C++ 06 스레드의 기본
ssuser0c2478
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshin
Dong Chan Shin
 
자바스크립트 프로토타입 및 클래스
자바스크립트 프로토타입 및 클래스자바스크립트 프로토타입 및 클래스
자바스크립트 프로토타입 및 클래스
Lee Dong Wook
 
02 realm 모델 & 관계
02   realm 모델 & 관계02   realm 모델 & 관계
02 realm 모델 & 관계
Lee-Jong-Chan
 
Free rtos seminar
Free rtos seminarFree rtos seminar
Free rtos seminar
Cho Daniel
 
Scope and Closure of JavaScript
Scope and Closure of JavaScript Scope and Closure of JavaScript
Scope and Closure of JavaScript
Dahye Kim
 
Java programming pdf
Java programming pdfJava programming pdf
Java programming pdf
Ji Hoon Lee
 
Realm 코딩카페 - 이종찬
Realm   코딩카페 - 이종찬Realm   코딩카페 - 이종찬
Realm 코딩카페 - 이종찬
Lee-Jong-Chan
 
Anatomy of Realm
Anatomy of RealmAnatomy of Realm
Anatomy of Realm
Leonardo YongUk Kim
 
Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706
Yong Joon Moon
 
[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request
[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request
[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request
NAVER D2
 
07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도
ssuser3fb17c
 
MutiCore 19-20
MutiCore 19-20MutiCore 19-20
MutiCore 19-20
HyeonSeok Choi
 
비동기 파일 로딩
비동기 파일 로딩비동기 파일 로딩
비동기 파일 로딩
Bongseok Cho
 
11 윈도우스레드풀
11 윈도우스레드풀11 윈도우스레드풀
11 윈도우스레드풀
ssuser0c2478
 
Introduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&CIntroduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&Csys4u
 

What's hot (20)

[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스
 
Java 8 고급 (1/6)
Java 8 고급 (1/6)Java 8 고급 (1/6)
Java 8 고급 (1/6)
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. Job
 
Jvm
JvmJvm
Jvm
 
Windows via C/C++ 06 스레드의 기본
Windows via C/C++ 06 스레드의 기본Windows via C/C++ 06 스레드의 기본
Windows via C/C++ 06 스레드의 기본
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshin
 
자바스크립트 프로토타입 및 클래스
자바스크립트 프로토타입 및 클래스자바스크립트 프로토타입 및 클래스
자바스크립트 프로토타입 및 클래스
 
02 realm 모델 & 관계
02   realm 모델 & 관계02   realm 모델 & 관계
02 realm 모델 & 관계
 
Free rtos seminar
Free rtos seminarFree rtos seminar
Free rtos seminar
 
Scope and Closure of JavaScript
Scope and Closure of JavaScript Scope and Closure of JavaScript
Scope and Closure of JavaScript
 
Java programming pdf
Java programming pdfJava programming pdf
Java programming pdf
 
Realm 코딩카페 - 이종찬
Realm   코딩카페 - 이종찬Realm   코딩카페 - 이종찬
Realm 코딩카페 - 이종찬
 
Anatomy of Realm
Anatomy of RealmAnatomy of Realm
Anatomy of Realm
 
Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706
 
[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request
[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request
[D2 CAMPUS] 안드로이드 오픈소스 스터디자료 - Http Request
 
07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도
 
MutiCore 19-20
MutiCore 19-20MutiCore 19-20
MutiCore 19-20
 
비동기 파일 로딩
비동기 파일 로딩비동기 파일 로딩
비동기 파일 로딩
 
11 윈도우스레드풀
11 윈도우스레드풀11 윈도우스레드풀
11 윈도우스레드풀
 
Introduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&CIntroduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&C
 

Similar to Java 8 고급 (3/6)

JVM Synchronization_Wh apm
JVM Synchronization_Wh apmJVM Synchronization_Wh apm
JVM Synchronization_Wh apm
엑셈
 
7가지 동시성 모델-2장
7가지 동시성 모델-2장7가지 동시성 모델-2장
7가지 동시성 모델-2장
Sunggon Song
 
Multi-thread : producer - consumer
Multi-thread : producer - consumerMulti-thread : producer - consumer
Multi-thread : producer - consumer
Chang Yoon Oh
 
자바 메모리 릭 패턴
자바 메모리 릭 패턴자바 메모리 릭 패턴
자바 메모리 릭 패턴
효원 강
 
[Practical owi] lock & latch
[Practical owi] lock & latch[Practical owi] lock & latch
[Practical owi] lock & latch
EXEM
 
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
흥배 최
 
[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성
NAVER D2
 
Multi thread
Multi threadMulti thread
Multi thread
Nam Hyeonuk
 
Tcpl 12장 파생클래스
Tcpl 12장 파생클래스Tcpl 12장 파생클래스
Tcpl 12장 파생클래스
재정 이
 
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
NAVER D2
 
Concurrent programming
Concurrent programmingConcurrent programming
Concurrent programming
Byeongsu Kang
 
LockFree Algorithm
LockFree AlgorithmLockFree Algorithm
LockFree Algorithm
Merry Merry
 
Gcd ppt
Gcd pptGcd ppt
Gcd ppt
Sangon Lee
 
Api design for c++ ch3 pattern
Api design for c++ ch3 patternApi design for c++ ch3 pattern
Api design for c++ ch3 patternjinho park
 
Multithread design pattern
Multithread design patternMultithread design pattern
Multithread design pattern종빈 오
 
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
내훈 정
 
스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴
Sanghyuk Jung
 
스톰 접근 중
스톰 접근 중스톰 접근 중
스톰 접근 중June Yi
 
[Gpg2권 박민근] 1.13 스택 와인딩
[Gpg2권 박민근] 1.13 스택 와인딩[Gpg2권 박민근] 1.13 스택 와인딩
[Gpg2권 박민근] 1.13 스택 와인딩MinGeun Park
 

Similar to Java 8 고급 (3/6) (20)

JVM Synchronization_Wh apm
JVM Synchronization_Wh apmJVM Synchronization_Wh apm
JVM Synchronization_Wh apm
 
7가지 동시성 모델-2장
7가지 동시성 모델-2장7가지 동시성 모델-2장
7가지 동시성 모델-2장
 
Multi-thread : producer - consumer
Multi-thread : producer - consumerMulti-thread : producer - consumer
Multi-thread : producer - consumer
 
자바 메모리 릭 패턴
자바 메모리 릭 패턴자바 메모리 릭 패턴
자바 메모리 릭 패턴
 
[Practical owi] lock & latch
[Practical owi] lock & latch[Practical owi] lock & latch
[Practical owi] lock & latch
 
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
 
Clean code appendix 1
Clean code appendix 1Clean code appendix 1
Clean code appendix 1
 
[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성
 
Multi thread
Multi threadMulti thread
Multi thread
 
Tcpl 12장 파생클래스
Tcpl 12장 파생클래스Tcpl 12장 파생클래스
Tcpl 12장 파생클래스
 
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
 
Concurrent programming
Concurrent programmingConcurrent programming
Concurrent programming
 
LockFree Algorithm
LockFree AlgorithmLockFree Algorithm
LockFree Algorithm
 
Gcd ppt
Gcd pptGcd ppt
Gcd ppt
 
Api design for c++ ch3 pattern
Api design for c++ ch3 patternApi design for c++ ch3 pattern
Api design for c++ ch3 pattern
 
Multithread design pattern
Multithread design patternMultithread design pattern
Multithread design pattern
 
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
 
스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴
 
스톰 접근 중
스톰 접근 중스톰 접근 중
스톰 접근 중
 
[Gpg2권 박민근] 1.13 스택 와인딩
[Gpg2권 박민근] 1.13 스택 와인딩[Gpg2권 박민근] 1.13 스택 와인딩
[Gpg2권 박민근] 1.13 스택 와인딩
 

More from Kyung Koo Yoon

Kubernetes
Kubernetes Kubernetes
Kubernetes
Kyung Koo Yoon
 
Java 8 고급 (6/6)
Java 8 고급 (6/6)Java 8 고급 (6/6)
Java 8 고급 (6/6)
Kyung Koo Yoon
 
Java 8 고급 (4/6)
Java 8 고급 (4/6)Java 8 고급 (4/6)
Java 8 고급 (4/6)
Kyung Koo Yoon
 
Spring Framework - Inversion of Control Container
Spring Framework - Inversion of Control ContainerSpring Framework - Inversion of Control Container
Spring Framework - Inversion of Control Container
Kyung Koo Yoon
 
Smart software engineer
Smart software engineerSmart software engineer
Smart software engineer
Kyung Koo Yoon
 
Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Kyung Koo Yoon
 
Lecture on Java Concurrency Day 2 on Feb 4, 2009.
Lecture on Java Concurrency Day 2 on Feb 4, 2009.Lecture on Java Concurrency Day 2 on Feb 4, 2009.
Lecture on Java Concurrency Day 2 on Feb 4, 2009.
Kyung Koo Yoon
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Kyung Koo Yoon
 
Lecture on Java Concurrency Day 1 on Jan 21, 2009.
Lecture on Java Concurrency Day 1 on Jan 21, 2009.Lecture on Java Concurrency Day 1 on Jan 21, 2009.
Lecture on Java Concurrency Day 1 on Jan 21, 2009.
Kyung Koo Yoon
 
창의와 열정, 소프트웨어 엔지니어
창의와 열정, 소프트웨어 엔지니어창의와 열정, 소프트웨어 엔지니어
창의와 열정, 소프트웨어 엔지니어
Kyung Koo Yoon
 

More from Kyung Koo Yoon (10)

Kubernetes
Kubernetes Kubernetes
Kubernetes
 
Java 8 고급 (6/6)
Java 8 고급 (6/6)Java 8 고급 (6/6)
Java 8 고급 (6/6)
 
Java 8 고급 (4/6)
Java 8 고급 (4/6)Java 8 고급 (4/6)
Java 8 고급 (4/6)
 
Spring Framework - Inversion of Control Container
Spring Framework - Inversion of Control ContainerSpring Framework - Inversion of Control Container
Spring Framework - Inversion of Control Container
 
Smart software engineer
Smart software engineerSmart software engineer
Smart software engineer
 
Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.
 
Lecture on Java Concurrency Day 2 on Feb 4, 2009.
Lecture on Java Concurrency Day 2 on Feb 4, 2009.Lecture on Java Concurrency Day 2 on Feb 4, 2009.
Lecture on Java Concurrency Day 2 on Feb 4, 2009.
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
 
Lecture on Java Concurrency Day 1 on Jan 21, 2009.
Lecture on Java Concurrency Day 1 on Jan 21, 2009.Lecture on Java Concurrency Day 1 on Jan 21, 2009.
Lecture on Java Concurrency Day 1 on Jan 21, 2009.
 
창의와 열정, 소프트웨어 엔지니어
창의와 열정, 소프트웨어 엔지니어창의와 열정, 소프트웨어 엔지니어
창의와 열정, 소프트웨어 엔지니어
 

Java 8 고급 (3/6)

  • 1. Java 사흘째 TmaxSoft R&D Center 1 113년 10월 10일 목
  • 2. 자바 교육 계획 1일 : Language, String, ClassLoader, Proxy 2일 : GC, Collections 3일 : Thread, Java Memory Model 4일 : AQS, ForkJoin, Concurrent Utils 5일 : IO, Generics, Annotation, RMI 6일 : Unsafe, Lambda (Java 8) 2 213년 10월 10일 목
  • 3. 오늘 내용 GC Review Thread and Locks park/unpark Java Memory Model volatile, final 3 313년 10월 10일 목
  • 4. 지난 시간 리뷰 : Hotspot GC 4 413년 10월 10일 목
  • 5. GC 종류별 JVM Heap 형태 Generational Heap Young (Eden, two survivor spaces) Old (Tenured Areas, permanent) 새로운 G1 GC : 2~32MB 크기의 Region들로 구성 하지만 각 region은 generation 개념을 가진다 5 513년 10월 10일 목
  • 7. G1 GC Regions 7 713년 10월 10일 목
  • 8. Hotspot Collector 종류 mark-sweep-compact collector : serial 혹은 parallel. young이든 old든 짧고 긴 STW pause가 필요 mark & sweep collector : pause time이 짧다. CMS(Concurrent Mark & Sweep) collector는 compaction을 하 지 않는다. fragmentation 이슈가 발생. G1 collector (JDK 7u4 버전부터 지원) CMS와 유사하지만, 대부분 reclaimable한 region들에 대해서 compaction 수행 (마지막 단계가 compaction) 8 813년 10월 10일 목
  • 9. Thread and Locks 9 913년 10월 10일 목
  • 10. Thread 실행 10 “main” thread : java launcher에 의해 실행되는 사용자 쓰레드 public static void main(String[ ]); java.lang.Thread 객체를 사용한 사용자 쓰레드 실행 public synchronized void start(); Thread 객체의 이 메소드를 호출하면 JVM이 새 쓰레드를 만 들어 해당 쓰레드에서 run() 메소드를 호출 하나의 Thread 객체에서 두번 start()를 호출하면 IllegalStateException 발생 1013년 10월 10일 목
  • 11. java.lang.Thread Constructor parameters String name : 쓰레드 이름 명시할 때 ThreadGroup group : 쓰레드 그룹을 지정할 때 Runnable runnable : run()에서 실행할 내용을 다른 객체에서 구현했을 때 public final void setDaemon(boolean); 사용자가 만든 쓰레드를 daemon thread와 user thread 두가지로 구분. JVM은 user thread가 모두 종료하면 프로세스를 종료시킴. public long getId(); JVM에서 thread를 만들 때 발급하는 고유 id. OS의 tid와 아무 관련없음. 11 1113년 10월 10일 목
  • 12. Thread의 종료 run() 메소드가 끝나면 해당 Thread가 종료 프로세스를 종료하는 System.exit() 외에 유일하게 안전한 방법 JVM 구현상 이슈로 아래 메소드들은 모두 금지 public final void stop() public void destroy() public final void suspend() public final void resume() 12 1213년 10월 10일 목
  • 13. Why not stop/suspend/...?? 쓰레드가 임의의 lock을 잡은 상태에서 강제로 stop하거나 suspend시켰을 때 practical한 방법으로 안전하게 구현할 수가 없기 때문 즉, 해당 쓰레드는 기존의 lock들을 놓아야 하고, 해당 lock을 기다리던 다른 쓰레 드들이 이 lock을 잡아서 실행하게 되는데 stop과 suspend는 임의의 시점에서 호 출될 수 있기 때문에 semantic하게 critical section의 역할을 처리해줄 수가 없음 원래 stop 구현은 호출되면 JVM에서 해당 thread 문맥에서 ThreadDeath 객 체를 만들어 throw하는 방식 논리적으로 불가능하지 않지만 너무 복잡해지고 효율적이지 않음 모든 user code에서 ThreadDeath 객체를 catch해야 하지만 그 catch나 finally 안에서 또 ThreadDeath가 발생할 수 있음을 고려해야 함. 13 1313년 10월 10일 목
  • 14. Then, 어떻게??? 다른 쓰레드에서 종료/일시중지하려는 해당 쓰레드에 interrupt 를 사용하여 해당 thread에 notification을 보낼 수 는 있으므로 사용자 코드에서 flag를 사용하여 직접 종료/일시 중지/재개 등을 구현해야 함 14 1413년 10월 10일 목
  • 15. Thread의 interrupt public void interrupt(); Thread 객체가 가리키는 쓰레드를 interrupt하는 동작 해당 쓰레드가 Object 객체의 wait이나, Thread 객체의 sleep, join 등 을 수행 중이었으면 InterruptedException이 발생되고 해당 쓰레드의 interrupted 플래그가 clear 다른 blocking operation이 진행 중이었으면 interrupted 플래그가 set blocking op가 interruptible channel이었으면 바로 종료하면서 ClosedByInterruptedException를 리턴하나(이 경우에도 flag는 set), 그렇지 않은 경우는 플래그만 바뀐 채 계속 block되어 있음 15 1513년 10월 10일 목
  • 16. interrupt 상태 체크 java.lang.Thread의 다음 두 메소드 동작이 다름 public static boolean interrupted(); 현재 실행 쓰레드의 interrupted 플래그를 알려주고 reset public boolean isInterrupted(); Thread 객체가 가리키는 쓰레드의 현재 interrupted 플 래그를 알려줌 16 1613년 10월 10일 목
  • 17. Thread 상태 (JDK 5) NEW : start 호출 전 RUNNABLE : run 실행 상태 BLOCKED : synchronized lock을 기다리는 상태 WAITING : Object.wait, Thread.join 혹은 LockSupport.park를 실행 중인 상태 TIMED_WAITING : time 인자를 줘서 wait, join, park를 실행하였 거나 Thread.sleep을 실행 중인 상태 TERMINATED : thread가 종료한 상태 17 1713년 10월 10일 목
  • 18. ContextClassLoader? public ClassLoader getContextClassLoader(); public void setContextClassLoader(ClassLoader cl); 쓰레드별로 특별한 의미를 가진 classloader를 지정하기 위함 쓰레드를 만들 때 creator thread로부터 상속받음 main thread의 context classloader는 null 같은 로직을 수행하는 worker thread들(thread pool)을 고려한 API Java EE 환경에서 주로 많이 사용 18 1813년 10월 10일 목
  • 19. Locks and Conditions synchronized block (or method) monitor object lock/unlock의 대상 개념 모든 객체가 monitor가 될 수 있음 java.lang.Object의 wait, notify, notifyAll lock을 획득한 monitor 객체에 대해 condition 기능 사 용하는 API 19 1913년 10월 10일 목
  • 20. spurious wakeup Object.wait A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup 예를 들어 내부적으로 signal handler 루틴 내에서 system call 을 처리하는 중에 전달된 notify를 놓칠 수가 있으므로 kernel 내부에서 다시 wait하는 형태로 처리할 수가 없다. 항상 user code에서 spurious wakeup의 가능성을 고려하 여 guarded condition을 체크하는 loop 안에서 wait해야 20 2013년 10월 10일 목
  • 21. notify/notifyAll Notify Wake up only one thread if any was waiting less overhead (better performance) Applicable on limited cases NotifyAll All the waiting threads can check its guard condition waiting thread들이 많을 때엔 큰 오버헤드 21 2113년 10월 10일 목
  • 22. Hotspot JVM에서 lock 구현 2-word object header (array인 경우는 3-word) 1st word : mark word used by sync and gc, caches hashCode 2bit를 sync state로 사용 (monitor object) 01 unlocked, 00 light-weight locked, 10 heavy-weight locked, 11 marked for GC 2nd word : metadata word 22 2213년 10월 10일 목
  • 23. Hotspot JVM에서 lock 구현 CAS를 사용한 lightweight lock 1. 먼저 mark word를 execution stack의 lock record에 copy한다 2. AtomicCAS를 사용하여 mark word를 stack에 copy된 주소 pointer로 변경 한다. 3. 성공하면 이 object가 해당 execution thread의 lock monitor가 됨 4. 실패하면 (contention이 생길 때) heavyweight lock 시도 unlock 1. lock record에 mark word를 object의 word로 CAS recursive lock : lock record에 0을 저장 23 2313년 10월 10일 목
  • 24. Hotspot JVM에서 lock 구현 CAS latency를 줄이기 위한 biased locking도 현재 버전에 구현 하나의 object가 하나의 thread의 monitor로 사용될 경우 atomic CAS 없이 lock, unlock을 수행할 수 있는 알고리즘. 즉, 같은 쓰레드가 reacquire할 때를 위한 optimization mark word에 앞의 2bit 외에 1bit를 추가적으로 사용 001 => unlocked 101 => biased or biasable (thread ID == 0 == unlocked) Bias obtained via CAS Subsequent locks / unlocks by owner very cheap Test-and-branch, no atomics 24 2413년 10월 10일 목
  • 25. park/unpark 모델 (JDK 5) java.util.concurrent.locks.LockSupport public static void park(); blocks current thread if unpark is not (yet) called or until unpark is called parked thread can be spuriously waken and can be waken by interrupt() call public static void unpark(Thread thread); unblock currently parked thread. multiple unpark doesn’t count but the unparked state is remembered 25 2513년 10월 10일 목
  • 26. Java Memory Model Atomicity Java에서 long과 double을 제외한 모든 data field에 대한 update는 atomic volatile로 선언되면 모든 field update가 atomic Visibility 한 쓰레드에서 이루어진 data field update를 다른 쓰레드에서 보는 걸 보장하려면 (1) 두 쓰레드가 lock을 공유하거나 (2) 해당 필드가 volatile로 선언되거나 (3) 읽는 쓰레드가 해당 필드를 처음 접근 할 때 한 쓰레드가 종료할 때에는 메모리에 flush가 되므로 Thread.join을 통해 기다리는 쓰레드는 해당 종료 쓰레드의 write를 모두 읽을 수 있다. Ordering lock 혹은 volatile을 제외하면 컴파일러에 의해 어떤 reordering도 가능 (물론 같은 쓰레드 내에서 는 동일한 효과가 있어야 함) 26 2613년 10월 10일 목
  • 27. volatile Java Memory Model (JSR-133)에 의하면 같은 volatile 필드에 접근하는 서로 다 른 쓰레드들 간에서 happens-before 관계가 성립해야 함 (visibility, ordering 보장) volatile 필드에 write하면 해당 쓰레드의 모든 변수들을 flush하는 효과가 있어야 하며 (sync 블럭을 벗어날때와 동일) volatile 필드에 read할 때에도 cache 값이 invalidate되어야 한다 (sync 블럭을 시작할 때와 동일) JVM은 volatile을 monitor와 마찬가지로 barrier를 사용해서 구현 (memory 변수로 구현해서는 JMM을 위반하게 된다) 실제 구현은 앞 op가 write 이고 다음 op가 read일 경우에만 mfence (x86) 등의 instruction으로 구현할 수 있다. (다른 case는 x86에서는 no-op) 27 2713년 10월 10일 목
  • 28. volatile 예제 int x = 0; volatile boolean v = false; public void writer() { // Thread t1 x = 42; v = true; } public void reader() { // Thread t2 if (v == true) { // uses x - guaranteed to see 42 (not 0!) }} 28 2813년 10월 10일 목
  • 29. Double-checked Locking 엄격해진 JMM의 volatile 정의로 DCL이 동작 private static volatile Something instance = null; public Something getInstance() { if (instance == null) { synchronized (this) { if (instance == null) instance = new Something(); } } return instance; } 29 Lazy Initialization Holder를 사용하면 volatile도 불필요 (static field는 visibility가 보 장) private static class LazySomethingHolder { public static Something something = new Something(); } public static Something getInstance() { return LazySomethingHolder.something; } 2913년 10월 10일 목
  • 30. final field final field cannot be modified once it has been initialized final fields are initialized in its constructor or its initializer correct value of any final fields will be visible to other threads without synchronization if constructor follows a rule rule : the this reference must not be released from the constructor before the constructor returns 즉, final field 값이 될 객체가 생성자가 리턴하기 전에 이 필드를 액세스하면 초기화되기 전의 값이 보인다. final static field나 final method는 컴파일러가 optimize할 여지가 많지만 final field는 별로 그렇지 않다. (초기화 시 컴파일러가 reordering 제약만 적용) 30 3013년 10월 10일 목
  • 31. ThreadLocal thread 객체에 threadLocals라는 ThreadLocalMap을 들고 있음 (since JDK 1.5) 별도의 Overhead는 없으며, access할 때에도 lock을 전혀 쓰지 않음 WeakReference를 쓰고 있어서 Memory 부족 현상이 있을 때 정보가 소실될 수 있음 InheritedThreadLocal thread 객체에 inheritableThreadLocals라는 ThreadLocalMap을 들고 있음 생성할 때 parent thread의 inheritableThreadLocals 정보를 모두 복사하여 child의 inherited thread local에 넣어줌 parent의 것이 동적으로 반영되지는 않음 (생성 시에 복사로 상속) 31 3113년 10월 10일 목
  • 32. 다음 시간 예정 java.util.concurrent Atomic CAS AbstractQueueSynchronizer, Lock & Condition Concurrent Collections Fork-Join framework 32 3213년 10월 10일 목