public void testSelfExcludingJobs() throws Exception {

    BuildBlockerProperty theProperty = new BuildBlockerProperty();
    theProperty.setBlockingJobs("SelfExcluding_.*");

    FreeStyleProject theJob1 = createFreeStyleProject("SelfExcluding_Job1");
    theJob1.addProperty(theProperty);
    assertTrue(theJob1.getBuilds().isEmpty());

    FreeStyleProject theJob2 = createFreeStyleProject("SelfExcluding_Job2");
    theJob2.addProperty(theProperty);
    assertTrue(theJob1.getBuilds().isEmpty());

    // allow executing two simultanious jobs
    int theOldNumExecutors = Hudson.getInstance().getNumExecutors();
    Hudson.getInstance().setNumExecutors(2);

    Future<FreeStyleBuild> theFuture1 = theJob1.scheduleBuild2(0);
    Future<FreeStyleBuild> theFuture2 = theJob2.scheduleBuild2(0);

    long theStartTime = System.currentTimeMillis();
    long theEndTime = theStartTime;
    while ((!theFuture1.isDone() || !theFuture2.isDone()) && theEndTime < theStartTime + 5000) {
      theEndTime = System.currentTimeMillis();
    }

    // if more then five seconds have passed, we assume its a deadlock.
    assertTrue(theEndTime < theStartTime + 5000);

    // restore changed settings
    Hudson.getInstance().setNumExecutors(theOldNumExecutors);
    theJob2.delete();
    theJob1.delete();
  }
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Invalid number of arguments specified. Specify an input file.");
      return;
    }

    File inputFile = new File(args[0]);
    if (!inputFile.isDirectory()) {
      System.err.println(
          "Specified input is not a directory. Please specify a directory as an input.");
      return;
    }

    // Construct an object of TestFileReaderCallable

    TestFolderChildrenReaderCallable testObj = new TestFolderChildrenReaderCallable(inputFile);
    List<Future<StringBuffer>> inputList = new ArrayList<>();
    testObj.startProcess(testObj.getInputFile(), inputList);

    do {
      for (Future<StringBuffer> futureTask : inputList) {
        if (futureTask.isDone() && !futureTask.isCancelled()) {
          System.out.println(futureTask.get());
        } else if (futureTask.isDone() && futureTask.isCancelled()) {
          System.out.println("This task is cancelled....");
        } else if (!futureTask.isDone()) {
          System.out.println(futureTask + " is still in progress...");
        }
      }
    } while (testObj.getExecutorService().getCompletedTaskCount() < inputList.size());

    testObj.shutdown();
  }
Beispiel #3
0
  @Test
  public void getLargeBlock() throws Exception {
    connect();

    Block b1 = createFakeBlock(blockStore).block;
    blockChain.add(b1);
    Block b2 = makeSolvedTestBlock(b1);
    Transaction t = new Transaction(unitTestParams);
    t.addInput(b1.getTransactions().get(0).getOutput(0));
    t.addOutput(
        new TransactionOutput(
            unitTestParams, t, BigInteger.ZERO, new byte[Block.MAX_BLOCK_SIZE - 1000]));
    b2.addTransaction(t);

    // Request the block.
    Future<Block> resultFuture = peer.getBlock(b2.getHash());
    assertFalse(resultFuture.isDone());
    // Peer asks for it.
    GetDataMessage message = (GetDataMessage) outbound(writeTarget);
    assertEquals(message.getItems().get(0).hash, b2.getHash());
    assertFalse(resultFuture.isDone());
    // Peer receives it.
    inbound(writeTarget, b2);
    Block b = resultFuture.get();
    assertEquals(b, b2);
  }
  @Override
  public void handle(
      String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType(Const.JSON);
    Service service = getService(request);
    Module module = getModule(request, service);

    GetVersionData data = new GetVersionData();

    Future artifactFuture =
        executorService.submit(
            new ReadModuleArtifactVersionsRunnable(service, module, data, moduleArtifactHelper));
    Future configFuture =
        executorService.submit(
            new ReadModuleConfigVersionsRunnable(module, data, moduleConfigHelper));

    while (!artifactFuture.isDone() || !configFuture.isDone()) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
      }
    }

    toJson(response, data);
    response.setStatus(200);
    request.setHandled(true);
  }
  @Test
  public void testLeaseCancel() throws Exception {
    final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class);

    final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
    Mockito.when(conn1.isOpen()).thenReturn(true);
    Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1);

    final LocalConnPool pool = new LocalConnPool(connFactory, 1, 1);

    final Future<LocalPoolEntry> future1 = pool.lease("somehost", null);
    final GetPoolEntryThread t1 = new GetPoolEntryThread(future1);
    t1.start();

    t1.join(GRACE_PERIOD);
    Assert.assertTrue(future1.isDone());
    final LocalPoolEntry entry1 = t1.getEntry();
    Assert.assertNotNull(entry1);

    final Future<LocalPoolEntry> future2 = pool.lease("somehost", null);
    final GetPoolEntryThread t2 = new GetPoolEntryThread(future2);
    t2.start();

    Thread.sleep(5);

    Assert.assertFalse(future2.isDone());
    Assert.assertFalse(future2.isCancelled());

    future2.cancel(true);
    t2.join(GRACE_PERIOD);
    Assert.assertTrue(future2.isDone());
    Assert.assertTrue(future2.isCancelled());
    future2.cancel(true);
    future2.cancel(true);
  }
