2013-03-24 3 views
1

synchronized은 뮤텍스 종류의 것들을 처리하기 위해 Java에서 사용됩니다. 그러나 Lock 인터페이스 (예 : ReentrantLock)의 구현은 Java에서이 키워드를 사용하지 않습니다. 모든 코드는 정상적인 코드로 보입니다. 그렇다면 지구상의 여러 스레드를 어떻게 처리합니까?Java lock 구현에 synchronized 키워드가 사용되지 않는 이유는 무엇입니까?

은 다음 코드 조각이 관련되어 믿을 :

ReentrantLock

protected final boolean tryAcquire(int acquires) { 
    final Thread current = Thread.currentThread(); 
    int c = getState(); 
    if (c == 0) { 
     if (!hasQueuedPredecessors() && 
      compareAndSetState(0, acquires)) { 
      setExclusiveOwnerThread(current); 
      return true; 
     } 
    } 
    else if (current == getExclusiveOwnerThread()) { 
     int nextc = c + acquires; 
     if (nextc < 0) 
      throw new Error("Maximum lock count exceeded"); 
     setState(nextc); 
     return true; 
    } 
    return false; 
} 

SyncSynctryAcquire 방법은 AbstractQueuedSynchronizer 확장 및 코드 관련 :

final boolean acquireQueued(final Node node, int arg) { 
    boolean failed = true; 
    try { 
     boolean interrupted = false; 
     for (;;) { 
      final Node p = node.predecessor(); 
      if (p == head && tryAcquire(arg)) { 
       setHead(node); 
       p.next = null; // help GC 
       failed = false; 
       return interrupted; 
      } 
      if (shouldParkAfterFailedAcquire(p, node) && 
       parkAndCheckInterrupt()) 
       interrupted = true; 
     } 
    } finally { 
     if (failed) 
      cancelAcquire(node); 
    } 
} 

그래서 더 보인다 synchronized 키워드를 사용하면 음소거가 어떻게 보장됩니까? 엑스?

답변

4

Java 1.5 (?)부터 Compare-And-Swap 메서드를 사용하여 하드웨어 잠금을위한 JVM 지원이 있습니다. 이것이 호출 될 때까지 소스를 따라 가십시오.

또한 더 나은 이해를 위해 더그 레아의 논문을 참조하십시오 http://gee.cs.oswego.edu/dl/papers/aqs.pdf

+0

네를. 그것을 발견하고 네이티브 키워드를 가지고 있습니다. 그래서 해당 코드는 실제로 java가 아닙니다. – NSF

+1

JVM이 작성된 코드에 있습니다. Oracle의 경우 C++이고, IBM의 경우 Java 자체 :-) – Sebastian

+0

Gotcha. 감사. – NSF

관련 문제