/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

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