public void waitInternal(boolean interrupt) {
    if (queueListener.get() == null) {
      return;
    }
    if (isCurrentThread()) {
      return;
    }

    long MAX_TIMEOUT = 1000 * 10;
    long start = System.currentTimeMillis();

    while (queueListener.get().isRunning()) {
      try {
        TimeUnit.MILLISECONDS.sleep(100);

        Thread thread = queueListener.get().getThread();
        if (interrupt) {
          if (thread != null) {
            thread.interrupt();
          }
        } else if (System.currentTimeMillis() - start > MAX_TIMEOUT) {
          if (thread != null) {
            String msg = "Waited for " + MAX_TIMEOUT + "ms, will now interrupt the thread";
            log.warn(msg);
            thread.interrupt();
            throw new RuntimeException(msg);
          }
        }
      } catch (InterruptedException e) {
        log.trace("Got Interrupted while waiting for tasks.", e);
      }
    }
  }
  /** Run the test for the queue parameter. */
  public static SynchronizedQueueResult testQueue(QueueAdapter<Integer> queue) {
    try {
      mQueue = queue;

      // Please make sure to keep all the "TODO" comments in the
      // code below to make it easy for peer reviewers to find
      // them.

      // TODO - you fill in here to replace the null
      // initialization below to create two Java Threads, one
      // that's passed the producerRunnable and the other that's
      // passed the consumerRunnable.
      Thread consumer = new Thread(consumerRunnable);
      Thread producer = new Thread(producerRunnable);

      // TODO - you fill in here to start the threads. More
      // interesting results will occur if you start the
      // consumer first.
      producer.start();
      consumer.start();

      // Give the Threads a chance to run before interrupting
      // them.
      Thread.sleep(100);

      // TODO - you fill in here to interrupt the threads.
      producer.interrupt();
      consumer.interrupt();

      // TODO - you fill in here to wait for the threads to
      // exit.
      consumer.join();
      producer.join();
      ;

      // Do some sanity checking to see if the Threads work as
      // expected.
      if (consumer == null || producer == null)
        return SynchronizedQueueResult.THREADS_NEVER_CREATED;
      else if (consumer.isAlive() || producer.isAlive())
        return SynchronizedQueueResult.JOIN_NEVER_CALLED;
      else if (mConsumerCounter == 0 || mProducerCounter == 0)
        return SynchronizedQueueResult.THREADS_NEVER_RAN;
      else if (mConsumerCounter == mMaxIterations || mProducerCounter == mMaxIterations)
        return SynchronizedQueueResult.THREADS_NEVER_INTERUPTED;
      else if (mConsumerCounter == FAILURE_OCCURRED || mProducerCounter == FAILURE_OCCURRED)
        return SynchronizedQueueResult.THREADS_THREW_EXCEPTION;
      else if (mConsumerCounter == TIMEOUT_OCCURRED || mProducerCounter == TIMEOUT_OCCURRED)
        return SynchronizedQueueResult.THREADS_TIMEDOUT;
      else return SynchronizedQueueResult.RAN_PROPERLY;
    } catch (Exception e) {
      return SynchronizedQueueResult.TESTING_LOGIC_THREW_EXCEPTION;
    }
  }
  public static void main(String[] args) throws Exception {
    int counter = 0;
    while (true) {
      Thread outThread = null;
      Thread errThread = null;
      try {
        // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange

        // *** start slave

        ServerSocket commSocket = new ServerSocket(0);
        int commPort = commSocket.getLocalPort();
        System.out.println("commPort = " + commPort);

        // org.pitest.mutationtest.execute.MutationTestProcess#start
        //   - org.pitest.util.CommunicationThread#start
        FutureTask<Integer> commFuture = createFuture(commSocket);
        //   - org.pitest.util.WrappingProcess#start
        //       - org.pitest.util.JavaProcess#launch
        Process slaveProcess = startSlaveProcess(commPort);
        outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout");
        errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr");
        outThread.start();
        errThread.start();

        // *** wait for slave to die

        // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie
        //    - org.pitest.util.CommunicationThread#waitToFinish
        System.out.println("waitToFinish");
        Integer controlReturned = commFuture.get();
        System.out.println("controlReturned = " + controlReturned);
        // NOTE: the following won't get called if commFuture.get() fails!
        //    - org.pitest.util.JavaProcess#destroy
        outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        slaveProcess.destroy();
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }

      // test: the threads should exit eventually
      outThread.join();
      errThread.join();
      counter++;
      System.out.println("try " + counter + ": stdout and stderr threads exited normally");
    }
  }
 void stop() {
   stopping = true;
   sinkThread.interrupt();
   try {
     sinkThread.join();
   } catch (InterruptedException e) {
     LOG.warn("Stop interrupted", e);
   }
 }
