1 package net.sf.openrocket.util;
3 import static org.junit.Assert.*;
7 public class TestMutex {
10 public void testSingleLocking() {
11 SafetyMutex m = new SafetyMutex();
13 // Test single locking
14 assertNull(m.lockingThread);
17 assertNotNull(m.lockingThread);
18 assertTrue(m.unlock("here"));
23 public void testDoubleLocking() {
24 SafetyMutex m = new SafetyMutex();
26 // Test double locking
32 assertTrue(m.unlock("bazqux"));
34 assertTrue(m.unlock("foobar"));
39 public void testDoubleUnlocking() {
40 SafetyMutex m = new SafetyMutex();
41 // Mark error reported to not init exception handler
42 SafetyMutex.errorReported = true;
45 assertTrue(m.unlock("here"));
46 assertFalse(m.unlock("here"));
51 private volatile int testState = 0;
52 private volatile String failure = null;
55 public void testThreadingErrors() {
56 final SafetyMutex m = new SafetyMutex();
58 // Initialize and start the thread
59 Thread thread = new Thread() {
64 // Test locking a locked mutex
67 m.lock("in thread one");
68 failure = "Succeeded in locking a mutex locked by a different thread";
70 } catch (ConcurrencyException e) {
74 // Test unlocking a mutex locked by a different thread
75 if (m.unlock("in thread two")) {
76 failure = "Succeeded in unlocking a mutex locked by a different thread";
80 // Test verifying a locked mutex that already has an error
83 failure = "Succeeded in verifying a mutex locked by a different thread";
85 } catch (ConcurrencyException e) {
89 // Test locking a mutex after it's been unlocked
92 m.lock("in thread three");
95 // Wait for other side to test
102 } catch (Exception e) {
103 failure = "Exception occurred in thread: " + e;
109 thread.setDaemon(true);
116 assertNull("Thread error: " + failure, failure);
123 assertNull("Thread error: " + failure, failure);
127 fail("Succeeded in locking a locked mutex in main thread");
128 } catch (ConcurrencyException e) {
132 // Test unlocking a mutex locked by a different thread
133 assertFalse(m.unlock("here"));
137 fail("Succeeded in verifying a locked mutex in main thread");
138 } catch (ConcurrencyException e) {
144 assertNull("Thread error: " + failure, failure);
147 private void waitFor(int state) {
148 while (testState != state && failure == null) {
151 } catch (InterruptedException e) {