1 package org.jboss.cache.lock; 2 3 import EDU.oswego.cs.dl.util.concurrent.ReadWriteLock; 4 import EDU.oswego.cs.dl.util.concurrent.ReentrantWriterPreferenceReadWriteLock; 5 import junit.framework.Test; 6 import junit.framework.TestCase; 7 import junit.framework.TestSuite; 8 9 14 public class ReadWriteLockTest extends TestCase { 15 ReadWriteLock lock; 16 Exception ex=null; 17 18 19 protected void setUp() throws Exception { 20 super.setUp(); 21 ex=null; 22 } 23 24 protected void tearDown() throws Exception { 25 super.tearDown(); 26 lock=null; 27 if(ex != null) 28 throw ex; 29 } 30 31 32 public void testMoreWriteReleasesThanAcquisitions() throws InterruptedException { 33 lock=new ReentrantWriterPreferenceReadWriteLock(); 34 lock.writeLock().acquire(); 35 lock.writeLock().release(); 36 lock.writeLock().release(); 37 } 38 39 public void testMoreReadReleasesThanAcquisitions() throws InterruptedException { 40 lock=new ReentrantWriterPreferenceReadWriteLock(); 41 lock.readLock().acquire(); 42 lock.readLock().release(); 43 try { 44 lock.readLock().release(); 45 fail("read locks cannot be released more than acquired"); 46 } 47 catch(IllegalStateException illegalStateEx) { 48 49 } 50 } 51 52 public void testSimple() throws InterruptedException { 53 lock=new ReentrantWriterPreferenceReadWriteLock(); 54 lock.readLock().acquire(); 55 lock.readLock().acquire(); 56 lock.writeLock().acquire(); 57 lock.writeLock().acquire(); 58 } 59 60 61 public void testOneWriterMultipleReaders() throws InterruptedException { 62 lock=new ReentrantWriterPreferenceReadWriteLock(); 63 64 Writer writer=new Writer("writer"); 65 Reader reader1=new Reader("reader1"); 66 Reader reader2=new Reader("reader2"); 67 68 writer.start(); 69 reader1.start(); 70 reader2.start(); 71 72 writer.join(); 73 reader1.join(); 74 reader2.join(); 75 } 76 77 class Writer extends Thread { 78 79 public Writer(String name) { 80 super(name); 81 } 82 83 public void run() { 84 try { 85 log("acquiring WL"); 86 lock.writeLock().acquire(); 87 log("acquired WL successfully"); 88 sleep(1000); 89 } 90 catch(InterruptedException e) { 91 ex=e; 92 } 93 finally { 94 log("releasing WL"); 95 lock.writeLock().release(); 96 } 97 } 98 } 99 100 101 class Reader extends Thread { 102 103 public Reader(String name) { 104 super(name); 105 } 106 107 108 public void run() { 109 try { 110 log("acquiring RL"); 111 lock.readLock().acquire(); 112 log("acquired RL successfully"); 113 sleep(500); 114 } 115 catch(InterruptedException e) { 116 ex=e; 117 } 118 finally { 119 log("releasing RL"); 120 lock.readLock().release(); 121 } 122 } 123 } 124 125 static void log(String msg) { 126 System.out.println(Thread.currentThread().getName() + ": " + msg); 127 } 128 129 public static Test suite() { 130 return new TestSuite(ReadWriteLockTest.class); 131 } 132 133 public static void main(String [] args) { 134 junit.textui.TestRunner.run(suite()); 135 } 136 137 } 138 | Popular Tags |