samples/deadlock/test/org/apidesign/deadlock/SynchronizedFieldsInternallyTest.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
import org.junit.Test;
jtulach@103
     4
import static org.junit.Assert.*;
jtulach@103
     5
jtulach@103
     6
public class SynchronizedFieldsInternallyTest {
jtulach@103
     7
    public SynchronizedFieldsInternallyTest() {
jtulach@103
     8
    }
jtulach@103
     9
jtulach@103
    10
    @Test
jtulach@103
    11
    public void increment() {
jtulach@103
    12
        SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
jtulach@103
    13
        instance.increment();
jtulach@103
    14
    }
jtulach@103
    15
jtulach@103
    16
    @Test
jtulach@103
    17
    public void unsafeDecrement() {
jtulach@103
    18
        SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
jtulach@103
    19
        try {
jtulach@103
    20
            instance.unsafeDecrement();
jtulach@103
    21
        } catch (java.lang.AssertionError ex) {
jtulach@103
    22
            // OK
jtulach@103
    23
            return;
jtulach@103
    24
        }
jtulach@103
    25
        fail("This will fail as unsafeDecrement is not synchronized, and that" +
jtulach@103
    26
            "is why it cannot access the field using getter and setter"
jtulach@103
    27
        );
jtulach@103
    28
    }
jtulach@103
    29
jtulach@103
    30
    @Test
jtulach@103
    31
    public void fixUnsafeDecrementFromOutside() {
jtulach@103
    32
        SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
jtulach@103
    33
        try {
jtulach@103
    34
            synchronized (instance) {
jtulach@103
    35
                instance.unsafeDecrement();
jtulach@103
    36
            }
jtulach@103
    37
        } catch (AssertionError ex) {
jtulach@103
    38
            // OK
jtulach@103
    39
            return;
jtulach@103
    40
        }
jtulach@103
    41
        fail("Unlike the SynchronizedFieldsTest, the fix by wrapping instance" +
jtulach@103
    42
            "into own synchronized block will not help, neither any other" +
jtulach@103
    43
            "fix, the lock is really private"
jtulach@103
    44
        );
jtulach@103
    45
    }
jtulach@103
    46
}