Example #5
0
 protected void handleInterruptRequest(Address source, long requestId) {
   Owner owner = new Owner(source, requestId);
   Runnable runnable = removeKeyForValue(_running, owner);
   Thread thread = null;
   if (runnable != null) {
     thread = _runnableThreads.remove(runnable);
   }
   if (thread != null) {
     thread.interrupt();
   } else if (log.isTraceEnabled())
     log.trace("Message could not be interrupted due to it already returned");
 }
  @Override
  public void onDestroy() {
    if (AppConfig.DEBUG) Log.d(TAG, "Service shutting down");
    isRunning = false;
    updateReport();

    stopForeground(true);
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancel(NOTIFICATION_ID);

    downloadCompletionThread.interrupt();
    syncExecutor.shutdown();
    schedExecutor.shutdown();
    cancelNotificationUpdater();
    unregisterReceiver(cancelDownloadReceiver);
  }
Example #7
0
  static void test() throws Throwable {
    final ExecutorService executor = Executors.newCachedThreadPool();

    final NotificationReceiver notifiee1 = new NotificationReceiver();
    final NotificationReceiver notifiee2 = new NotificationReceiver();

    final Collection<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
    tasks.add(new BlockingTask(notifiee1));
    tasks.add(new BlockingTask(notifiee2));
    tasks.add(new NonBlockingTask());

    // start a thread to invoke the tasks
    Thread thread =
        new Thread() {
          public void run() {
            try {
              executor.invokeAll(tasks);
            } catch (RejectedExecutionException t) {
              /* OK */
            } catch (Throwable t) {
              unexpected(t);
            }
          }
        };
    thread.start();

    // Wait until tasks begin execution
    notifiee1.waitForNotification();
    notifiee2.waitForNotification();

    // Now try to shutdown the executor service while tasks
    // are blocked.  This should cause the tasks to be
    // interrupted.
    executor.shutdownNow();
    if (!executor.awaitTermination(5, TimeUnit.SECONDS)) throw new Error("Executor stuck");

    // Wait for the invocation thread to complete.
    thread.join(1000);
    if (thread.isAlive()) {
      thread.interrupt();
      thread.join(1000);
      throw new Error("invokeAll stuck");
    }
  }
 public static void main(String[] args) {
   // 3 ways to do it:
   // use Thread:
   Thread t = new Thread(new Worker());
   t.start();
   t.interrupt();
   // use Executor execute:
   ExecutorService exec = Executors.newSingleThreadExecutor();
   exec.execute(new Worker());
   exec.shutdownNow();
   // use Executor submit:
   ExecutorService exec2 = Executors.newSingleThreadExecutor();
   Future<?> f = exec2.submit(new Worker());
   try {
     TimeUnit.MILLISECONDS.sleep(100); // start task
   } catch (InterruptedException e) {
     System.out.println("Sleep interrupted in main()");
   }
   f.cancel(true);
   exec2.shutdown();
 }
Example #9
0
 public void cancel() {
   LOG.debug("Feed cancelled");
   shouldRun = false;
   thread.interrupt();
 }
Example #10
0
 void interrupt() {
   thread.interrupt();
 }
Example #11
0
 // public int globalTickCount(){return globalTickCount;}
 public void interrupt() {
   dead = true;
   super.interrupt();
 }