PageRenderTime 32ms CodeModel.GetById 10ms app.highlight 16ms RepoModel.GetById 1ms app.codeStats 1ms

/test/kilim/test/TestLock.java

http://github.com/kilim/kilim
Java | 70 lines | 64 code | 6 blank | 0 comment | 5 complexity | ff7b035ffee7ec19f0d5319db7be8ff7 MD5 | raw file
 1package kilim.test;
 2
 3import junit.framework.TestCase;
 4import kilim.ExitMsg;
 5import kilim.ForkJoinScheduler;
 6import kilim.Mailbox;
 7import kilim.Pausable;
 8import kilim.ReentrantLock;
 9import kilim.Scheduler;
10import kilim.Task;
11
12public class TestLock extends TestCase{
13    static int numThreads = 4;
14    static int maxDelay = 30;
15    static int numTasks = 20;
16    static int numIters = 20;
17    static boolean force = false;
18    static boolean preLock = true;
19    static int ratio = 10;
20    static int timeout = maxDelay/ratio*numIters*numTasks/numThreads + maxDelay*numIters;
21    
22    public void testLocks() {
23        Scheduler scheduler = force ? new ForkJoinScheduler(numThreads) : Scheduler.getDefaultScheduler();
24        Mailbox<ExitMsg> mb = new Mailbox<ExitMsg>();
25        for (int i = 0; i < numTasks; i++) {
26            Task t = new LockTask();
27            t.informOnExit(mb);
28            t.setScheduler(scheduler);
29            t.start();
30        }
31        boolean ok = true;
32        for (int i = 0; i < numTasks; i++) {
33            ExitMsg em = mb.getb(timeout);
34            assertNotNull("Timed out. #tasks finished = " + i + " of " + numTasks, em);
35            if (em.result instanceof Exception) {
36                ok = false; break;
37            }
38        }
39        scheduler.shutdown();
40        assertTrue(ok);
41    }
42
43    static void sleep(int delay) {
44        try { Thread.sleep(delay); }
45        catch (InterruptedException ex) {}
46    }
47    
48    static int delay() {
49        return (int) (maxDelay*Math.random());
50    }
51    
52    static class LockTask extends Task {
53        ReentrantLock syncLock = new ReentrantLock();
54        @Override
55        public void execute() throws Pausable, Exception {
56            Task.sleep(delay());
57            if (preLock) syncLock.preLock();
58            try {
59            for (int i = 0; i < numIters; i++) {
60                syncLock.lock();
61                Task.sleep(delay());
62                syncLock.unlock();
63                TestLock.sleep(delay()/ratio);
64            }
65            } catch (Exception e) {
66                e.printStackTrace();
67            }
68        }
69    }
70}