public void run() {
   long lastTime = System.nanoTime();
   double nsPerTick = 1000000000D / 60D;
   int ticks = 0;
   int frames = 0;
   long lastTimer = System.currentTimeMillis();
   double delta = 0.0;
   while (running) {
     long now = System.nanoTime();
     delta += (now - lastTime) / nsPerTick;
     lastTime = now;
     boolean shouldRender = false;
     while (delta >= 1) {
       ticks++;
       update();
       delta -= 1;
       shouldRender = true;
     }
     if (shouldRender) {
       frames++;
       paint(game.getWindow().getGraphics());
     }
     if (System.currentTimeMillis() - lastTimer >= 1000) {
       lastTimer += 1000;
       if (ticks >= 55 && frames >= 50) {
         RNG.extraTime();
         RNG.extraTime();
       }
       frames = 0;
       ticks = 0;
     }
   }
 }
Example #2
0
    @Override
    public Connection<CL> borrowConnection(int duration, TimeUnit unit) {

      if (numActiveConnections.get() < 1) {
        // Need to throw something other than DynoConnectException in order to bubble past
        // HostSelectionWithFallback
        // Is that the right thing to do ???
        throw new PoolExhaustedException(
                HostConnectionPoolImpl.this, "Fast fail - NO ACTIVE CONNECTIONS in pool")
            .setHost(getHost());
      }

      // Start recording how long it takes to get the connection - for insight/metrics
      long startTime = System.nanoTime() / 1000;

      Connection<CL> conn = null;
      try {
        // wait on the connection pool with a timeout
        conn = availableConnections.poll(duration, unit);
      } catch (InterruptedException e) {
        Logger.info("Thread interrupted when waiting on connections");
        throw new DynoConnectException(e);
      }

      long delay = System.nanoTime() / 1000 - startTime;

      if (conn == null) {
        throw new PoolTimeoutException("Fast fail waiting for connection from pool")
            .setHost(getHost())
            .setLatency(delay);
      }

      monitor.incConnectionBorrowed(host, delay);
      return conn;
    }
  @Test
  public void testTime() {
    int connections = 5;
    List<Integer> opIds = new ArrayList<>();
    // Build a router
    for (int i = 0; i < connections; i++) {
      opIds.add(i);
    }
    Router r = RouterFactory.buildRouterFor(opIds, false);

    // Try router
    // Try router
    int iter = 10000000;
    long start = System.nanoTime();
    for (int i = 0; i < iter; i++) {
      int opId = r.route();
    }
    long stop = System.nanoTime();
    long totalMillis = (stop - start) / 1000000;
    System.out.println(
        "Time to route: "
            + iter
            + " to "
            + connections
            + " downstreams is: "
            + totalMillis
            + " ms");
    assert (true);
  }
Example #4
0
  /**
   * Main method.
   *
   * @param args command-line arguments
   */
  public static void main(final String[] args) {
    try {
      // initialize timer
      final long time = System.nanoTime();

      // create session
      final BaseXClient session = new BaseXClient("localhost", 1984, "admin", "admin");

      // version 1: perform command and print returned string
      System.out.println(session.execute("info"));

      // version 2 (faster): perform command and pass on result to output stream
      final OutputStream out = System.out;
      session.execute("xquery 1 to 10", out);

      // close session
      session.close();

      // print time needed
      final double ms = (System.nanoTime() - time) / 1000000d;
      System.out.println("\n\n" + ms + " ms");

    } catch (final IOException ex) {
      // print exception
      ex.printStackTrace();
    }
  }
