The Java™ Tutorials - Concurrency: Intrinsic Locks and Synchronization 내장 자물쇠 와 동기 화

The Java™ Tutorials - Concurrency: Intrinsic Locks and Synchronization 내장 자물쇠 와 동기 화
원본 주소:https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
포인트
동기 화 실현 원리: 동기 화 는 내 장 된 자물쇠 나 감시 자물쇠 라 는 내 장 된 대상 을 통 해 이 루어 진다 .
synchronized 키 워드 를 대상 으로 잠 그 고 동시성 향상 동기 화 가능: 같은 자 물 쇠 를 사용 하 는 동기 화 코드 블록 을 다른 동기 화 코드 블록 으로 호출 할 수 있 습 니 다 하나의 스 레 드 가 동기 화 방법 을 호출 했 을 때 이 방법 대상 의 내 장 된 자 물 쇠 를 자동 으로 가 져 오고 방법 이 돌아 온 후에 이 자 물 쇠 를 자동 으로 방출 합 니 다.
전문 번역
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a “monitor.”) Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object’s state and establishing happens-before relationships that are essential to visibility.
동기 화 는 내 장 된 자물쇠 나 감시 자물쇠 라 는 내 장 된 대상 을 통 해 이 루어 집 니 다.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object’s fields has to acquire the object’s intrinsic lock before accessing them, and then release the intrinsic lock when it’s done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
대상 마다 내 장 된 자물쇠 가 설치 되 어 있 습 니 다. 관례 에 따라 대상 을 지속 적 으로 독점 적 으로 방문 해 야 하 는 스 레 드 는 방문 전에 대상 의 내 장 된 자 물 쇠 를 얻 고 방문 이 끝 난 후에 자 물 쇠 를 풀 어야 합 니 다. 스 레 드 는 내 장 된 자 물 쇠 를 가지 고 있 습 니 다. 이 자 물 쇠 를 얻 고 방출 하 는 시간 대 에 말 합 니 다. 대상 이 내 장 된 자 물 쇠 를 얻 으 면 다른 스 레 드 는 내 장 된 자 물 쇠 를 풀 수 없습니다.같은 자 물 쇠 를 가 져 옵 니 다. 다른 스 레 드 가 이 자 물 쇠 를 가 져 오 려 고 시도 할 때 이 스 레 드 는 막 힙 니 다.
When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.
하나의 스 레 드 가 내 장 된 자 물 쇠 를 풀 었 을 때 선행 관 계 는 이 동작 과 이 자물쇠 에 관 한 다음 작업 사이 에 세 워 졌 습 니 다.
Locks In Synchronized Methods 동기 화 방법의 잠 금
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method’s object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
스 레 드 가 동기 화 방법 을 호출 했 을 때 이 방법 대상 의 내 장 된 자 물 쇠 를 자동 으로 가 져 오고 방법 이 돌아 온 후에 이 자 물 쇠 를 자동 으로 방출 합 니 다. 방법 이 이상 을 포착 하지 못 해 돌아 올 때 스 레 드 도 이 자 물 쇠 를 방출 합 니 다.
You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class’s static fields is controlled by a lock that’s distinct from the lock for any instance of the class.
정적 동기 화 방법 을 호출 했 을 때 무슨 일이 일어 날 지 곤 혹 스 러 울 수 있 습 니 다. 정적 방법 은 대상 이 아 닌 모든 것 이기 때문에 이 경우 스 레 드 는 이러한 클 라 스 대상 의 내 장 된 자 물 쇠 를 가 져 옵 니 다. 따라서 정적 변수 에 대한 접근 은 하나의 자 물 쇠 를 통 해 제 어 됩 니 다. 이 자 물 쇠 는 각 대상 의 자물쇠 와 다 릅 니 다.
Synchronized Statements 동기 화 문
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:
또 다른 동기 코드 를 만 드 는 방식 은 동기 화 문 구 를 이용 하 는 것 입 니 다. 동기 화 방법 이 다 르 면 동기 화 문 구 는 내 장 된 자 물 쇠 를 제공 하 는 대상 을 만들어 야 합 니 다.
public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++;
}
nameList.add(name);
}

In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects’ methods. (Invoking other objects’ methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.
이 예 에서 이 addName 방법 은 lastName 과 nameCount 를 동기 적 으로 바 꿔 야 하지만 이 대상 의 다른 방법 에 대한 동기 화 호출 도 피해 야 합 니 다. (동기 코드 블록 에서 다른 대상 을 호출 하 는 방법 은 '활약 도' 장 에서 토론 할 수 있 습 니 다). 동기 화 문구 가 없 으 면 위의 두 가지 목적 은 단계별 로 진행 되 어야 합 니 다. namelist. add 라 는 목적 을 호출 하기 위해 서 는 비동기 화 방법 이 필요 합 니 다.
Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there’s no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.
동기 화 문 구 는 보다 세밀 한 병발 에 도 효과 가 있 습 니 다. 예 를 들 어 MsLunch 류 에 c1 과 c2 의 두 변수 가 있 고 함께 사용 되 지 않 았 다 면 모든 변수 에 대한 업데이트 작업 은 동기 화 되 어야 하지만 c1 과 c2 의 교차 업 데 이 트 를 막 을 이유 가 없습니다. 막 으 면 불필요 한 차단 을 만들어 병발 로 이 어 집 니 다.성의 저하. 동기 화 방법 을 사용 하지 않 고 이와 관련 된 자 물 쇠 를 사용 하지 않 는 상황 에서 우 리 는 두 개의 대상 을 만들어 각각 자 물 쇠 를 제공 합 니 다.
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();

public void inc1() {
synchronized(lock1) {
c1++;
}
}

public void inc2() {
synchronized(lock2) {
c2++;
}
}

Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access of the affected fields.
이 방법 을 사용 하 십시오. 선택 한 변수 에 대한 교차 접근 이 충분히 안전 하 다 는 것 을 보증 해 야 합 니 다.
Reentrant Synchronization 은 동기 화 에 다시 들 어 갈 수 있 습 니 다.
Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.
하나의 스 레 드 는 다른 스 레 드 가 가지 고 있 는 자 물 쇠 를 가 져 올 수 없습니다. 그러나 하나의 스 레 드 는 이미 가지 고 있 는 자 물 쇠 를 가 져 올 수 있 습 니 다. 하나의 스 레 드 가 같은 자 물 쇠 를 여러 번 가 져 올 수 있 도록 해 줍 니 다. 동기 화 코드 블록 은 다른 동기 화 코드 블록 을 포함 하 는 방법 을 직접 또는 간접 적 으로 호출 할 수 있 습 니 다.그리고 이 두 동기 코드 블록 은 모두 같은 자 물 쇠 를 사 용 했 습 니 다. 동기 화 에 다시 들 어 갈 수 없 으 면 동기 코드 블록 은 하나의 스 레 드 가 자기 호출 로 인해 막 히 는 것 을 방지 하 는 추가 조 치 를 취해 야 합 니 다.

좋은 웹페이지 즐겨찾기