2015-01-14 2 views
6

존재하지 않지만이 구문과 비슷한 것을 찾고 있습니다.Java에서 객체 동기화

메서드를 컬렉션에 적용하고 메서드 수명 동안 컬렉션이 엉망이되지 않도록해야합니다.

그래서 같이 수 :

private void synchronized(collectionX) doSomethingWithCollectionX() { 
    // do something with collection x here, method acquires and releases lock on 
    // collectionX automatically before and after the method is called 
} 

대신, 나는이 될 것이라고 할 수있는 유일한 방법은 두려워 :

private void doSomethingWithTheCollectionX(List<?> collectionX) { 
    synchronized(collectionX) { 
     // do something with collection x here 
    } 
} 

이 가장 좋은 방법은 그것을 할인가요?

+0

, 여기에 유일한 차이점은 들여 쓰기 수준이다. – Radiodef

답변

4

입니다. 당신이 this 것보다 다른 인스턴스에서 동기화 할 경우 다른 선택의 여지가 있지만, 방법 내부 synchronized 블록 선언이없는, 그래서

private myMethod() { 
    synchronized(this) { 
     // do work 
    } 
} 

:

private synchronized myMethod() { 
    // do work 
} 

은 동일합니다.

4

이 경우 동기화 된 목록을 사용하는 것이 좋을 것이다 :

List<X> list = Collections.synchronizedList(new ArrayList<X>()); 

콜렉션 API는 스레드 안전을 위해 synchronized wrapper collections 제공합니다.

메서드 본문의 목록에서 동기화하면 메서드의 전체 수명 동안 목록에 액세스해야하는 다른 스레드가 차단됩니다.

대안은 수동으로 목록에 대한 모든 액세스에 동기화됩니다 : 제가 질문을 오해하고있어 않는

private void doSomethingWithTheCollectionX(List<?> collectionX){ 
    ... 
    synchronized(collectionX) { 
     ... e.g. adding to the list 
    } 

    ... 

    synchronized(collectionX) { 
     ... e.g. updating an element 
    } 

}