/** 填充内存缓存队列 */
  private void loadMessages() {
    // 刚启动的时候,可能还没有数据文件,当第一次调用add方法时会导致填充任务真正开始
    if (StringUtils.isBlank(memCacheFileReading)) {
      try {
        latch.await();
      } catch (InterruptedException e) {
        log.error("lacth interruptted", e);
        return;
      }
      switchReadFile(null);
    }

    // 每次循环加载一个文件
    while (!stopped.get()) {

      ObjectInputStream oi = openInputStream();
      seek(oi, memCacheLoadPos);
      // 响应线程池的shutdown或者cancel
      if (Thread.interrupted() || stopped.get()) {
        return;
      }
      loadFromFile(oi);
      // 响应线程池的shutdown或者cancel
      if (Thread.interrupted() || stopped.get()) {
        return;
      }
      switchReadFile(oi);
    }
  }
Exemplo n.º 2
1
  /**
   * Parse an XML document from a location identified by an URI reference. If the URI contains a
   * fragment identifier (see section 4.1 in ), the behavior is not defined by this specification.
   */
  public Document parseURI(String uri) throws LSException {

    // If DOMParser insstance is already busy parsing another document when this
    // method is called, then raise INVALID_STATE_ERR according to DOM L3 LS spec
    if (fBusy) {
      String msg =
          DOMMessageFormatter.formatMessage(
              DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null);
      throw new DOMException(DOMException.INVALID_STATE_ERR, msg);
    }

    XMLInputSource source = new XMLInputSource(null, uri, null, false);
    try {
      currentThread = Thread.currentThread();
      fBusy = true;
      parse(source);
      fBusy = false;
      if (abortNow && currentThread.isInterrupted()) {
        // reset interrupt state
        abortNow = false;
        Thread.interrupted();
      }
    } catch (Exception e) {
      fBusy = false;
      if (abortNow && currentThread.isInterrupted()) {
        Thread.interrupted();
      }
      if (abortNow) {
        abortNow = false;
        restoreHandlers();
        return null;
      }
      // Consume this exception if the user
      // issued an interrupt or an abort.
      if (e != Abort.INSTANCE) {
        if (!(e instanceof XMLParseException) && fErrorHandler != null) {
          DOMErrorImpl error = new DOMErrorImpl();
          error.fException = e;
          error.fMessage = e.getMessage();
          error.fSeverity = DOMError.SEVERITY_FATAL_ERROR;
          fErrorHandler.getErrorHandler().handleError(error);
        }
        if (DEBUG) {
          e.printStackTrace();
        }
        throw (LSException) DOMUtil.createLSException(LSException.PARSE_ERR, e).fillInStackTrace();
      }
    }
    Document doc = getDocument();
    dropDocumentReferences();
    return doc;
  }
Exemplo n.º 3
1
  /** Parse an XML document from a resource identified by an <code>LSInput</code>. */
  public Document parse(LSInput is) throws LSException {

    // need to wrap the LSInput with an XMLInputSource
    XMLInputSource xmlInputSource = dom2xmlInputSource(is);
    if (fBusy) {
      String msg =
          DOMMessageFormatter.formatMessage(
              DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null);
      throw new DOMException(DOMException.INVALID_STATE_ERR, msg);
    }

    try {
      currentThread = Thread.currentThread();
      fBusy = true;
      parse(xmlInputSource);
      fBusy = false;
      if (abortNow && currentThread.isInterrupted()) {
        // reset interrupt state
        abortNow = false;
        Thread.interrupted();
      }
    } catch (Exception e) {
      fBusy = false;
      if (abortNow && currentThread.isInterrupted()) {
        Thread.interrupted();
      }
      if (abortNow) {
        abortNow = false;
        restoreHandlers();
        return null;
      }
      // Consume this exception if the user
      // issued an interrupt or an abort.
      if (e != Abort.INSTANCE) {
        if (!(e instanceof XMLParseException) && fErrorHandler != null) {
          DOMErrorImpl error = new DOMErrorImpl();
          error.fException = e;
          error.fMessage = e.getMessage();
          error.fSeverity = DOMError.SEVERITY_FATAL_ERROR;
          fErrorHandler.getErrorHandler().handleError(error);
        }
        if (DEBUG) {
          e.printStackTrace();
        }
        throw (LSException) DOMUtil.createLSException(LSException.PARSE_ERR, e).fillInStackTrace();
      }
    }
    Document doc = getDocument();
    dropDocumentReferences();
    return doc;
  }
