/** compareAndSet in one thread enables another waiting for value to succeed */
  public void testCompareAndSetInMultipleThreads() throws Exception {
    x = one;
    final AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer> a;
    try {
      a =
          AtomicReferenceFieldUpdater.newUpdater(
              AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
    } catch (RuntimeException ok) {
      return;
    }

    Thread t =
        new Thread(
            new CheckedRunnable() {
              public void realRun() {
                while (!a.compareAndSet(AtomicReferenceFieldUpdaterTest.this, two, three))
                  Thread.yield();
              }
            });

    t.start();
    assertTrue(a.compareAndSet(this, one, two));
    t.join(LONG_DELAY_MS);
    assertFalse(t.isAlive());
    assertSame(a.get(this), three);
  }
  /** awaitUninterruptibly is uninterruptible */
  public void testAwaitUninterruptibly() {
    final Mutex sync = new Mutex();
    final ConditionObject c = sync.newCondition();
    final BooleanLatch pleaseInterrupt = new BooleanLatch();
    Thread t =
        newStartedThread(
            new CheckedRunnable() {
              public void realRun() {
                sync.acquire();
                assertTrue(pleaseInterrupt.releaseShared(0));
                c.awaitUninterruptibly();
                assertTrue(Thread.interrupted());
                assertHasWaitersLocked(sync, c, NO_THREADS);
                sync.release();
              }
            });

    pleaseInterrupt.acquireShared(0);
    sync.acquire();
    assertHasWaitersLocked(sync, c, t);
    sync.release();
    t.interrupt();
    assertHasWaitersUnlocked(sync, c, t);
    assertThreadStaysAlive(t);
    sync.acquire();
    assertHasWaitersLocked(sync, c, t);
    assertHasExclusiveQueuedThreads(sync, NO_THREADS);
    c.signal();
    assertHasWaitersLocked(sync, c, NO_THREADS);
    assertHasExclusiveQueuedThreads(sync, t);
    sync.release();
    awaitTermination(t);
  }
  @SuppressWarnings("deprecation")
  // test explicitly needs to use "stop", which is deprecated
  public static void testCase() {
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  synchronized (o) {
                    in_wait = true;
                    // System.out.println("wait");
                    o.wait(3000); // just a bit
                    in_wait = false;
                  }
                } catch (Exception e) {
                  // System.out.println(Thread.currentThread().getName() + " caught " + e);
                  // e.printStackTrace();
                  in_wait = false;
                }
              }
            });

    t.start();
    while (!in_wait) {} // Lame
    synchronized (o) {
      // System.out.println("stop");
      t.stop();
    }
    try {
      Thread.sleep(8000); // sleep longer than our wait thread
    } catch (Exception e) {
      assertTrue(false);
    }
    assertTrue(in_wait); // if we finished wait, we failed to interrupt
  }
 /** getSharedQueuedThreads returns all shared waiting threads */
 public void testGetSharedQueuedThreads_Shared() {
   final BooleanLatch l = new BooleanLatch();
   assertHasSharedQueuedThreads(l, NO_THREADS);
   Thread t1 =
       newStartedThread(
           new CheckedInterruptedRunnable() {
             public void realRun() throws InterruptedException {
               l.acquireSharedInterruptibly(0);
             }
           });
   waitForQueuedThread(l, t1);
   assertHasSharedQueuedThreads(l, t1);
   Thread t2 =
       newStartedThread(
           new CheckedRunnable() {
             public void realRun() throws InterruptedException {
               l.acquireSharedInterruptibly(0);
             }
           });
   waitForQueuedThread(l, t2);
   assertHasSharedQueuedThreads(l, t1, t2);
   t1.interrupt();
   awaitTermination(t1);
   assertHasSharedQueuedThreads(l, t2);
   assertTrue(l.releaseShared(0));
   awaitTermination(t2);
   assertHasSharedQueuedThreads(l, NO_THREADS);
 }