Beispiel #6
0
  public static void main(String[] args) {
    Callable<Integer> task =
        () -> {
          try {
            TimeUnit.SECONDS.sleep(1);
            return 123;
          } catch (InterruptedException e) {
            throw new IllegalStateException("task interrupted", e);
          }
        };

    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future<Integer> future = executor.submit(task);
    System.out.println("future done? " + future.isDone());
    Integer result = -1;
    try {
      result = future.get();
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("future done? " + future.isDone());
    System.out.println("result: " + result);

    stop(executor);
  }
Beispiel #7
0
  /**
   * Do Forever 1. Wait for a user input 2. Parse the user input. Separate the command and its
   * arguments 3. Create a new thread to execute the command 4. Execute the command and its
   * arguments on the newly created thread. Exit with the status code of the executed command 5. In
   * the shell, wait for the thread to complete execution 6. Report the exit status of the command
   * to the user
   */
  public static void main(String[] args) {
    Shell shell = new Shell();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    ExecutorService executorSvc = Executors.newSingleThreadExecutor();
    Future<?> taskThread = null;

    try {
      while (true) {

        if (taskThread == null || taskThread.isDone())
          System.out.print(System.getProperty("user.dir") + " >> ");

        String input = br.readLine();

        if (input == null) continue;

        input = input.trim();
        if (input.isEmpty()) continue;

        if (input.equals("Ctrl-Z")) {
          if (taskThread != null && !taskThread.isDone()) {
            taskThread.cancel(true);
            taskThread = null;
            System.out.println("Task Interrupted");
          }
        } else {
          if (taskThread == null || taskThread.isDone()) {
            ITool tool = shell.parse(input);
            boolean toExecuteTool = true;
            if (tool != null) {

              // get standard input if needed
              if (stdinRequired) {
                stdIn = "";
                while ((input = br.readLine()) != null) {
                  // do not execute task
                  if (input.equals("Ctrl-Z")) {
                    toExecuteTool = false;
                    System.out.println("Task Interrupted");
                    break;
                  }
                  stdIn += input + System.lineSeparator();
                }
              }

              if (toExecuteTool) {
                Runnable runnable = shell.execute(tool);
                taskThread = executorSvc.submit(runnable);
              }
            } else {
              System.err.println("Invalid Command : " + input);
            }
          }
        }
      }
    } catch (IOException e) {
      System.err.println("Error: invalid input - " + e.getMessage());
    }
  }
  @Override
  public void run() {
    while (!myDisposed) {
      boolean isEmpty;
      synchronized (filesToResolve) {
        isEmpty = filesToResolve.isEmpty();
      }
      if (enableVetoes.get() > 0
          || isEmpty
          || !resolveProcess.isDone()
          || HeavyProcessLatch.INSTANCE.isRunning()
          || PsiDocumentManager.getInstance(myProject).hasUncommitedDocuments()) {
        try {
          waitForQueue();
        } catch (InterruptedException e) {
          break;
        }
        continue;
      }
      final Set<VirtualFile> files = pollFilesToResolve();
      if (files.isEmpty()) continue;

      upToDate = false;

      myApplication.invokeLater(
          () -> {
            if (!resolveProcess.isDone()) return;
            log("Started to resolve " + files.size() + " files");

            Task.Backgroundable backgroundable =
                new Task.Backgroundable(myProject, "Resolving files...", false) {
                  @Override
                  public void run(@NotNull final ProgressIndicator indicator) {
                    if (!myApplication.isDisposed()) {
                      processBatch(indicator, files);
                    }
                  }
                };
            ProgressIndicator indicator;
            if (files.size() > 1) {
              // show progress
              indicator = new BackgroundableProcessIndicator(backgroundable);
            } else {
              indicator = new MyProgress();
            }
            resolveProcess =
                ((ProgressManagerImpl) ProgressManager.getInstance())
                    .runProcessWithProgressAsynchronously(backgroundable, indicator, null);
          },
          myProject.getDisposed());

      flushLog();
    }
  }
 /** Test the method isDone() */
 @Test
 public void testIsDoneMethod() throws Exception {
   Callable<String> task = new BasicTestTask();
   IExecutorService executor = createSingleNodeExecutorService("isDoneMethod");
   Future future = executor.submit(task);
   if (future.isDone()) {
     assertTrue(future.isDone());
   }
   assertEquals(future.get(), BasicTestTask.RESULT);
   assertTrue(future.isDone());
 }
Beispiel #10
0
 private static void futureDemo(AsynchronousFileChannel afc, ByteBuffer byteBuffer)
     throws InterruptedException, ExecutionException, IOException {
   Future<Integer> result = afc.read(byteBuffer, 0);
   while (!result.isDone()) {
     System.out.println("Waiting file channel finished....");
     Thread.sleep(1);
   }
   System.out.println("Finished? = " + result.isDone());
   System.out.println("byteBuffer = " + result.get());
   System.out.println(byteBuffer);
   afc.close();
 }
Beispiel #11
0
 @Override
 public void run(String... arg0) throws Exception {
   long start = System.currentTimeMillis();
   Future<User> page1 = gitservice.findUser("gcstar");
   Future<User> page2 = gitservice.findUser("tj");
   Future<User> page3 = gitservice.findUser("alsotang");
   while (!(page1.isDone() && page2.isDone() && page3.isDone())) {
     Thread.sleep(10); // 10-millisecond pause between each check
   }
   System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));
   System.out.println(page1.get());
   System.out.println(page2.get());
   System.out.println(page3.get());
 }
 /** Test for the issue 129. Repeatedly runs tasks and check for isDone() status after get(). */
 @Test
 public void testIsDoneMethod2() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("isDoneMethod2");
   for (int i = 0; i < COUNT; i++) {
     Callable<String> task1 = new BasicTestTask();
     Callable<String> task2 = new BasicTestTask();
     Future future1 = executor.submit(task1);
     Future future2 = executor.submit(task2);
     assertEquals(future2.get(), BasicTestTask.RESULT);
     assertTrue(future2.isDone());
     assertEquals(future1.get(), BasicTestTask.RESULT);
     assertTrue(future1.isDone());
   }
 }
  public void testCanPersistOnlySomeDeltas() throws Exception {
    appendDeltas(d1, d2, d3);
    Future<Void> future = target.persist(d2.getResultingVersion());
    awaitPersistence();
    assertTrue(future.isDone());
    assertEquals(null, future.get());
    assertEquals(d2.getResultingVersion(), target.getLastPersistedVersion());

    future = target.persist(d3.getResultingVersion());
    awaitPersistence();
    assertTrue(future.isDone());
    assertEquals(null, future.get());
    assertEquals(d3.getResultingVersion(), target.getLastPersistedVersion());
  }
  /**
   * One test for all for faster execution.
   *
   * @throws Exception
   */
  public void testCanRun() throws Exception {
    // init slave
    LabelAtom slaveLabel = new LabelAtom("slave");
    LabelAtom masterLabel = new LabelAtom("master");

    DumbSlave slave = this.createSlave(slaveLabel);
    SlaveComputer c = slave.getComputer();
    c.connect(false).get(); // wait until it's connected
    if (c.isOffline()) {
      fail("Slave failed to go online: " + c.getLog());
    }

    BuildBlockerQueueTaskDispatcher dispatcher = new BuildBlockerQueueTaskDispatcher();

    String blockingJobName = "blockingJob";

    Shell shell = new Shell("sleep 1");

    Future<FreeStyleBuild> future1 = createBlockingProject("xxx", shell, masterLabel);
    Future<FreeStyleBuild> future2 = createBlockingProject(blockingJobName, shell, masterLabel);
    Future<FreeStyleBuild> future3 = createBlockingProject("yyy", shell, slaveLabel);
    // add project to slave
    FreeStyleProject project = this.createFreeStyleProject();
    project.setAssignedLabel(slaveLabel);

    Queue.BuildableItem item =
        new Queue.BuildableItem(
            new Queue.WaitingItem(Calendar.getInstance(), project, new ArrayList<Action>()));

    CauseOfBlockage causeOfBlockage = dispatcher.canRun(item);

    assertNull(causeOfBlockage);

    BuildBlockerProperty property = new BuildBlockerProperty();

    property.setBlockingJobs(".*ocki.*");

    project.addProperty(property);

    causeOfBlockage = dispatcher.canRun(item);
    assertNotNull(causeOfBlockage);

    assertEquals(
        "Blocking job " + blockingJobName + " is running.", causeOfBlockage.getShortDescription());

    while (!(future1.isDone() && future2.isDone() && future3.isDone())) {
      // wait until jobs are done.
    }
  }
  /**
   * Opens the connection to the worker. And start the heartbeat thread.
   *
   * @throws IOException if a non-Tachyon exception occurs
   */
  private synchronized void connectOperation() throws IOException {
    if (!mConnected) {
      LOG.info("Connecting to {} worker @ {}", (mIsLocal ? "local" : "remote"), mAddress);

      TProtocol binaryProtocol =
          new TBinaryProtocol(AuthenticationUtils.getClientTransport(mTachyonConf, mAddress));
      mProtocol = new TMultiplexedProtocol(binaryProtocol, getServiceName());
      mClient = new BlockWorkerClientService.Client(mProtocol);

      try {
        mProtocol.getTransport().open();
      } catch (TTransportException e) {
        LOG.error(e.getMessage(), e);
        return;
      }
      mConnected = true;

      // only start the heartbeat thread if the connection is successful and if there is not
      // another heartbeat thread running
      if (mHeartbeat == null || mHeartbeat.isCancelled() || mHeartbeat.isDone()) {
        final int interval = mTachyonConf.getInt(Constants.USER_HEARTBEAT_INTERVAL_MS);
        mHeartbeat =
            mExecutorService.submit(
                new HeartbeatThread(HeartbeatContext.WORKER_CLIENT, mHeartbeatExecutor, interval));
      }
    }
  }
  @Test
  public void testSendWithNoEndpoint() throws Exception {
    Meta meta = m_metaHolder.getMeta();
    reset(m_metaHolder);
    Topic topic = meta.findTopic(TEST_TOPIC);
    for (Partition p : topic.getPartitions()) {
      p.setEndpoint(null);
    }
    when(m_metaHolder.getMeta()).thenReturn(meta);

    brokerActionsWhenReceivedSendMessageCmd( //
        MessageSendAnswer.NoOp);

    List<Pair<String, String>> appProperties = Arrays.asList(new Pair<String, String>("a", "A"));
    Future<SendResult> future =
        sendAsync(TEST_TOPIC, "pKey", "body", "rKey", appProperties, false, null);

    try {
      future.get(
          lookup(ProducerConfig.class).getBrokerSenderSendTimeoutMillis() + 200L,
          TimeUnit.MILLISECONDS);
      fail();
    } catch (TimeoutException e) {
      // do nothing
    } catch (Exception e) {
      fail();
    }
    assertFalse(future.isDone());

    List<Command> brokerReceivedCmds = getBrokerReceivedCmds();
    assertEquals(0, brokerReceivedCmds.size());
  }