Exemplo n.º 4
0
 @Override
 public void end(Board board) throws InterruptedException {
   if (Thread.interrupted()) throw new InterruptedException();
   updateValue(board);
   while (!completedUpdate) {
     if (Thread.interrupted()) throw new InterruptedException();
   }
 }
Exemplo n.º 5
0
  private String trainFace(String tid, String userId) throws InterruptedException {
    HttpURLConnection con;
    URL url;
    String payload = null;
    try {
      url =
          new URL(
              this.TRAIN_URI
                  + "?api_key="
                  + this.API_KEY
                  + "&api_secret="
                  + this.API_SECRET
                  + "&uids="
                  + userId);

      con = (HttpURLConnection) url.openConnection();
      // Check if task has been interrupted
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
      con.setReadTimeout(10000 /* milliseconds */);
      con.setConnectTimeout(15000 /* milliseconds */);

      con.setRequestMethod("GET");
      con.setDoInput(true);
      // Start the query
      Log.i(TAG, "Start trainFace " + this.TRAIN_URI);
      con.connect();
      Log.i(TAG, "Finish trainFace " + this.TRAIN_URI);
      // Check if task has been interrupted
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
      // Read results from the query
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
      payload = reader.readLine();
      reader.close();
      payload.length();

      if (con != null) {
        con.disconnect();
      }
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return payload;
  }
Exemplo n.º 6
0
 public void record2(DataOutputStream dos) {
   try {
     mRecorder = new Recorder();
     mRecorder.StartRecord(dos);
     while (isRecording) {
       if (Thread.interrupted())
         Log.e("YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY", "" + Thread.interrupted());
     }
     mRecorder.StopRecord();
   } catch (Exception t) {
     Log.e("AudioRecord", "Recording Failed - " + t);
   }
   return;
 }
Exemplo n.º 7
0
 /**
  * Adds the specified element to this queue, waiting if necessary for another thread to receive
  * it.
  *
  * @throws InterruptedException {@inheritDoc}
  * @throws NullPointerException {@inheritDoc}
  */
 public void put(E o) throws InterruptedException {
   if (o == null) throw new NullPointerException();
   if (transferer.transfer(o, false, 0) == null) {
     Thread.interrupted();
     throw new InterruptedException();
   }
 }
Exemplo n.º 8
0
 public void run() {
   int temp = 0;
   System.out.println("Iniciar contador:");
   try {
     if (!Thread.interrupted()) {
       while (temp < 10) {
         System.out.println("Tiempo restante " + (10 - temp) + " segundos");
         Thread.sleep(1000);
         temp++;
       }
     }
   } catch (InterruptedException x) {
     if (temp > 5) {
       System.out.println("Interrumpido despues de 5 segundos, cerramos el programa");
     } else {
       System.out.println(
           "Interrumpido antes de 5 segundos, el programa se cerrará en 10 segundos");
       try {
         Thread.sleep(10000);
       } catch (InterruptedException e) {
       }
       System.out.println("Fin 10 segundos");
     }
     return;
   }
   System.out.println("Finalizado");
 }
Exemplo n.º 9
0
    public void doReadLoop() {
      HttpContext context = new BasicHttpContext();
      context.setAttribute(CX_SOCKET, rawSocket);

      while (!Thread.interrupted() && this.htConn.isOpen() && HttpServer.this.shouldRun) {
        // Clear the context from any auth settings; since this is done
        // anew on each connection..
        context.removeAttribute(CX_AUTH);

        try {
          HttpServer.this.httpService.handleRequest(htConn, context);
        } catch (ConnectionClosedException ex_closed) {
          break;
        } catch (IOException ex) {
          if (!closeRequested) {
            ex.printStackTrace();
          }
          break;
        } catch (HttpException ex) {
          ex.printStackTrace();
          break;
        } catch (ResponseHandledException ex) {
          break;
        }
      }
      bail();
    }
Exemplo n.º 10
0
 @Override
 protected void runInContext() {
   HttpContext context = new BasicHttpContext(null);
   try {
     while (!Thread.interrupted() && _conn.isOpen()) {
       _httpService.handleRequest(_conn, context);
       _conn.close();
     }
   } catch (ConnectionClosedException ex) {
     if (s_logger.isTraceEnabled()) {
       s_logger.trace("ApiServer:  Client closed connection");
     }
   } catch (IOException ex) {
     if (s_logger.isTraceEnabled()) {
       s_logger.trace("ApiServer:  IOException - " + ex);
     }
   } catch (HttpException ex) {
     s_logger.warn("ApiServer:  Unrecoverable HTTP protocol violation" + ex);
   } finally {
     try {
       _conn.shutdown();
     } catch (IOException ignore) {
     }
   }
 }
Exemplo n.º 11
0
 public void run() {
   try {
     in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
     while (!Thread.interrupted()) {
       String value = in.readUTF();
       if (ConfigSettings.instance().isActivateStats()) {
         StatsCommunication.instance().sent(value.getBytes().length);
       }
       if (ConfigSettings.instance().isDumpMessages()) {
         System.out.println("Received: " + value);
       }
       Message message = (Message) MessageSerializer.readMessage(value);
       consumer.receive(message);
     }
   } catch (Throwable t) {
     t.printStackTrace();
   } finally {
     consumer = null;
     try {
       out.close();
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
 }
 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))));
 }
    /* (non-Javadoc)
     * @see edu.umd.cs.findbugs.classfile.ICodeBaseIterator#hasNext()
     */
    public boolean hasNext() throws InterruptedException {
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }

      return ze != null;
    }
