samples/deadlock/test/org/apidesign/deadlock/SynchronizedFieldsTest.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
     1 package org.apidesign.deadlock;
     2 
     3 import org.junit.Test;
     4 import static org.junit.Assert.*;
     5 
     6 public class SynchronizedFieldsTest {
     7     public SynchronizedFieldsTest() {
     8     }
     9 
    10     @Test
    11     public void increment() {
    12         SynchronizedFields instance = new SynchronizedFields();
    13         instance.increment();
    14     }
    15 
    16     @Test
    17     public void unsafeDecrement() {
    18         SynchronizedFields instance = new SynchronizedFields();
    19         try {
    20             instance.unsafeDecrement();
    21         } catch (java.lang.AssertionError ex) {
    22             // OK
    23             return;
    24         }
    25         fail("This will fail as unsafeDecrement is not synchronized, and that" +
    26             "is why it cannot access the field using getter and setter"
    27         );
    28     }
    29 
    30     @Test
    31     public void fixUnsafeDecrementFromOutside() {
    32         SynchronizedFields instance = new SynchronizedFields();
    33         synchronized (instance) {
    34             // in contract to original "Monitors", one can "fix" this 
    35             // problem from outside by using synchronizing externally
    36             instance.unsafeDecrement();
    37         }
    38     }
    39 }