Beispiel #17
0
 /* This is different from threadly's FutureUtils because
  * we want logging progress as futures complete...Since
  * these futures may take a VERY long time to complete.
  * The alternative would be to add runnables to these
  * so that we log out at 10% intervals, but that would assume
  * that the futures complete mostly in order.
  */
 public static void blockTillAllDone(List<Future<?>> futures) {
   float doneCount = 0;
   int lastReportedDonePercent = 0;
   Iterator<Future<?>> it = futures.iterator();
   while (it.hasNext()) {
     try {
       Future<?> f = it.next();
       if (!f.isDone() || !it.hasNext()) {
         // we take * 10 and / 10 so we can get one additional decimal of accuracy
         int donePercent = (int) Math.round((doneCount / futures.size()) * 100 * 10);
         if (donePercent != lastReportedDonePercent) {
           lastReportedDonePercent = donePercent;
           System.out.println("Progress: " + (donePercent / 10.) + "%");
         }
         f.get();
       }
       doneCount++;
     } catch (InterruptedException e) {
       ExceptionUtils.handleException(e);
       return; // let thread exit
     } catch (ExecutionException e) {
       ExceptionUtils.handleException(e);
     }
   }
 }
 /**
  * Tests that a SLSB method which is marked as asynchronous and returns a {@link
  * java.util.concurrent.Future} is invoked asynchronously and the client isn't blocked for the
  * lifetime of the method
  *
  * @throws Exception
  */
 @Test
 public void testAsyncFutureMethodOnSLSB() throws Exception {
   final StatelessEJBLocator<EchoRemote> locator =
       new StatelessEJBLocator<EchoRemote>(
           EchoRemote.class, APP_NAME, MODULE_NAME, EchoBean.class.getSimpleName(), "");
   final EchoRemote echoRemote = EJBClient.createProxy(locator);
   Assert.assertNotNull("Received a null proxy", echoRemote);
   final String message = "You are supposed to be an asynchronous method";
   final long DELAY = 5000;
   final long start = System.currentTimeMillis();
   // invoke the asynchronous method
   final Future<String> futureEcho = echoRemote.asyncEcho(message, DELAY);
   final long end = System.currentTimeMillis();
   logger.info(
       "Asynchronous invocation returned a Future: "
           + futureEcho
           + " in "
           + (end - start)
           + " milli seconds");
   // test that the invocation did not act like a synchronous invocation and instead returned
   // "immediately"
   Assert.assertFalse(
       "Asynchronous invocation behaved like a synchronous invocation", (end - start) >= DELAY);
   Assert.assertNotNull("Future is null", futureEcho);
   // Check if the result is marked as complete (it shouldn't be this soon)
   Assert.assertFalse("Future result is unexpectedly completed", futureEcho.isDone());
   // wait for the result
   final String echo = futureEcho.get();
   Assert.assertEquals("Unexpected echo message", message, echo);
 }
 /**
  * Cancel Feed Submissions request sample cancels feed submissions - by default all of the
  * submissions of the last 30 days that have not started processing
  *
  * @param service instance of MarketplaceWebService service
  * @param requests list of requests to process
  */
 public static void invokeCancelFeedSubmissions(
     MarketplaceWebService service, List<CancelFeedSubmissionsRequest> requests) {
   List<Future<CancelFeedSubmissionsResponse>> responses =
       new ArrayList<Future<CancelFeedSubmissionsResponse>>();
   for (CancelFeedSubmissionsRequest request : requests) {
     responses.add(service.cancelFeedSubmissionsAsync(request));
   }
   for (Future<CancelFeedSubmissionsResponse> future : responses) {
     while (!future.isDone()) {
       Thread.yield();
     }
     try {
       CancelFeedSubmissionsResponse response = future.get();
       // Original request corresponding to this response, if needed:
       CancelFeedSubmissionsRequest originalRequest = requests.get(responses.indexOf(future));
       System.out.println("Response request id: " + response.getResponseMetadata().getRequestId());
       System.out.println(response.getResponseHeaderMetadata());
       System.out.println();
     } catch (Exception e) {
       if (e.getCause() instanceof MarketplaceWebServiceException) {
         MarketplaceWebServiceException exception =
             MarketplaceWebServiceException.class.cast(e.getCause());
         System.out.println("Caught Exception: " + exception.getMessage());
         System.out.println("Response Status Code: " + exception.getStatusCode());
         System.out.println("Error Code: " + exception.getErrorCode());
         System.out.println("Error Type: " + exception.getErrorType());
         System.out.println("Request ID: " + exception.getRequestId());
         System.out.print("XML: " + exception.getXML());
         System.out.println("ResponseHeaderMetadata: " + exception.getResponseHeaderMetadata());
       } else {
         e.printStackTrace();
       }
     }
   }
 }
  @Test
  public void testSendNonPriorityAsync() throws Exception {
    brokerActionsWhenReceivedSendMessageCmd( //
        MessageSendAnswer.Accept, //
        MessageSendAnswer.ResponseSucessResult //
        );

    List<Pair<String, String>> appProperties = Arrays.asList(new Pair<String, String>("b", "B"));
    Future<SendResult> future =
        sendAsync(TEST_TOPIC, "pKey", "body", "rKey", appProperties, true, null);

    future.get();
    assertTrue(future.isDone());

    List<Command> brokerReceivedCmds = getBrokerReceivedCmds();
    assertEquals(1, brokerReceivedCmds.size());

    SendMessageCommand sendCmd = (SendMessageCommand) brokerReceivedCmds.get(0);
    ConcurrentMap<Integer, List<ProducerMessage<?>>> msgs = sendCmd.getMsgs();
    // priority
    assertEquals(1, msgs.get(0).size());
    // non-priority
    assertNull(msgs.get(1));

    assertMsg(msgs.get(0).get(0), TEST_TOPIC, "pKey", "body", "rKey", appProperties);
  }
 @Override
 protected void doClose() throws ElasticsearchException {
   int size = tasks.size();
   if (size > 0) {
     for (Future<?> f : tasks) {
       if (!f.isDone()) {
         logger.info("aborting knapsack task {}", f);
         boolean b = f.cancel(true);
         if (!b) {
           logger.error("knapsack task {} could not be cancelled", f);
         }
       }
     }
     tasks.clear();
   }
   logger.info("knapsack shutdown...");
   executor.shutdown();
   try {
     this.executor.awaitTermination(5, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
     throw new ElasticsearchException(e.getMessage());
   }
   if (!executor.isShutdown()) {
     logger.info("knapsack shutdown now");
     executor.shutdownNow();
     try {
       this.executor.awaitTermination(5, TimeUnit.SECONDS);
     } catch (InterruptedException e) {
       throw new ElasticsearchException(e.getMessage());
     }
   }
   logger.info("knapsack shutdown complete");
 }
  private void closeImmediately0() {
    // We need to close the channel immediately to remove it from the
    // server session's channel table and *not* send a packet to the
    // client.  A notification was already sent by our caller, or will
    // be sent after we return.
    //
    super.close(true);

    // We also need to close the socket.
    Socket.close(handle);

    try {
      if ((forwarder != null) && (!forwarder.isDone())) {
        forwarder.cancel(true);
      }
    } finally {
      forwarder = null;
    }

    try {
      if ((forwardService != null) && shutdownForwarder) {
        Collection<?> runners = forwardService.shutdownNow();
        if (log.isDebugEnabled()) {
          log.debug("Shut down runners count=" + GenericUtils.size(runners));
        }
      }
    } finally {
      forwardService = null;
      shutdownForwarder = false;
    }
  }
  /** Scenario: loads on one label shouldn't translate to load on another label. */
  public void testLabels() throws Exception {
    BulkChange bc = new BulkChange(hudson);
    try {
      DummyCloudImpl cloud = initHudson(0);
      Label blue = hudson.getLabel("blue");
      Label red = hudson.getLabel("red");
      cloud.label = red;

      // red jobs
      List<FreeStyleProject> redJobs = create5SlowJobs(new Latch(5));
      for (FreeStyleProject p : redJobs) p.setAssignedLabel(red);

      // blue jobs
      List<FreeStyleProject> blueJobs = create5SlowJobs(new Latch(5));
      for (FreeStyleProject p : blueJobs) p.setAssignedLabel(blue);

      // build all
      List<Future<FreeStyleBuild>> blueBuilds = buildAll(blueJobs);
      verifySuccessfulCompletion(buildAll(redJobs));

      // cloud should only give us 5 nodes for 5 red jobs
      assertEquals(5, cloud.numProvisioned);

      // and all blue jobs should be still stuck in the queue
      for (Future<FreeStyleBuild> bb : blueBuilds) assertFalse(bb.isDone());
    } finally {
      bc.abort();
    }
  }
Beispiel #24
0
 public long get() {
   if (snychState == SynchState.NTP) return startNTPTime + (System.currentTimeMillis() - ntpTimer);
   // We are using tick based server time here
   // Check if synch is ongoing
   if (ntpFuture.isDone()) {
     logger.debug("ntpSynchTask result available.");
     startNTPTime = getNTPFuture();
     if (startNTPTime != 0L) {
       // NTP time now available
       snychState = SynchState.NTP;
       ntpTimer = System.currentTimeMillis();
       logger.debug("Switched to SynchState NTP");
       return startNTPTime;
     } else {
       logger.debug("Synch taks failed, reset synch timer");
       serverSynchTimer = System.currentTimeMillis();
     }
   }
   // No synch ongoing, check if synch is triggered
   if (isServerTimeSynchTriggered()) {
     logger.debug("Server time synching was triggered.");
     startNTPSynch();
     serverSynchTimer = System.currentTimeMillis();
   }
   long latestTickTime = getLatestTickTime();
   if (latestTickTime == 0L) {
     logger.warn(
         "latestTickTime is invalid, server time currently not available, fallback to system time!");
     return System.currentTimeMillis();
   }
   return latestTickTime;
 }
  @Override
  public void close() {
    boolean shouldSendDelete;
    Future<?> future;
    synchronized (this) {
      shouldSendDelete = !closed;

      closed = true;

      future = this.future;

      this.future = null;

      lastUpdate = DateTime.now();
    }

    if (future != null && !future.isDone()) {
      future.cancel(true);
    }

    // abort the output buffer on the remote node; response of delete is ignored
    if (shouldSendDelete) {
      sendDelete();
    }
  }
Beispiel #26
0
  /** 通过将来式一度读取文件 */
  @Test
  public void testAsynchronousFileChannel() {
    Path path = Paths.get(ParentPath + "\\win7.iso");
    try {
      AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
      ByteBuffer buffer = ByteBuffer.allocate(1000000000);
      Future<Integer> read = channel.read(buffer, 0);
      while (!read.isDone()) {
        System.out.println("read");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      try {
        Integer resoult = read.get();
        System.out.println(resoult);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  // check whether the semaphore is valid
  private boolean waitTaskDone() {
    log.error("waitTaskDone():: entrance");
    final long timeout = 1 * 1000;
    long startTimestamp = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTimestamp < timeout) {
      for (int index = 0; index < mTaskList.size(); ++index) {
        ITaskBase currentTask = mTaskList.get(index);

        // check whether the mTaskList is cleared
        if (currentTask == null) {
          log.info("waitTaskDone():: currentTask == null, return");
          return true;
        }

        Future<?> currentFuture = currentTask.getFuture();

        if (currentFuture == null) {
          log.info("waitTaskDone():: the task is added just now, return");
          return true;
        }

        if (currentFuture != null && currentFuture.isDone()) {
          log.info("waitTaskDone():: one task is done, return");
          return true;
        }
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    log.info("waitTaskDone():: tiemout, fake semaphore");
    return false;
  }
Beispiel #28
0
    @Override
    public void addListener(Runnable listener, Executor exec) {
      executionList.add(listener, exec);

      // When a listener is first added, we run a task that will wait for the delegate to finish,
      // and when it is done will run the listeners.
      if (hasListeners.compareAndSet(false, true)) {
        if (delegate.isDone()) {
          // If the delegate is already done, run the execution list immediately on the current
          // thread.
          executionList.execute();
          return;
        }

        // TODO(lukes): handle RejectedExecutionException
        adapterExecutor.execute(
            new Runnable() {
              @Override
              public void run() {
                try {
                  /*
                   * Threads from our private pool are never interrupted. Threads from a
                   * user-supplied executor might be, but... what can we do? This is another reason
                   * to return a proper ListenableFuture instead of using listenInPoolThread.
                   */
                  getUninterruptibly(delegate);
                } catch (Throwable e) {
                  // ExecutionException / CancellationException / RuntimeException / Error
                  // The task is presumably done, run the listeners.
                }
                executionList.execute();
              }
            });
      }
    }
 public double getExecutionTimeMillis() {
   final long t = time.get();
   if (!future.isDone()) {
     return System.nanoTime() - t;
   }
   return t / 1000000.0;
 }
 public void doFuture() {
   CallableTask call = new CallableTask();
   try {
     /**
      * Future<t> is result of asynchronous computation. It may possible that CallableTask has not
      * started yet but 'ExecutorService' gives the result via Future Object.
      */
     Future<String> future = executorPool.submit(call);
     /** We can check if CallableTask has been completed. */
     System.out.println("Status of Callable Task [Is Completed ? " + future.isDone() + "]");
     /**
      * We can get the result of callable Task. Note : future.get() is a blocking call, It will
      * wait until the associated process finishes.
      */
     System.out.println("Result of callable task [" + future.get() + "]");
     /** We can cancel the task. */
     System.out.println("Trying to cancel the task [Is Cancelled ? " + future.cancel(false) + "]");
     /**
      * We can see if the task was canceled. Returns true if this task was canceled before it
      * completed normally
      */
     System.out.println("Was task canceled before normal complition ? -" + future.isCancelled());
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     executorPool.shutdownNow();
   }
 }