Exemplo n.º 14
0
  private Pair<Map<String, String>, /*was it created now?*/ Boolean> getOrCreateIndexConfig(
      Class<? extends PropertyContainer> cls,
      String indexName,
      Map<String, String> suppliedConfig) {
    Pair<Map<String, String>, Boolean> result =
        findIndexConfig(cls, indexName, suppliedConfig, config.getParams());
    boolean createdNow = false;
    if (result.other()) { // Ok, we need to create this config
      synchronized (this) { // Were we the first ones to get here?
        Map<String, String> existing = indexStore.get(cls, indexName);
        if (existing != null) {
          // No, someone else made it before us, cool
          assertConfigMatches(
              getIndexProvider(existing.get(PROVIDER)), indexName, existing, result.first());
          return Pair.of(result.first(), false);
        }

        // We were the first one here, let's create this config
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        try {
          executorService.submit(new IndexCreatorJob(cls, indexName, result.first())).get();
          indexStore.set(cls, indexName, result.first());
          createdNow = true;
        } catch (ExecutionException ex) {
          throw new TransactionFailureException(
              "Index creation failed for " + indexName + ", " + result.first(), ex.getCause());
        } catch (InterruptedException ex) {
          Thread.interrupted();
        } finally {
          executorService.shutdownNow();
        }
      }
    }
    return Pair.of(result.first(), createdNow);
  }