示例#5
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();
    IO.copy(IO.getFile("testdata/ws"), tmp);
    workspace = Workspace.getWorkspace(tmp);
    workspace.refresh();

    InfoRepository repo = workspace.getPlugin(InfoRepository.class);
    t1 = create("bsn-1", new Version(1, 0, 0));
    t2 = create("bsn-2", new Version(1, 0, 0));

    repo.put(new FileInputStream(t1), null);
    repo.put(new FileInputStream(t2), null);
    t1 = repo.get("bsn-1", new Version(1, 0, 0), null);
    t2 = repo.get("bsn-2", new Version(1, 0, 0), null);
    repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null);

    workspace.getPlugins().add(repo);

    File storage = IO.getFile("generated/storage-1");
    storage.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());

    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2");

    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    context = framework.getBundleContext();
    location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString();
    agent = context.installBundle(location);
    agent.start();

    thread =
        new Thread() {
          @Override
          public void run() {
            try {
              Main.main(
                  new String[] {
                    "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et"
                  });
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    thread.setDaemon(true);
    thread.start();

    super.setUp();
  }
 /** Spin-waits until sync.isQueued(t) becomes true. */
 void waitForQueuedThread(AbstractQueuedLongSynchronizer sync, Thread t) {
   long startTime = System.nanoTime();
   while (!sync.isQueued(t)) {
     if (millisElapsedSince(startTime) > LONG_DELAY_MS)
       throw new AssertionFailedError("timed out");
     Thread.yield();
   }
   assertTrue(t.isAlive());
 }
 /** Checks that the threads do not terminate within the given millisecond delay. */
 void assertThreadsStayAlive(long millis, Thread... threads) {
   try {
     // No need to optimize the failing case via Thread.join.
     delay(millis);
     for (Thread thread : threads) assertTrue(thread.isAlive());
   } catch (InterruptedException ie) {
     fail("Unexpected InterruptedException");
   }
 }
 /**
  * Waits for the specified time (in milliseconds) for the thread to terminate (using {@link
  * Thread#join(long)}), else interrupts the thread (in the hope that it may terminate later) and
  * fails.
  */
 void awaitTermination(Thread t, long timeoutMillis) {
   try {
     t.join(timeoutMillis);
   } catch (InterruptedException ie) {
     threadUnexpectedException(ie);
   } finally {
     if (t.getState() != Thread.State.TERMINATED) {
       t.interrupt();
       fail("Test timed out");
     }
   }
 }
 /**
  * Delays, via Thread.sleep, for the given millisecond delay, but if the sleep is shorter than
  * specified, may re-sleep or yield until time elapses.
  */
 static void delay(long millis) throws InterruptedException {
   long startTime = System.nanoTime();
   long ns = millis * 1000 * 1000;
   for (; ; ) {
     if (millis > 0L) Thread.sleep(millis);
     else // too short to sleep
     Thread.yield();
     long d = ns - (System.nanoTime() - startTime);
     if (d > 0L) millis = d / (1000 * 1000);
     else break;
   }
 }
示例#10
0
  private void beforeFirstTest() {
    if ((ourMode & START_GUARD) != 0) {
      Thread timeAndMemoryGuard =
          new Thread() {
            @Override
            public void run() {
              log("Starting Time and Memory Guard");
              while (true) {
                try {
                  try {
                    Thread.sleep(10000);
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                  }
                  // check for time spent on current test
                  if (myLastTestStartTime != 0) {
                    long currTime = System.currentTimeMillis();
                    long secondsSpent = (currTime - myLastTestStartTime) / 1000L;
                    Thread currentThread = getCurrentThread();
                    if (!mySavingMemorySnapshot) {
                      if (secondsSpent > PlatformTestCase.ourTestTime * myLastTestTestMethodCount) {
                        UsefulTestCase.printThreadDump();
                        log(
                            "Interrupting current Test (out of time)! Test class: "
                                + myLastTestClass
                                + " Seconds spent = "
                                + secondsSpent);
                        myInterruptedByOutOfTime = true;
                        if (currentThread != null) {
                          currentThread.interrupt();
                          if (!currentThread.isInterrupted()) {
                            //noinspection deprecation
                            currentThread.stop(
                                new RuntimeException("Current Test Interrupted: OUT OF TIME!"));
                          }

                          break;
                        }
                      }
                    }
                  }
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
              log("Time and Memory Guard finished.");
            }
          };
      timeAndMemoryGuard.setDaemon(true);
      timeAndMemoryGuard.start();
    }
    myStartTime = System.currentTimeMillis();
  }
示例#11
0
  /*
   * Launches against the agent
   */
  public void testSimpleLauncher() throws Exception {
    Project project = workspace.getProject("p1");
    Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun"));
    bndrun.setProperty("-runpath", "biz.aQute.remote.launcher");
    bndrun.setProperty("-runbundles", "bsn-1,bsn-2");
    bndrun.setProperty("-runremote", "test");

    final RemoteProjectLauncherPlugin pl =
        (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher();
    pl.prepare();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger exitCode = new AtomicInteger(-1);

    List<? extends RunSession> sessions = pl.getRunSessions();
    assertEquals(1, sessions.size());

    final RunSession session = sessions.get(0);

    Thread t =
        new Thread("test-launch") {
          public void run() {
            try {
              exitCode.set(session.launch());
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              latch.countDown();
            }
          }
        };
    t.start();
    Thread.sleep(500);

    for (Bundle b : context.getBundles()) {
      System.out.println(b.getLocation());
    }
    assertEquals(4, context.getBundles().length);
    String p1 = t1.getAbsolutePath();
    System.out.println(p1);

    assertNotNull(context.getBundle(p1));
    assertNotNull(context.getBundle(t2.getAbsolutePath()));

    pl.cancel();
    latch.await();

    assertEquals(-3, exitCode.get());

    bndrun.close();
  }
示例#12
0
 /**
  * Spin-waits up to the specified number of milliseconds for the given thread to enter a wait
  * state: BLOCKED, WAITING, or TIMED_WAITING.
  */
 void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
   long startTime = System.nanoTime();
   for (; ; ) {
     Thread.State s = thread.getState();
     if (s == Thread.State.BLOCKED || s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING)
       return;
     else if (s == Thread.State.TERMINATED) fail("Unexpected thread termination");
     else if (millisElapsedSince(startTime) > timeoutMillis) {
       threadAssertTrue(thread.isAlive());
       return;
     }
     Thread.yield();
   }
 }
  /** tryAcquireNanos is interruptible */
  public void testTryAcquireNanos_Interruptible() {
    final Mutex sync = new Mutex();
    sync.acquire();
    Thread t =
        newStartedThread(
            new CheckedInterruptedRunnable() {
              public void realRun() throws InterruptedException {
                sync.tryAcquireNanos(MILLISECONDS.toNanos(2 * LONG_DELAY_MS));
              }
            });

    waitForQueuedThread(sync, t);
    t.interrupt();
    awaitTermination(t);
  }
示例#14
0
  /*
   * Launches against the agent& main
   */
  public void testAgentAndMain() throws Exception {
    Project project = workspace.getProject("p1");
    Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun"));
    bndrun.setProperty("-runpath", "biz.aQute.remote.launcher");
    bndrun.setProperty("-runbundles", "bsn-1,bsn-2");
    bndrun.setProperty("-runremote", "agent,main;agent=1090");

    final RemoteProjectLauncherPlugin pl =
        (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher();
    pl.prepare();

    List<? extends RunSession> sessions = pl.getRunSessions();
    assertEquals(2, sessions.size());

    RunSession agent = sessions.get(0);
    RunSession main = sessions.get(1);

    CountDownLatch agentLatch = launch(agent);
    CountDownLatch mainLatch = launch(main);

    agent.waitTillStarted(1000);
    main.waitTillStarted(1000);
    Thread.sleep(500);

    agent.cancel();
    main.cancel();

    agentLatch.await();
    mainLatch.await();
    assertEquals(-3, agent.getExitCode());
    assertEquals(-3, main.getExitCode());

    bndrun.close();
  }
示例#15
0
 public void run() {
   try {
     Thread.sleep(MEDIUM_DELAY_MS);
     fail("should throw exception");
   } catch (InterruptedException success) {
   }
 }
 public boolean checkEvents(BundleEvent[] expevents) {
   boolean res = true;
   for (int i = 0; i < 20; i++) {
     try {
       Thread.sleep(100);
     } catch (InterruptedException ignore) {
     }
     if (events.size() == expevents.length) {
       break;
     }
   }
   if (events.size() == expevents.length) {
     for (int i = 0; i < events.size(); i++) {
       BundleEvent be = (BundleEvent) events.elementAt(i);
       if (!(be.getBundle().equals(expevents[i].getBundle())
           && be.getType() == expevents[i].getType())) {
         res = false;
       }
     }
   } else {
     res = false;
   }
   if (!res) {
     out.println("Real events");
     for (int i = 0; i < events.size(); i++) {
       BundleEvent be = (BundleEvent) events.elementAt(i);
       out.println("Event " + be.getBundle() + ", Type " + be.getType());
     }
     out.println("Expected events");
     for (int i = 0; i < expevents.length; i++) {
       out.println("Event " + expevents[i].getBundle() + ", Type " + expevents[i].getType());
     }
   }
   return res;
 }
 /**
  * The AIM server doesn't like it if we change states too often and we use this method to slow
  * things down.
  */
 private void pauseBetweenStateChanges() {
   try {
     Thread.sleep(5000);
   } catch (InterruptedException ex) {
     logger.debug("Pausing between state changes was interrupted", ex);
   }
 }
  public void testEmptyHeader() {
    fFrame = new JFrame("Test Window");

    // Create a panel to hold all other components
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new BorderLayout());

    // Create a new table instance
    MyTableModel myModel = new MyTableModel();
    fTable = new JTable(myModel);

    // Add the table to a scrolling pane
    JScrollPane scrollPane = new JScrollPane(fTable);
    topPanel.add(scrollPane, BorderLayout.CENTER);

    fFrame.getContentPane().setLayout(new BorderLayout());
    fFrame.getContentPane().add(BorderLayout.CENTER, topPanel);

    fFrame.setSize(400, 450);
    fFrame.setLocation(20, 20);
    fFrame.setVisible(true);
    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    JTableHeader header = fTable.getTableHeader();
    assertTrue(
        "JTableHeader greater than 5 pixels tall with empty string first element.",
        header.getSize().height > 5);
    fFrame.setVisible(false);
    fFrame.dispose();
  }
示例#19
0
 public void run() {
   try {
     Thread.sleep(LONG_DELAY_MS);
     done = true;
   } catch (Exception e) {
   }
 }
示例#20
0
 public void run() {
   try {
     Thread.sleep(MEDIUM_DELAY_MS);
   } catch (Exception e) {
     fail("Unexpected exception");
   }
 }
 /** getFirstQueuedThread returns first waiting thread or null if none */
 public void testGetFirstQueuedThread() {
   final Mutex sync = new Mutex();
   assertNull(sync.getFirstQueuedThread());
   sync.acquire();
   Thread t1 = newStartedThread(new InterruptedSyncRunnable(sync));
   waitForQueuedThread(sync, t1);
   assertEquals(t1, sync.getFirstQueuedThread());
   Thread t2 = newStartedThread(new InterruptibleSyncRunnable(sync));
   waitForQueuedThread(sync, t2);
   assertEquals(t1, sync.getFirstQueuedThread());
   t1.interrupt();
   awaitTermination(t1);
   assertEquals(t2, sync.getFirstQueuedThread());
   sync.release();
   awaitTermination(t2);
   assertNull(sync.getFirstQueuedThread());
 }
示例#22
0
 public Object call() {
   try {
     Thread.sleep(SMALL_DELAY_MS);
     done = true;
   } catch (Exception e) {
   }
   return Boolean.TRUE;
 }
示例#23
0
 public Object call() {
   try {
     Thread.sleep(SMALL_DELAY_MS);
   } catch (Exception e) {
     fail("Unexpected exception");
   }
   return Boolean.TRUE;
 }
 /** hasQueuedThreads reports whether there are waiting threads */
 public void testHasQueuedThreads() {
   final Mutex sync = new Mutex();
   assertFalse(sync.hasQueuedThreads());
   sync.acquire();
   Thread t1 = newStartedThread(new InterruptedSyncRunnable(sync));
   waitForQueuedThread(sync, t1);
   assertTrue(sync.hasQueuedThreads());
   Thread t2 = newStartedThread(new InterruptibleSyncRunnable(sync));
   waitForQueuedThread(sync, t2);
   assertTrue(sync.hasQueuedThreads());
   t1.interrupt();
   awaitTermination(t1);
   assertTrue(sync.hasQueuedThreads());
   sync.release();
   awaitTermination(t2);
   assertFalse(sync.hasQueuedThreads());
 }
  /** acquireSharedInterruptibly is interruptible */
  public void testAcquireSharedInterruptibly_Interruptible() {
    final BooleanLatch l = new BooleanLatch();
    Thread t =
        newStartedThread(
            new CheckedInterruptedRunnable() {
              public void realRun() throws InterruptedException {
                assertFalse(l.isSignalled());
                l.acquireSharedInterruptibly(0);
              }
            });

    waitForQueuedThread(l, t);
    assertFalse(l.isSignalled());
    t.interrupt();
    awaitTermination(t);
    assertFalse(l.isSignalled());
  }
 public void run() {
   Configuration conf = new Configuration();
   try {
     conf.setEventManager(new EventManager());
     Thread.sleep(100);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
  public void testInterruptible(final AwaitMethod awaitMethod) {
    final Mutex sync = new Mutex();
    final ConditionObject c = sync.newCondition();
    final BooleanLatch pleaseInterrupt = new BooleanLatch();
    Thread t =
        newStartedThread(
            new CheckedInterruptedRunnable() {
              public void realRun() throws InterruptedException {
                sync.acquire();
                assertTrue(pleaseInterrupt.releaseShared(0));
                await(c, awaitMethod);
              }
            });

    pleaseInterrupt.acquireShared(0);
    t.interrupt();
    awaitTermination(t);
  }
  /** tryAcquireSharedNanos is interruptible */
  public void testTryAcquireSharedNanos_Interruptible() {
    final BooleanLatch l = new BooleanLatch();
    Thread t =
        newStartedThread(
            new CheckedInterruptedRunnable() {
              public void realRun() throws InterruptedException {
                assertFalse(l.isSignalled());
                long nanos = MILLISECONDS.toNanos(2 * LONG_DELAY_MS);
                l.tryAcquireSharedNanos(0, nanos);
              }
            });

    waitForQueuedThread(l, t);
    assertFalse(l.isSignalled());
    t.interrupt();
    awaitTermination(t);
    assertFalse(l.isSignalled());
  }
示例#29
0
  private CountDownLatch launch(final RunSession session) {
    final CountDownLatch latch = new CountDownLatch(1);

    Thread t =
        new Thread("test-launch") {
          public void run() {
            try {
              session.launch();
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              latch.countDown();
            }
          }
        };
    t.start();
    return latch;
  }
 /** getSharedQueuedThreads does not include exclusively waiting threads */
 public void testGetSharedQueuedThreads_Exclusive() {
   final Mutex sync = new Mutex();
   assertTrue(sync.getSharedQueuedThreads().isEmpty());
   sync.acquire();
   assertTrue(sync.getSharedQueuedThreads().isEmpty());
   Thread t1 = newStartedThread(new InterruptedSyncRunnable(sync));
   waitForQueuedThread(sync, t1);
   assertTrue(sync.getSharedQueuedThreads().isEmpty());
   Thread t2 = newStartedThread(new InterruptibleSyncRunnable(sync));
   waitForQueuedThread(sync, t2);
   assertTrue(sync.getSharedQueuedThreads().isEmpty());
   t1.interrupt();
   awaitTermination(t1);
   assertTrue(sync.getSharedQueuedThreads().isEmpty());
   sync.release();
   awaitTermination(t2);
   assertTrue(sync.getSharedQueuedThreads().isEmpty());
 }