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
     1 package org.apidesign.deadlock;
     2 
     3 import org.junit.Test;
     4 import static org.junit.Assert.*;
     5 
     6 public class SynchronizedFieldsInternallyTest {
     7     public SynchronizedFieldsInternallyTest() {
     8     }
     9 
    10     @Test
    11     public void increment() {
    12         SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
    13         instance.increment();
    14     }
    15 
    16     @Test
    17     public void unsafeDecrement() {
    18         SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
    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         SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
    33         try {
    34             synchronized (instance) {
    35                 instance.unsafeDecrement();
    36             }
    37         } catch (AssertionError ex) {
    38             // OK
    39             return;
    40         }
    41         fail("Unlike the SynchronizedFieldsTest, the fix by wrapping instance" +
    42             "into own synchronized block will not help, neither any other" +
    43             "fix, the lock is really private"
    44         );
    45     }
    46 }