Exemplo n.º 15
0
  private void backgroundOperationsLoop() {
    AuthInfo auth = authInfo.getAndSet(null);
    if (auth != null) {
      try {
        client.getZooKeeper().addAuthInfo(auth.scheme, auth.auth);
      } catch (Exception e) {
        logError("addAuthInfo for background operation threw exception", e);
        return;
      }
    }

    while (!Thread.interrupted()) {
      OperationAndData<?> operationAndData;
      try {
        operationAndData = backgroundOperations.take();
        if (debugListener != null) {
          debugListener.listen(operationAndData);
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        break;
      }

      performBackgroundOperation(operationAndData);
    }
  }
Exemplo n.º 16
0
  @Override
  public void run() {
    try {
      while (!Thread.interrupted()) {
        synchronized (this) {
          while (restaurant.meal != null) {
            wait();
          }
        }

        if (++count == 11) {
          System.out.println("菜上齐了");
          // 这块只是向 chef 和 waiter 发送一个 interrupt 信号
          // 但是因为 synchronized 和 IO 是不能被中断的,所以这里会通过可中断的
          // sleep()抛出 InterruptedException。
          // 而 waiter 只能通过 while(Thread.interrupted())抛出的 InterruptedException返回

          // 而且我们会发现,多做了一个菜!本来做了10个就够了。11个本意想关闭程序,但是因为
          // synchronized 无法中断,只好又做了一个菜(厨师也饿了)。但是因为服务员在 wait(),可以被中断
          // 所以做好的菜没有被服务员上去。。。。
          restaurant.exec.shutdownNow();
        }

        System.out.print("做菜ing...");
        synchronized (restaurant.waiter) {
          restaurant.meal = new Meal(count);
          restaurant.waiter.notifyAll();
        }

        TimeUnit.MILLISECONDS.sleep(100);
      }
    } catch (InterruptedException e) {
      System.out.println("chef interrupted");
    }
  }
Exemplo n.º 17
0
  @Test(timeout = 90000)
  public void testRPCInterruptedSimple() throws IOException {
    final Configuration conf = new Configuration();
    Server server =
        new RPC.Builder(conf)
            .setProtocol(TestProtocol.class)
            .setInstance(new TestImpl())
            .setBindAddress(ADDRESS)
            .setPort(0)
            .setNumHandlers(5)
            .setVerbose(true)
            .setSecretManager(null)
            .build();

    server.start();
    InetSocketAddress addr = NetUtils.getConnectAddress(server);

    final TestProtocol proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
    // Connect to the server
    proxy.ping();
    // Interrupt self, try another call
    Thread.currentThread().interrupt();
    try {
      proxy.ping();
      fail("Interruption did not cause IPC to fail");
    } catch (IOException ioe) {
      if (!ioe.toString().contains("InterruptedException")) {
        throw ioe;
      }
      // clear interrupt status for future tests
      Thread.interrupted();
    }
  }
Exemplo n.º 18
0
  public void close() throws IOException {
    flush();

    if (!commitExecutor.isShutdown()) {
      commitExecutor.shutdown();
      try {
        if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES))
          throw new OException("Background data flush task can not be stopped.");
      } catch (InterruptedException e) {
        OLogManager.instance().error(this, "Data flush thread was interrupted");

        Thread.interrupted();
        throw new OException("Data flush thread was interrupted", e);
      }
    }

    synchronized (syncObject) {
      for (OFileClassic fileClassic : files.values()) {
        if (fileClassic.isOpen()) fileClassic.close();
      }

      if (nameIdMapHolder != null) {
        nameIdMapHolder.setLength(0);
        for (Map.Entry<String, Long> entry : nameIdMap.entrySet()) {
          writeNameIdEntry(new NameFileIdEntry(entry.getKey(), entry.getValue()), false);
        }
        nameIdMapHolder.getFD().sync();
        nameIdMapHolder.close();
      }
    }
  }
    @Override
    public void run() {
      if (!backlogStore.exists()) {
        return;
      }

      try (BufferedReader fr = new BufferedReader(new FileReader(backlogStore))) {
        while (!Thread.interrupted()) {
          String line = fr.readLine();
          if (line == null) {
            break;
          }

          try {
            messageHandler.processBackloggedMessage(fromString(line));
          } catch (IllegalStateException e) {
            LOGGER.debug("Unable to reload message; {}", e.getMessage());
          }
        }

        backlogStore.delete();
      } catch (FileNotFoundException e) {
        LOGGER.error("Unable to reload checkpoint file: {}", e.getMessage());
      } catch (IOException e) {
        LOGGER.error("Unrecoverable error during reload checkpoint file: {}", e.getMessage());
      }

      LOGGER.info("Done reloading backlogged messages.");
    }
Exemplo n.º 20
0
  public void delete() throws IOException {
    synchronized (syncObject) {
      for (long fileId : files.keySet()) doDeleteFile(fileId);

      if (nameIdMapHolderFile != null) {
        nameIdMapHolder.close();

        if (!nameIdMapHolderFile.delete())
          throw new OStorageException(
              "Can not delete disk cache file which contains name-id mapping.");
      }
    }

    if (!commitExecutor.isShutdown()) {
      commitExecutor.shutdown();
      try {
        if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES))
          throw new OException("Background data flush task can not be stopped.");
      } catch (InterruptedException e) {
        OLogManager.instance().error(this, "Data flush thread was interrupted");

        Thread.interrupted();
        throw new OException("Data flush thread was interrupted", e);
      }
    }
  }
