samples/deadlock/test/org/apidesign/deadlock/SynchronizedFieldsInternallyTest.java
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/samples/deadlock/test/org/apidesign/deadlock/SynchronizedFieldsInternallyTest.java Sat Jun 14 09:54:28 2008 +0200
1.3 @@ -0,0 +1,46 @@
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 SynchronizedFieldsInternallyTest {
1.10 + public SynchronizedFieldsInternallyTest() {
1.11 + }
1.12 +
1.13 + @Test
1.14 + public void increment() {
1.15 + SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
1.16 + instance.increment();
1.17 + }
1.18 +
1.19 + @Test
1.20 + public void unsafeDecrement() {
1.21 + SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
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 + SynchronizedFieldsInternally instance = new SynchronizedFieldsInternally();
1.36 + try {
1.37 + synchronized (instance) {
1.38 + instance.unsafeDecrement();
1.39 + }
1.40 + } catch (AssertionError ex) {
1.41 + // OK
1.42 + return;
1.43 + }
1.44 + fail("Unlike the SynchronizedFieldsTest, the fix by wrapping instance" +
1.45 + "into own synchronized block will not help, neither any other" +
1.46 + "fix, the lock is really private"
1.47 + );
1.48 + }
1.49 +}
1.50 \ No newline at end of file