1 package net.sf.openrocket.util;
3 import static org.junit.Assert.*;
5 import org.junit.Before;
8 public class TestMutex {
12 System.setProperty("openrocket.debug.safetycheck", "true");
16 public void testSingleLocking() {
17 SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex();
19 // Test single locking
20 assertNull(m.lockingThread);
23 assertNotNull(m.lockingThread);
24 assertTrue(m.unlock("here"));
29 public void testDoubleLocking() {
30 SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex();
32 // Test double locking
38 assertTrue(m.unlock("bazqux"));
40 assertTrue(m.unlock("foobar"));
45 public void testDoubleUnlocking() {
46 SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex();
47 // Mark error reported to not init exception handler
48 SafetyMutex.ConcreteSafetyMutex.errorReported = true;
51 assertTrue(m.unlock("here"));
52 assertFalse(m.unlock("here"));
57 private volatile int testState = 0;
58 private volatile String failure = null;
61 public void testThreadingErrors() {
62 final SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex();
64 // Initialize and start the thread
65 Thread thread = new Thread() {
70 // Test locking a locked mutex
73 m.lock("in thread one");
74 failure = "Succeeded in locking a mutex locked by a different thread";
76 } catch (ConcurrencyException e) {
80 // Test unlocking a mutex locked by a different thread
81 if (m.unlock("in thread two")) {
82 failure = "Succeeded in unlocking a mutex locked by a different thread";
86 // Test verifying a locked mutex that already has an error
89 failure = "Succeeded in verifying a mutex locked by a different thread";
91 } catch (ConcurrencyException e) {
95 // Test locking a mutex after it's been unlocked
98 m.lock("in thread three");
101 // Wait for other side to test
108 } catch (Exception e) {
109 failure = "Exception occurred in thread: " + e;
115 thread.setDaemon(true);
122 assertNull("Thread error: " + failure, failure);
129 assertNull("Thread error: " + failure, failure);
133 fail("Succeeded in locking a locked mutex in main thread");
134 } catch (ConcurrencyException e) {
138 // Test unlocking a mutex locked by a different thread
139 assertFalse(m.unlock("here"));
143 fail("Succeeded in verifying a locked mutex in main thread");
144 } catch (ConcurrencyException e) {
150 assertNull("Thread error: " + failure, failure);
153 private void waitFor(int state) {
154 while (testState != state && failure == null) {
157 } catch (InterruptedException e) {
163 public void testBogusMutex() {
164 SafetyMutex m = new SafetyMutex.BogusSafetyMutex();