Exemplo n.º 21
0
  /**
   * Creates new symbolic file system link from file or folder to another filesystem file. The
   * target path has to be present on disk.
   *
   * @param linkPath - filesystem path of the link being created.
   * @param realPath - file or folder on the file system, the target of the link.
   * @throws UnsupportedOperationException on Windows where links are not supported.
   * @throws IOException if execution of the command fails.
   */
  public static void createSymbolicLink(IPath linkPath, IPath realPath) throws IOException {
    if (!isSymbolicLinkSupported()) {
      throw new UnsupportedOperationException("Windows links .lnk are not supported.");
    }

    String command = "ln -s " + realPath.toOSString() + ' ' + linkPath.toOSString();
    Process process = Runtime.getRuntime().exec(command);

    // Wait for up to 2.5s...
    for (int i = 0; i < 5; i++) {
      try {
        Assert.assertTrue("ln process exited with non-zero status", process.waitFor() == 0);
        // If exitValue succeeded, then the process has exitted successfully.
        break;
      } catch (InterruptedException e) {
        // Clear interrupted state, see Java bug http://bugs.sun.com/view_bug.do?bug_id=6420270
        Thread.interrupted();
      }
      // wait for a 500ms before checking again
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        /*don't care*/
      }
    }
    Assert.assertTrue(
        "Symbolic link not created, command=[" + command + "]", linkPath.toFile().exists());
  }
Exemplo n.º 22
0
 /** @return <b>true</b> - if current task was interrupted; <b>false</b> - otherwise */
 private boolean isTaskInterrupted() {
   if (Thread.interrupted()) {
     log(LOG_TASK_INTERRUPTED);
     return true;
   }
   return false;
 }
 public static byte[] httpEntityToByteArray(final HttpEntity entity) throws IOException {
   if (entity == null) {
     throw new IllegalArgumentException("HTTP entity may not be null");
   }
   InputStream instream = entity.getContent();
   if (instream == null) {
     return new byte[] {};
   }
   if (entity.getContentLength() > Integer.MAX_VALUE) {
     throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
   }
   int i = (int) entity.getContentLength();
   if (i < 0) {
     i = 4096;
   }
   ByteArrayBuffer buffer = new ByteArrayBuffer(i);
   try {
     byte[] tmp = new byte[4096];
     int l;
     while ((l = instream.read(tmp)) != -1) {
       if (Thread.interrupted())
         throw new InterruptedIOException("File download process was canceled");
       buffer.append(tmp, 0, l);
     }
   } finally {
     instream.close();
   }
   return buffer.toByteArray();
 }
  @Override
  public final V get(final long timeout, final TimeUnit unit)
      throws InterruptedException, ExecutionException, TimeoutException {
    Object response = registerWaiter(Thread.currentThread(), null);
    if (response != VOID) {
      return resolveAndThrow(response);
    }

    long deadlineNanos = System.nanoTime() + unit.toNanos(timeout);
    boolean interrupted = false;
    try {
      long timeoutNanos = unit.toNanos(timeout);
      while (timeoutNanos > 0) {
        parkNanos(timeoutNanos);
        timeoutNanos = deadlineNanos - System.nanoTime();

        if (isDone()) {
          return resolveAndThrow(state);
        } else if (Thread.interrupted()) {
          interrupted = true;
          onInterruptDetected();
        }
      }
    } finally {
      restoreInterrupt(interrupted);
    }

    unregisterWaiter(Thread.currentThread());
    throw newTimeoutException(timeout, unit);
  }
Exemplo n.º 25
0
  private static <T> T lookupMBean(
      final Map<String, String> props,
      final Class<T> type,
      final Predicate<T> tester,
      final long timeout) {
    long until = System.currentTimeMillis() + timeout;
    do
      try {
        final T bean = Mbeans.lookup(jdbcJmxDomain, props, type);
        tester.apply(bean);
        return bean;
      } catch (UndeclaredThrowableException e) {
        if (Exceptions.isCausedBy(e, InstanceNotFoundException.class)) {
          if (System.currentTimeMillis() < until) {
            try {
              TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e1) {
              Thread.interrupted();
              break;
            }
            LOG.debug("Waiting for MBean " + type.getSimpleName() + "/" + props);
            continue;
          }
          throw new NoSuchElementException(type.getSimpleName() + " " + props.toString());
        } else {
          throw Exceptions.toUndeclared(e);
        }
      }
    while (System.currentTimeMillis() < until);

    throw new NoSuchElementException(type.getSimpleName() + " " + props.toString());
  }
