samples/deadlock/src/org/apidesign/deadlock/SynchronizedFieldsInternally.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:54:28 +0200
changeset 103 e492694451f6
permissions -rw-r--r--
Deadlocks on this and internal lock explained
jtulach@103
     1
package org.apidesign.deadlock;
jtulach@103
     2
jtulach@103
     3
public final class SynchronizedFieldsInternally {
jtulach@103
     4
    // BEGIN: deadlock.ownLock
jtulach@103
     5
    private final Object LOCK = new Object();
jtulach@103
     6
    private int counter;
jtulach@103
     7
    
jtulach@103
     8
    private int getCounter() {
jtulach@103
     9
        assert Thread.holdsLock(LOCK);
jtulach@103
    10
        return counter;
jtulach@103
    11
    } 
jtulach@103
    12
    
jtulach@103
    13
    private void setCounter(int c) {
jtulach@103
    14
        assert Thread.holdsLock(LOCK);
jtulach@103
    15
        counter = c;
jtulach@103
    16
    }
jtulach@103
    17
    // END: deadlock.ownLock
jtulach@103
    18
    
jtulach@103
    19
    
jtulach@103
    20
    public void increment() {
jtulach@103
    21
        synchronized (LOCK) {
jtulach@103
    22
            setCounter(getCounter() + 1);
jtulach@103
    23
        }
jtulach@103
    24
    }
jtulach@103
    25
    
jtulach@103
    26
    public void unsafeDecrement() {
jtulach@103
    27
        setCounter(getCounter() - 1);
jtulach@103
    28
    }
jtulach@103
    29
}