결론:thread safe가 필요할 경우 아래의 패키지를 활용할 것! 

 멀티스레드 동기화 문제에 대한 자바측의 편의 제공 클래스! java.util.concurrent 패키지!

=>한마디로 데이터를 원자적으로 보호한다. (내부적으로 synchrozied 처럼 lock, unlock 래핑한 것인듯.. 
   참조를 보호하는 거야.. reflect가 있으니.. Class 를 Object로 처리 가능할테고.. 아님 말고 -_-;)


패키지 java.util.concurrent.atomic

단일의 변수에 대한 락 프리로 thread 세이프인 프로그래밍을 지원하는 클래스의 소규모의 툴 킷입니다.


************************기타 찌끄레기 방법? 심플하니 좋은건가?********************


멀티쓰레드 환경에서 클래스의 멤버변수를 안전하게 사용하기 위해서 사용하는 방법이 sychronized 블록을 사용하거나, 변수를 volatile로 선언하는 방식이 있습니다. 두 방식의 차이에 대해 알아보았습니다.

 

Question of the month: Volatile vs. Synchronized re-visited

 

먼저 각각의 방식에 대한 한 쓰레드에서 처리 방식을 살펴보면 다음과 같습니다.

 

volatile

synchronized

Get a global lock on the variableGet a global lock on the monitor
Update the one variable from main memoryUpdate all shared variables that have been accessed from main memory
Process some statements
Write any change of the one variable back to main memoryWrite all shared variables that have been changed back to main memory
Release the lockRelease the lock

 

여기에서 알 수 있듯이 volatile이 선언되지 않은 멤버변수는 sychronized 블록이 아닌 곳에서 사용할 경우, 쓰레드가 변수값들을 복사해서 사용하기 때문에 다른 쓰레드에서 값을 변경했을 경우 같은 변수임에도 불구하고 실제와 다른 값을 읽을 수 있다는 것입니다.

 

Use Synchronized or Volatile when Accessing Shared Variables

 

각각의 방식의 장단점을 살펴보면 다음과 같습니다.

 

TechniqueAdvantagesDisadvantages

synchronized

Private working memory is reconciled with main memory when the lock is obtained and when the lock is released.Eliminates concurrency.

volatile

Allows concurrency.Private working memory is reconciled with main memory on each variable access.


by givingsheart 2014. 1. 1. 16:33