1 5 package org.h2.test.unit; 6 7 import java.io.File ; 8 9 import org.h2.message.TraceSystem; 10 import org.h2.store.FileLock; 11 import org.h2.test.TestBase; 12 import org.h2.util.FileUtils; 13 14 15 18 public class TestFileLock extends TestBase implements Runnable { 19 20 int wait; 21 static final int KILL = 10; 22 static final String FILE = BASE_DIR + "/test.lock"; 23 24 private boolean allowSockets; 25 private static volatile int locks; 26 private static volatile boolean stop; 27 28 public TestFileLock() {} 29 30 public void test() throws Exception { 31 new File (FILE).delete(); 32 int threadCount = getSize(3, 5); 33 wait = getSize(20, 200); 34 Thread [] threads = new Thread [threadCount]; 35 for (int i = 0; i < threadCount; i++) { 36 threads[i] = new Thread (new TestFileLock(this, false)); 37 threads[i].start(); 38 Thread.sleep(wait + (int) (Math.random() * wait)); 39 } 40 trace("wait"); 41 Thread.sleep(100); 42 stop = true; 43 trace("STOP file"); 44 for (int i = 0; i < threadCount; i++) { 45 threads[i].join(); 46 } 47 check(locks, 0); 48 FileUtils.delete(FILE); 49 stop = false; 50 for (int i = 0; i < threadCount; i++) { 51 threads[i] = new Thread (new TestFileLock(this, true)); 52 threads[i].start(); 53 Thread.sleep(wait + (int) (Math.random() * wait)); 54 } 55 trace("wait"); 56 Thread.sleep(100); 57 stop = true; 58 trace("STOP sockets"); 59 for (int i = 0; i < threadCount; i++) { 60 threads[i].join(); 61 } 62 check(locks, 0); 63 } 64 65 TestBase base; 66 67 TestFileLock(TestBase base, boolean allowSockets) { 68 this.base = base; 69 this.allowSockets = allowSockets; 70 } 71 72 public void run() { 73 while (!stop) { 74 FileLock lock = new FileLock(new TraceSystem(null), 100); 75 try { 76 lock.lock(FILE, allowSockets); 77 base.trace(lock + " locked"); 78 locks++; 79 if (locks > 1) { 80 System.err.println("ERROR! LOCKS=" + locks); 81 stop = true; 82 } 83 Thread.sleep(wait + (int) (Math.random() * wait)); 84 locks--; 85 if ((Math.random() * 50) < KILL) { 86 base.trace(lock + " kill"); 87 lock = null; 88 System.gc(); 89 } else { 90 base.trace(lock + " unlock"); 91 lock.unlock(); 92 } 93 if (locks < 0) { 94 System.err.println("ERROR! LOCKS=" + locks); 95 stop = true; 96 } 97 } catch (Exception e) { 98 } 100 try { 101 Thread.sleep(wait + (int) (Math.random() * wait)); 102 } catch (InterruptedException e1) { 103 } 105 } 106 } 107 108 } 109 | Popular Tags |