Example #5
0
  private void shutdownNodes() {
    final Operation op = new ShutdownNodeOperation();

    logger.info("Sending shutting down operations to all members...");

    Collection<Member> members = getMembers(NON_LOCAL_MEMBER_SELECTOR);
    final long timeout =
        node.groupProperties.getNanos(GroupProperty.CLUSTER_SHUTDOWN_TIMEOUT_SECONDS);
    final long startTime = System.nanoTime();

    while ((System.nanoTime() - startTime) < timeout && !members.isEmpty()) {
      for (Member member : members) {
        nodeEngine.getOperationService().send(op, member.getAddress());
      }

      try {
        Thread.sleep(CLUSTER_SHUTDOWN_SLEEP_DURATION_IN_MILLIS);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        logger.warning("Shutdown sleep interrupted. ", e);
        break;
      }

      members = getMembers(NON_LOCAL_MEMBER_SELECTOR);
    }

    logger.info(
        "Number of other nodes remaining: "
            + getSize(NON_LOCAL_MEMBER_SELECTOR)
            + ". Shutting down itself.");
    node.shutdown(false);
  }
  @Override
  public org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> value(
      final org.drip.param.valuation.ValuationParams valParams,
      final org.drip.param.pricer.CreditPricerParams pricerParams,
      final org.drip.param.market.CurveSurfaceQuoteSet csqs,
      final org.drip.param.valuation.ValuationCustomizationParams quotingParams) {
    long lStart = System.nanoTime();

    org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapResult =
        new org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double>();

    if (null != _aCompFixedStream && 0 != _aCompFixedStream.length) {
      for (org.drip.product.rates.Stream fixedStream : _aCompFixedStream) {
        org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapFixedStreamResult =
            fixedStream.value(valParams, pricerParams, csqs, quotingParams);

        if (!org.drip.analytics.support.AnalyticsHelper.AccumulateMeasures(
            mapResult, fixedStream.name(), mapFixedStreamResult)) return null;
      }
    }

    if (null != _aCompFloatStream && 0 != _aCompFloatStream.length) {
      for (org.drip.product.rates.Stream floatStream : _aCompFloatStream) {
        org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapFixedStreamResult =
            floatStream.value(valParams, pricerParams, csqs, quotingParams);

        if (!org.drip.analytics.support.AnalyticsHelper.AccumulateMeasures(
            mapResult, floatStream.name(), mapFixedStreamResult)) return null;
      }
    }

    mapResult.put("CalcTime", (System.nanoTime() - lStart) * 1.e-09);

    return mapResult;
  }
  @Override
  public void chooseMove() {
    long startTime = System.nanoTime();
    Move bestMove = null;
    double bestScore = 0;

    // We need to initialize alpha and beta -infinity and + infinity respectively.
    double alpha = Double.NEGATIVE_INFINITY;
    double beta = Double.POSITIVE_INFINITY;

    int maxDepth;
    for (maxDepth = 1; (System.nanoTime() - startTime) <= maxTime; maxDepth++) {
      List<Move> legalMoves = GameState2P.getLegalMoves(state, index);
      bestScore = 0;

      for (Move m : legalMoves) {
        // If we run out time we break out.
        if ((System.nanoTime() - startTime) >= maxTime) {
          break;
        }

        GameState2P next = m.doMove(state);
        double score = getMinScoreAlphaBeta(next, maxDepth, alpha, beta);

        if (bestMove == null || score >= bestScore) {
          bestMove = m;
          bestScore = score;
        }
      }
    }

    System.out.println("Depth: " + maxDepth + " trans score: " + bestScore);
    GameState2P newState = bestMove.doMove(state);
    game.doMove(index, newState);
  }
