samples/deadlock/test/org/apidesign/deadlock/SynchronizedFieldsTest.java
changeset 103 e492694451f6
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/samples/deadlock/test/org/apidesign/deadlock/SynchronizedFieldsTest.java	Sat Jun 14 09:54:28 2008 +0200
     1.3 @@ -0,0 +1,39 @@
     1.4 +package org.apidesign.deadlock;
     1.5 +
     1.6 +import org.junit.Test;
     1.7 +import static org.junit.Assert.*;
     1.8 +
     1.9 +public class SynchronizedFieldsTest {
    1.10 +    public SynchronizedFieldsTest() {
    1.11 +    }
    1.12 +
    1.13 +    @Test
    1.14 +    public void increment() {
    1.15 +        SynchronizedFields instance = new SynchronizedFields();
    1.16 +        instance.increment();
    1.17 +    }
    1.18 +
    1.19 +    @Test
    1.20 +    public void unsafeDecrement() {
    1.21 +        SynchronizedFields instance = new SynchronizedFields();
    1.22 +        try {
    1.23 +            instance.unsafeDecrement();
    1.24 +        } catch (java.lang.AssertionError ex) {
    1.25 +            // OK
    1.26 +            return;
    1.27 +        }
    1.28 +        fail("This will fail as unsafeDecrement is not synchronized, and that" +
    1.29 +            "is why it cannot access the field using getter and setter"
    1.30 +        );
    1.31 +    }
    1.32 +
    1.33 +    @Test
    1.34 +    public void fixUnsafeDecrementFromOutside() {
    1.35 +        SynchronizedFields instance = new SynchronizedFields();
    1.36 +        synchronized (instance) {
    1.37 +            // in contract to original "Monitors", one can "fix" this 
    1.38 +            // problem from outside by using synchronizing externally
    1.39 +            instance.unsafeDecrement();
    1.40 +        }
    1.41 +    }
    1.42 +}
    1.43 \ No newline at end of file