author | Jaroslav Tulach <jtulach@netbeans.org> |
Sat, 14 Jun 2008 09:54:28 +0200 | |
changeset 103 | e492694451f6 |
permissions | -rw-r--r-- |
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 SynchronizedFieldsTest { |
jtulach@103 | 7 |
public SynchronizedFieldsTest() { |
jtulach@103 | 8 |
} |
jtulach@103 | 9 |
|
jtulach@103 | 10 |
@Test |
jtulach@103 | 11 |
public void increment() { |
jtulach@103 | 12 |
SynchronizedFields instance = new SynchronizedFields(); |
jtulach@103 | 13 |
instance.increment(); |
jtulach@103 | 14 |
} |
jtulach@103 | 15 |
|
jtulach@103 | 16 |
@Test |
jtulach@103 | 17 |
public void unsafeDecrement() { |
jtulach@103 | 18 |
SynchronizedFields instance = new SynchronizedFields(); |
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 |
SynchronizedFields instance = new SynchronizedFields(); |
jtulach@103 | 33 |
synchronized (instance) { |
jtulach@103 | 34 |
// in contract to original "Monitors", one can "fix" this |
jtulach@103 | 35 |
// problem from outside by using synchronizing externally |
jtulach@103 | 36 |
instance.unsafeDecrement(); |
jtulach@103 | 37 |
} |
jtulach@103 | 38 |
} |
jtulach@103 | 39 |
} |