Example #8
0
 public void run() {
   long lastTime = System.nanoTime();
   long timer = System.currentTimeMillis();
   final double ns = 1000000000.0 / 60.0;
   double delta = 0;
   int frames = 0;
   int updates = 0;
   while (running) {
     long now = System.nanoTime();
     delta += (now - lastTime) / ns;
     lastTime = now;
     while (delta >= 1) {
       update();
       updates++;
       delta--;
     }
     render();
     frames++;
     if (System.currentTimeMillis() - timer >= 1000) {
       timer += 1000;
       frame.setTitle(title + "  |  " + updates + " ups, " + frames + " fps");
       frames = 0;
       updates = 0;
     }
   }
   stop();
 }
  @Test
  void testExponentialBackoffDelay() throws InterruptedException {
    long acceptableDelay = 25; // Delay to forgive if tests run long.

    long startTime = System.nanoTime();
    handler.imposeBackoffExponentialDelay(1, "TEST FAILURE: 1");
    long elapsedTime = (System.nanoTime() - startTime) / 1000000;
    assert (elapsedTime >= 49) : elapsedTime;
    assertTrue(elapsedTime < 50 + acceptableDelay);

    startTime = System.nanoTime();
    handler.imposeBackoffExponentialDelay(2, "TEST FAILURE: 2");
    elapsedTime = (System.nanoTime() - startTime) / 1000000;
    assert (elapsedTime >= 199) : elapsedTime;
    assertTrue(elapsedTime < 200 + acceptableDelay);

    startTime = System.nanoTime();
    handler.imposeBackoffExponentialDelay(3, "TEST FAILURE: 3");
    elapsedTime = (System.nanoTime() - startTime) / 1000000;
    assert (elapsedTime >= 449) : elapsedTime;
    assertTrue(elapsedTime < 450 + acceptableDelay);

    startTime = System.nanoTime();
    handler.imposeBackoffExponentialDelay(4, "TEST FAILURE: 4");
    elapsedTime = (System.nanoTime() - startTime) / 1000000;
    assert (elapsedTime >= 799) : elapsedTime;
    assertTrue(elapsedTime < 800 + acceptableDelay * 2);

    startTime = System.nanoTime();
    handler.imposeBackoffExponentialDelay(5, "TEST FAILURE: 5");
    elapsedTime = (System.nanoTime() - startTime) / 1000000;
    assert (elapsedTime >= 1249) : elapsedTime;
    assertTrue(elapsedTime < 1250 + acceptableDelay * 2);
  }
Example #10
0
  public static void main(String[] args) throws Exception {
    Thread.sleep(10000);
    longs = new long[DIMENSION_1][];
    for (int i = 0; i < DIMENSION_1; i++) {
      longs[i] = new long[DIMENSION_2];
      for (int j = 0; j < DIMENSION_2; j++) {
        longs[i][j] = 0L;
      }
    }
    System.out.println("starting....");

    long sum = 0L;
    for (int r = 0; r < RUNS; r++) {

      final long start = System.nanoTime();

      // slow
      for (int j = 0; j < DIMENSION_2; j++) {
        for (int i = 0; i < DIMENSION_1; i++) {
          sum += longs[i][j];
        }
      }

      System.out.println("Ended asd");

      // fast
      //                for (int i = 0; i < DIMENSION_1; i++) {
      //                    for (int j = 0; j < DIMENSION_2; j++) {
      //                        sum += longs[i][j];
      //                    }
      //                }

      System.out.println((System.nanoTime() - start));
    }
  }
Example #11
0
  /**
   * Thread action : zoom the view <br>
   * <br>
   * <b>Parent documentation:</b><br>
   * {@inheritDoc}
   *
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    Utilities.sleep(4096);

    final double zoom = 2;
    final int max = 100;
    long time = System.nanoTime();
    long top;

    for (int i = 1; i <= max; i++) {
      top = System.nanoTime();
      SampleCanvas1.canvas.getLayer(0).setZoom((zoom * i) / max);
      SampleCanvas1.sampleLabelJHelpImage.setJHelpImage(SampleCanvas1.canvas.updateImage());
      Debug.println(DebugLevel.INFORMATION, "top=", (System.nanoTime() - top) / 1000000);
    }

    time = System.nanoTime() - time;
    Debug.println(
        DebugLevel.INFORMATION,
        "time=",
        time / 1000000,
        "ms : ~",
        (time / max) / 1000000,
        "ms per draw");
  }
  /**
   * Test determines whether nano times are always distinct from the last generated nanos time (as
   * assigned by {@link System#nanoTime()}.
   *
   * <p>Note: This test is NOT designed to pass/fail but simply to test determine a characteristic
   * of the platform on which it is executing.
   */
  public void test_nextNanoTime() {

    final int limit = 1000000;

    long lastNanoTime = System.nanoTime();
    long nanoTime;
    long minDiff = Long.MAX_VALUE;

    for (int i = 0; i < limit; i++) {

      nanoTime = System.nanoTime();

      if (nanoTime == lastNanoTime) {

        System.err.println(
            "This platform can generate identical timestamps with nanosecond resolution");

        return;
      }

      long diff = nanoTime - lastNanoTime;

      if (diff < 0) diff = -diff;

      if (diff < minDiff) minDiff = diff;

      lastNanoTime = nanoTime;
    }

    System.err.println("Nano times appear to be distinct on this platorm.");

    System.err.println("Minimum difference in nanos is " + minDiff + " over " + limit + " trials");
  }
  @Test
  public void testOne() throws Exception {

    MarshallableFactory.getInstance().addMarshallable(Image.class);
    MarshallableFactory.getInstance().addMarshallable(Media.class);
    MarshallableFactory.getInstance().addMarshallable(MediaContent.class);
    MarshallableFactory.getInstance().addMarshallable(ArrayList.class, ListSerializer.class);

    MediaContent mc;

    long t1 = System.nanoTime();

    ObjectToByteBuffer otbb = new ObjectToByteBuffer(2048);
    ByteBufferToObject bbto = new ByteBufferToObject(otbb.getByteBuffer());

    mc = create();

    for (int i = 0; i < 1000000; i++) {
      otbb.clearM();
      otbb.writeObject(mc);
      MediaContent mc2 = (MediaContent) bbto.readObject();
    }
    long t2 = System.nanoTime();

    System.out.println("done: " + (t2 - t1) / 1000000);
  }