Exemplo n.º 26
0
 private void sleepALittle() {
   try {
     Thread.sleep(100);
   } catch (InterruptedException e) {
     Thread.interrupted();
   }
 }
Exemplo n.º 27
0
  public HdfsDirectory(Path hdfsDirPath, LockFactory lockFactory, Configuration configuration)
      throws IOException {
    super(lockFactory);
    this.hdfsDirPath = hdfsDirPath;
    this.configuration = configuration;
    fileSystem = FileSystem.get(hdfsDirPath.toUri(), configuration);
    fileContext = FileContext.getFileContext(hdfsDirPath.toUri(), configuration);

    if (fileSystem instanceof DistributedFileSystem) {
      // Make sure dfs is not in safe mode
      while (((DistributedFileSystem) fileSystem).setSafeMode(SafeModeAction.SAFEMODE_GET, true)) {
        LOG.warn("The NameNode is in SafeMode - Solr will wait 5 seconds and try again.");
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          Thread.interrupted();
          // continue
        }
      }
    }

    try {
      if (!fileSystem.exists(hdfsDirPath)) {
        boolean success = fileSystem.mkdirs(hdfsDirPath);
        if (!success) {
          throw new RuntimeException("Could not create directory: " + hdfsDirPath);
        }
      }
    } catch (Exception e) {
      org.apache.solr.common.util.IOUtils.closeQuietly(fileSystem);
      throw new RuntimeException("Problem creating directory: " + hdfsDirPath, e);
    }
  }
Exemplo n.º 28
0
  /** Starts the game loop. */
  @Override
  public final void run() {
    try {
      initialize();

      long past;
      long latest = System.nanoTime();
      long difference;

      while (!Thread.interrupted()) {
        // handle game time
        past = latest;
        difference = GameTime.TARGET_CYCLE_TIME - (System.nanoTime() - past);
        if (difference > 0) {
          // wait if update performs too fast
          Thread.sleep((difference + 500000) / 1000000);
          gameTime.setRunningSlowly(false);
        } else {
          gameTime.setRunningSlowly(true);
        }
        latest = System.nanoTime();
        gameTime.setElapsedGameTime(latest - past);

        process();
      }
    } catch (InterruptedException ex) {
      // interrupted while thread was sleeping, do nothing
    } finally {
      unload();
    }
  }
Exemplo n.º 29
0
  /** Wait at most msecs millisconds for a permit. * */
  public boolean attempt(long msecs) throws InterruptedException {
    if (Thread.interrupted()) throw new InterruptedException();

    synchronized (this) {
      if (permits_ > 0) {
        --permits_;
        return true;
      } else if (msecs <= 0) return false;
      else {
        try {
          long startTime = System.currentTimeMillis();
          long waitTime = msecs;

          for (; ; ) {
            wait(waitTime);
            if (permits_ > 0) {
              --permits_;
              return true;
            } else {
              waitTime = msecs - (System.currentTimeMillis() - startTime);
              if (waitTime <= 0) return false;
            }
          }
        } catch (InterruptedException ex) {
          notify();
          throw ex;
        }
      }
    }
  }
Exemplo n.º 30
0
  @Override
  public void run() {
    try {
      while (true) {
        this.selector.select(SELECT_MILLISECONDS);
        if (Thread.interrupted()) break;

        Iterator<SelectionKey> i = this.selector.selectedKeys().iterator();
        while (i.hasNext()) {
          SelectionKey key = i.next();
          SelectableChannel channel = key.channel();
          handleReadableChannel(key, channel);
          handleWritableChannel(key, channel);
          i.remove();
        }
      }
    } catch (ClosedByInterruptException e) {
      // User-requested interrupt, so clean up
    } catch (IOException e) {
      reportIOException(e);
    }

    for (Map.Entry<SelectableChannel, SelectableChannel> e : this.outputs.entrySet()) {
      closeChannelAndReportException(e.getKey());
      closeChannelAndReportException(e.getValue());
    }

    for (SelectableChannel c : this.outputBuffers.keySet()) closeChannelAndReportException(c);
  }