Example #14
0
  @Override
  public void run() {
    float deltaTime = 0;
    float targetFPS = 60.0f;
    float targetUpdateHertz = 1 / targetFPS;

    long firstTimer = System.nanoTime();
    long secondTimer = System.nanoTime();

    initialize();

    while (running) {
      firstTimer = System.nanoTime();
      update(deltaTime);
      render();
      secondTimer = System.nanoTime();
      deltaTime = secondTimer - firstTimer;
      deltaTime /= 1000000000;
      if (deltaTime < targetUpdateHertz) {
        long sleepTime = (long) ((targetUpdateHertz - deltaTime) * 1000);
        try {
          Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        deltaTime = targetUpdateHertz;
      }
    }

    System.exit(0);
  }
  @Override
  public long waitFor(
      long sequence, Sequence cursor, Sequence dependentSequence, SequenceBarrier barrier)
      throws AlertException, InterruptedException {
    long availableSequence;
    long startTime = 0;
    int counter = SPIN_TRIES;

    do {
      if ((availableSequence = dependentSequence.get()) >= sequence) {
        return availableSequence;
      }

      if (0 == --counter) {
        if (0 == startTime) {
          startTime = System.nanoTime();
        } else {
          long timeDelta = System.nanoTime() - startTime;
          if (timeDelta > yieldTimeoutNanos) {
            return lockingStrategy.waitOnLock(sequence, cursor, dependentSequence, barrier);
          } else if (timeDelta > spinTimeoutNanos) {
            Thread.yield();
          }
        }
        counter = SPIN_TRIES;
      }
    } while (true);
  }
 public static void measureReadingFile(File file, PrintWriter out) {
   try {
     long start = System.nanoTime();
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     BufferedOutputStream outToNull = new BufferedOutputStream(byteArrayOutputStream);
     BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
     long start1 = System.nanoTime();
     byte[] bytes = new byte[1024];
     int counter = 0;
     long start2 = System.nanoTime();
     while ((counter += in.read(bytes)) > 0) {
       outToNull.write(bytes, 0, counter);
     }
     in.close();
     outToNull.close();
     long stop = System.nanoTime(); // stop
     synchronized (out) {
       out.println(
           (double) (stop - start) / 1000000.
               + ", "
               + (double) (start1 - start) / 1000000.
               + ", "
               + (double) (start2 - start1) / 1000000.
               + ", "
               + (double) (stop - start2) / 1000000.); // + " " +
       threadCount++;
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public void gameLoop() {
    long lastLoopTime = System.nanoTime();
    final int TARGET_FPS = 60;
    final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;

    while (true) {

      long now = System.nanoTime();
      long updateLength = now - lastLoopTime;
      lastLoopTime = now;
      double delta = updateLength / ((double) OPTIMAL_TIME);

      doGameUpdates(delta);

      // render();
      //			myGame.getView().update();

      try {
        long temp = (lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000;
        if (temp < 0) temp = 0;
        Thread.sleep(temp);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
 public static void measureReadingHbase(HTable table, byte[] key, PrintWriter out) {
   try {
     long start1 = System.nanoTime();
     Get g = new Get(key);
     Result r = table.get(g);
     long start2 = System.nanoTime();
     byte[] value = r.getValue(Import.family, Import.qualifier);
     if (value != null) {
       long start3 = System.nanoTime();
       BufferedOutputStream outToNull = new BufferedOutputStream(new ByteArrayOutputStream());
       outToNull.write(value);
       outToNull.close();
       long stop = System.nanoTime(); // stop
       synchronized (out) {
         out.println(
             "NAN, "
                 + (double) (stop - start1) / 1000000.
                 + ", "
                 + (double) (start2 - start1) / 1000000.
                 + ", "
                 + (double) (start3 - start2) / 1000000.
                 + ", "
                 + (double) (stop - start3) / 1000000.); // +
         // " "
         // +
         threadCount++;
       }
     } else {
       System.out.println("No image is extracted with name key " + new String(key));
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #19
0
 public void run() {
   // Game Loop
   this.requestFocus();
   init();
   long lastTime = System.nanoTime();
   double amountOfTicks = 60.0;
   double ns = 1000000000 / amountOfTicks;
   double delta = 0;
   long timer = System.currentTimeMillis();
   int updates = 0;
   int frames = 0;
   while (running) {
     long now = System.nanoTime();
     delta += (now - lastTime) / ns;
     lastTime = now;
     while (delta >= 1) {
       tick();
       updates++;
       delta--;
     }
     render();
     frames++;
     if ((System.currentTimeMillis() - timer) > 1000) {
       timer += 1000;
       System.out.println("FPS: " + frames + " TICKS: " + updates);
       frames = 0;
       updates = 0;
     }
   }
 }
  @Override
  public void handle(ReutersDoc doc) {

    Document searchDoc = new Document();
    searchDoc.fields = Maps.newHashMap();

    searchDoc.fields.put("title", doc.title);
    searchDoc.fields.put("text", doc.text);

    documentsBuffer.add(searchDoc);

    if (documentsBuffer.size() >= bufferSize) {
      try {

        long before = System.nanoTime();
        broker.index(this.shard, documentsBuffer);
        long after = System.nanoTime();

        counter.addAndGet(documentsBuffer.size());

        indexTime += after - before;

      } catch (TException e) {
        e.printStackTrace();
      }
      documentsBuffer.clear();
    }
  }
  @Override
  public BytesRef writeToBytes() {
    long start = System.nanoTime();
    int size = set.size();

    BytesRef bytes = new BytesRef(new byte[HEADER_SIZE + (int) bytesUsed.get()]);

    // Encode encoding type
    Bytes.writeInt(bytes, this.getEncoding().ordinal());

    // Encode flag
    bytes.bytes[bytes.offset++] = (byte) (this.isPruned() ? 1 : 0);

    // Encode size of the set
    Bytes.writeInt(bytes, size);

    // Encode longs
    BytesRef reusable = new BytesRef();
    for (int i = 0; i < this.set.size(); i++) {
      this.set.get(i, reusable);
      Bytes.writeBytesRef(reusable, bytes);
    }

    logger.debug(
        "Serialized {} terms - took {} ms", this.size(), (System.nanoTime() - start) / 1000000);

    bytes.length = bytes.offset;
    bytes.offset = 0;
    return bytes;
  }
 /**
  * Method to create a new TE LSP initiated in this node
  *
  * @param destinationId IP AddreStart LSP Errorss of the destination of the LSP
  * @param bw Bandwidth requested
  * @param bidirectional bidirectional
  * @param OFcode
  * @throws LSPCreationException
  */
 public long addnewLSP(
     Inet4Address destinationId, float bw, boolean bidirectional, int OFcode, int lspID)
     throws LSPCreationException {
   log.info("Adding New LSP to " + destinationId);
   // FIXME: mirar esto
   // meter structura --> RequestedLSPinformation --> Dependiente de cada tecnologia
   // meter campo con el estado del LSP e ir cambiandolo
   LSPTE lsp =
       new LSPTE(
           lspID,
           localIP,
           destinationId,
           bidirectional,
           OFcode,
           bw,
           PathStateParameters.creatingLPS);
   LSPList.put(new LSPKey(localIP, lsp.getIdLSP()), lsp);
   ReentrantLock lock = new ReentrantLock();
   Condition lspEstablished = lock.newCondition();
   // log.info("Metemos en Lock list con ID: "+lsp.getIdLSP());
   lockList.put(lsp.getIdLSP(), lock);
   conditionList.put(lsp.getIdLSP(), lspEstablished);
   /*log.info("Size lockList : "+lockList.size());
   log.info("Size conditionList : "+conditionList.size());*/
   timeIni = System.nanoTime();
   log.info("Start to establish path: " + System.nanoTime());
   try {
     startLSP(lsp);
   } catch (LSPCreationException e) {
     log.info("Start LSP Error!");
     throw e;
   }
   return lsp.getIdLSP();
 }
Example #23
0
  @Override
  public synchronized void run() {
    long fps_Timer = System.currentTimeMillis();
    double unsPerUpdate = 1000000000 / 60;
    // Last update in nanoseconds
    double uthen = System.nanoTime();
    double unprocessed = 0;
    while (running) {
      double unow = System.nanoTime();
      unprocessed += (unow - uthen) / unsPerUpdate;
      uthen = unow;
      // Update queue
      while (unprocessed >= 1) {
        update();
        unprocessed--;
      }

      // FPS Timer
      if (System.currentTimeMillis() - fps_Timer > 1000) {
        fps_Timer += 1000;

        try {
          Thread.sleep(5);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #24
0
  /**
   * @param args
   * @throws IOException
   */
  public static void main(final String[] args) throws IOException {

    final long startTime = System.nanoTime();
    final int t = 1; // nextInt();

    for (int i = 0; i < t; ++i) {
      solve(i + 1);
      if (isLocal && file) {
        err.println(i + 1 + "/" + t);
      }
      if (isLocal && !file) {
        out.flush();
      }
    }

    if (isLocal) {
      err.println(
          String.format("Completed after %d ms.", (System.nanoTime() - startTime) / 1000000));
    }

    out.flush();
    if (file) {
      out.close();
    }
  }
  // specific tests should call this method, but it is not marked as a test itself intentionally
  public void testParquetFullEngineEventBased(
      boolean testValues,
      boolean generateNew,
      String plan,
      String readEntries,
      String filename,
      int numberOfTimesRead /* specified in json plan */,
      ParquetTestProperties props,
      QueryType queryType)
      throws Exception {
    if (generateNew) TestFileGenerator.generateParquetFile(filename, props);

    ParquetResultListener resultListener =
        new ParquetResultListener(getAllocator(), props, numberOfTimesRead, testValues);
    long C = System.nanoTime();
    String planText = Files.toString(FileUtils.getResourceAsFile(plan), Charsets.UTF_8);
    // substitute in the string for the read entries, allows reuse of the plan file for several
    // tests
    if (readEntries != null) {
      planText = planText.replaceFirst("&REPLACED_IN_PARQUET_TEST&", readEntries);
    }
    this.testWithListener(queryType, planText, resultListener);
    resultListener.getResults();
    long D = System.nanoTime();
    System.out.println(String.format("Took %f s to run query", (float) (D - C) / 1E9));
  }
 public void testNonStopTimer() throws Exception {
   long startTime = System.nanoTime();
   int loopTmes = 4;
   long timeout = 500;
   for (int i = 0; i < loopTmes; i++) {
     System.out.println("executing loop count" + i);
     nonStopManager.begin(timeout);
     try {
       blockUntilAborted();
     } finally {
       Assert.assertTrue(abortableOperationManager.isAborted());
       Thread.currentThread().interrupt();
       nonStopManager.finish();
       // check that aborted status is cleared.
       Assert.assertFalse(abortableOperationManager.isAborted());
       // check that interrupted flag is cleared.
       Assert.assertFalse(Thread.interrupted());
     }
   }
   long timeTaken = System.nanoTime() - startTime;
   System.out.println("time taken to execute operations " + timeTaken);
   Assert.assertTrue(
       (timeTaken >= loopTmes * TimeUnit.MILLISECONDS.toNanos(timeout)
           && timeTaken
               < (loopTmes * TimeUnit.MILLISECONDS.toNanos(timeout)
                   + TimeUnit.SECONDS.toNanos(2))));
 }
Example #27
0
 public Object process(Session sess, ObjectMap headMap, Object key) {
   if (key instanceof ScalarKey) {
     ScalarKey sk = (ScalarKey) key;
     key = sk.getKey();
   }
   AgentMBeanImpl mbean =
       WXSUtils.getAgentMBeanManager()
           .getBean(sess.getObjectGrid().getName(), this.getClass().getName());
   long startNS = System.nanoTime();
   try {
     ObjectMap itemMap = sess.getMap("list-item-string-long");
     ListHead head = (ListHead) headMap.getForUpdate(key);
     if (head != null) {
       head = (ListHead) headMap.get(key);
       head.insertItem(isLeft, value, headMap, itemMap);
       headMap.update(key, head);
     } else {
       // list doesn't exist on disk
       head = new ListHead((String) key, 1, -1, -1);
       headMap.insert(key, head);
       head.insertItem(isLeft, value, headMap, itemMap);
       headMap.update(key, head);
     }
     mbean.getKeysMetric().logTime(System.nanoTime() - startNS);
   } catch (ObjectGridException e) {
     mbean.getKeysMetric().logException(e);
     e.printStackTrace();
     throw new ObjectGridRuntimeException(e);
   }
   return null;
 }
  @Override
  public void run() {
    Thread videoDecoder = new Thread(new VideoDecoder(this));
    videoDecoder.start();
    long lastFrameWrite = System.nanoTime() - NANOSECONDS_PER_FRAME;
    long timeNow = 0;

    try {
      while ((!videoDecoded || !imgBuffer.isEmpty()) && frame.isVisible()) {
        timeNow = System.nanoTime();
        if (timeNow - lastFrameWrite >= NANOSECONDS_PER_FRAME) {
          lastFrameWrite = timeNow;
          BufferedImage img = imgBuffer.take();
          g.drawImage(img, 0, 0, frame.getWidth(), frame.getHeight(), null);

          ByteArrayOutputStream bos = new ByteArrayOutputStream();
          ImageIO.write(img, "jpg", bos);
          proxy.receiveImage(ByteBuffer.wrap(bos.toByteArray()));
        }
      }
    } catch (IOException | InterruptedException e) {
      // other user has disconnected, stop sending video
    }

    imgBuffer.clear();
    frame.setVisible(false);
    try {
      proxy.setFrameVisible(true, false);
    } catch (IOException e) {
      System.err.println("The other user has disconnected, stopping video.");
    }
  }
  public void onDrawFrame(GL10 gl) {
    GLGameState state = null;

    synchronized (stateChanged) {
      state = this.state;
    }

    if (state == GLGameState.Running) {
      float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
      startTime = System.nanoTime();

      screen.update(deltaTime);
      screen.present(deltaTime);
    }

    if (state == GLGameState.Paused) {
      screen.pause();
      synchronized (stateChanged) {
        this.state = GLGameState.Idle;
        stateChanged.notifyAll();
      }
    }

    if (state == GLGameState.Finished) {
      screen.pause();
      screen.dispose();
      synchronized (stateChanged) {
        this.state = GLGameState.Idle;
        stateChanged.notifyAll();
      }
    }
  }
Example #30
0
  /** L'oggetto gioco viene lanciato da un thread. Run lancia il thread della classe Gioco. */
  public void run() {

    inizializza();

    int fps = 60;
    double tempoDiAggiornamento = 1000000000 / fps;
    double tempoDiAggiornamentoMenu = 1000000000 / 55;
    double delta = 0;
    long ora;
    long ultimoTempo = System.nanoTime();
    double ultimoCiclo = 0;

    while (inCorso) {
      ora = System.nanoTime();
      // frame dinamico
      if (h.getGioco().getStato() instanceof StatoGioco)
        ultimoCiclo = (ora - ultimoTempo) / tempoDiAggiornamento;
      else ultimoCiclo = (ora - ultimoTempo) / tempoDiAggiornamentoMenu;
      delta += ultimoCiclo;
      ultimoTempo = ora;
      if (delta >= 1) {
        aggiorna();
        disegna();
        delta--;

        // Se l'errore accumulato si avvicina a 1 viene ribassato
        // alla quantità ultimoCiclo. Tutto ciò serve a evitare due
        // aggiornamenti consecutivi del gioco.

        if (delta + ultimoCiclo >= 1) delta = ultimoCiclo;
      }
    }

    stop();
  }