Example #1
0
 /**
  * Grab ledger entry page whose first entry is <code>pageEntry</code>.
  *
  * <p>If the page doesn't existed before, we allocate a memory page. Otherwise, we grab a clean
  * page and read it from disk.
  *
  * @param ledger Ledger Id
  * @param pageEntry Start entry of this entry page.
  */
 private LedgerEntryPage grabLedgerEntryPage(long ledger, long pageEntry) throws IOException {
   LedgerEntryPage lep = grabCleanPage(ledger, pageEntry);
   try {
     // should get the up to date page from the persistence manager
     // before we put it into table otherwise we would put
     // an empty page in it
     indexPersistenceManager.updatePage(lep);
     LedgerEntryPage oldLep;
     if (lep != (oldLep = pageMapAndList.putPage(lep))) {
       lep.releasePage();
       // Decrement the page count because we couldn't put this lep in the page cache.
       pageCount.decrementAndGet();
       // Increment the use count of the old lep because this is unexpected
       oldLep.usePage();
       lep = oldLep;
     }
   } catch (IOException ie) {
     // if we grab a clean page, but failed to update the page
     // we are exhausting the count of ledger entry pages.
     // since this page will be never used, so we need to decrement
     // page count of ledger cache.
     lep.releasePage();
     pageCount.decrementAndGet();
     throw ie;
   }
   return lep;
 }
  protected void afterEnd(Map<?, ?> flags, Task<?> task) {
    activeTaskCount.decrementAndGet();
    incompleteTaskCount.decrementAndGet();

    if (log.isTraceEnabled()) log.trace(this + " afterEnd, task: " + task);
    ExecutionUtils.invoke(flags.get("newTaskEndCallback"), task);

    PerThreadCurrentTaskHolder.perThreadCurrentTask.remove();
    ((TaskInternal<?>) task).setEndTimeUtc(System.currentTimeMillis());
    // clear thread _after_ endTime set, so we won't get a null thread when there is no end-time
    if (RENAME_THREADS) {
      String newThreadName = "brooklyn-" + Identifiers.makeRandomId(8);
      task.getThread().setName(newThreadName);
    }
    ((TaskInternal<?>) task).setThread(null);
    synchronized (task) {
      task.notifyAll();
    }

    for (ExecutionListener listener : listeners) {
      try {
        listener.onTaskDone(task);
      } catch (Exception e) {
        log.warn("Error notifying listener " + listener + " of task " + task + " done", e);
      }
    }
  }
 /** decrementAndGet decrements and returns current value */
 public void testDecrementAndGet() {
   AtomicInteger ai = new AtomicInteger(1);
   assertEquals(0, ai.decrementAndGet());
   assertEquals(-1, ai.decrementAndGet());
   assertEquals(-2, ai.decrementAndGet());
   assertEquals(-2, ai.get());
 }
 @Override
 public void response(IPaxosMessage pmsg) {
   if (pmsg instanceof AcceptedMessage) {
     if (((AcceptedMessage) pmsg).isNack()) {
       if (nackcount.incrementAndGet() >= expectedResponses) condition.signal();
     } else {
       IPaxosValue value = pmsg.getPaxosValue();
       //				System.out.println("expectedValue = " +
       // (expectedValue==null?null:expectedValue.getValue()));
       //				System.out.println("responseValue = " + (value==null?null:value.getValue()));
       // normal paxos phase 2
       if (expectedValue != null && value != null) {
         if (expectedValue.equals(value)) {
           if (responses.decrementAndGet() == 0) condition.signal();
         }
       }
       // no-op value phase 2, consistency level should be all
       // need to receive all responses, or any value got more than half of all responses
       else {
         if (responseValues.get(value) != null) {
           if (responseValues.get(value).incrementAndGet() >= expectedResponses)
             condition.signal();
         } else {
           synchronized (this) {
             if (responseValues.get(value) == null) {
               responseValues.put(value, new AtomicInteger(1));
               if (1 >= expectedResponses) condition.signal();
             }
           }
         }
         if (totalResponses.decrementAndGet() == 0) condition.signal();
       }
     }
   }
 }
Example #5
0
  public void newCharacter(CharacterEvent ce) {
    int oldChar2type;

    // Previous character not typed correctly - 1 point penalty
    if (ce.source == generator.get()) {
      oldChar2type = char2type.getAndSet(ce.character); // 接收随机字母

      if (oldChar2type != -1) {
        score.decrementAndGet();
        setScore();
      }
    }
    // If character is extraneous - 1 point penalty
    // If character does not match - 1 point penalty
    else if (ce.source == typist.get()) {
      // 在此有个假设:即正在使用的该变量值不会被变更且程序代码完成时也是如此
      // 所有已经被我们设定的具有特定值的变量就应当是那个值。
      while (true) {
        oldChar2type = char2type.get(); // 获取上次已接收到的随机字母

        if (oldChar2type != ce.character) { // ce.character是用户输入的字母,现在作比较
          score.decrementAndGet();
          break;
        } else if (char2type.compareAndSet(oldChar2type, -1)) {
          score.incrementAndGet();
          break;
        }
      }

      setScore();
    }
  }
  @Override
  public void releaseClient(HClient client) throws HectorException {
    if (cassandraHost.getMaxActive() == 0) {
      client.close();
    }
    boolean open = client.isOpen();
    if (open) {
      if (active.get()) {
        addClientToPoolGently(client);
      } else {
        log.info(
            "Open client {} released to in-active pool for host {}. Closing.",
            client,
            cassandraHost);
        client.close();
      }
    } else {
      try {
        addClientToPoolGently(createClient());
      } catch (HectorTransportException e) {
        // if unable to open client then don't add one back to the pool
        log.error("Transport exception in re-opening client in release on {}", getName());
      }
    }

    realActiveClientsCount.decrementAndGet();
    activeClientsCount.decrementAndGet();

    if (log.isTraceEnabled()) {
      log.trace("Status of releaseClient {} to queue: {}", client.toString(), open);
    }
  }
  @Override
  public void releaseClient(CassandraConnectionHandle conn) throws SQLException {
    boolean open;
    try {
      open = !conn.isClosed();
    } catch (SQLException e) {
      // Tight to Cassandra Driver implementation. It should not happen.
      open = false;
    }

    if (open) {
      if (active.get()) {
        addClientToPoolGently(conn);
      } else {
        log.info("Open client released to in-active pool for host {}. Closing.", cassandraHost);
        closeConnection(conn);
      }
    } else {
      try {
        addClientToPoolGently(createConnection());
      } catch (SQLException e) {
        log.info("Unable to reopen a connection. Bad server. Message: " + e.getMessage());
      }
    }

    realActiveConnectionCount.decrementAndGet();
    activeConnectionCount.decrementAndGet();

    if (log.isDebugEnabled()) {
      log.debug("Status of releaseClient {} to queue: {}", cassandraHost.getHost(), open);
    }
  }
Example #8
0
  private boolean addConnectionIfUnderMaximum() {
    for (; ; ) {
      int opened = open.get();
      if (opened >= options().getMaxConnectionsPerHost()) return false;

      if (open.compareAndSet(opened, opened + 1)) break;
    }

    if (isClosed()) {
      open.decrementAndGet();
      return false;
    }

    try {
      connections.add(session.connectionFactory().open(this));
      signalAvailableConnection();
      return true;
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      // Skip the open but ignore otherwise
      open.decrementAndGet();
      return false;
    } catch (ConnectionException e) {
      open.decrementAndGet();
      logger.debug("Connection error to {} while creating additional connection", host);
      return false;
    }
  }
  @SuppressWarnings("deprecation")
  protected void afterEnd(Map flags, Task<?> task) {
    activeTaskCount.decrementAndGet();
    incompleteTaskCount.decrementAndGet();

    if (log.isTraceEnabled()) log.trace(this + " afterEnd, task: " + task);
    ExecutionUtils.invoke(flags.get("newTaskEndCallback"), task);
    List l = (List) flags.get("tagLinkedPreprocessors");
    Collections.reverse(l);
    for (Object li : l) {
      TaskPreprocessor t = (TaskPreprocessor) li;
      t.onEnd(flags, task);
    }

    PerThreadCurrentTaskHolder.perThreadCurrentTask.remove();
    ((BasicTask) task).endTimeUtc = System.currentTimeMillis();
    // clear thread _after_ endTime set, so we won't get a null thread when there is no end-time
    if (RENAME_THREADS) {
      String newThreadName = "brooklyn-" + LanguageUtils.newUid();
      ((BasicTask) task).thread.setName(newThreadName);
    }
    ((BasicTask) task).thread = null;
    synchronized (task) {
      task.notifyAll();
    }

    ExpirationPolicy expirationPolicy = (ExpirationPolicy) flags.get("expirationPolicy");
    if (expirationPolicy == null) expirationPolicy = ExpirationPolicy.IMMEDIATE;
    if (expirationPolicy == ExpirationPolicy.IMMEDIATE) {
      for (Object t : ((BasicTask) task).tags) {
        getMutableTasksWithTag(t).remove(task);
      }
    }
  }
 void onQueryPhaseFailure(
     final int shardIndex, final AtomicInteger counter, final long searchId, Throwable t) {
   if (logger.isDebugEnabled()) {
     logger.debug("[{}] Failed to execute query phase", t, searchId);
   }
   addShardFailure(shardIndex, new ShardSearchFailure(t));
   successfulOps.decrementAndGet();
   if (counter.decrementAndGet() == 0) {
     executeFetchPhase();
   }
 }
Example #11
0
 private StreamState removeActiveStream(int streamId, boolean remote) {
   StreamState state = activeStreams.remove(streamId);
   if (state != null) {
     if (remote) {
       activeRemoteStreams.decrementAndGet();
     } else {
       activeLocalStreams.decrementAndGet();
     }
   }
   return state;
 }
        @Override
        public void run() {
          if (BuildConfig.DEBUG) Log.d(TAG, "downloadCompletionThread was started");
          while (!isInterrupted()) {
            try {
              Downloader downloader = downloadExecutor.take().get();
              if (BuildConfig.DEBUG) Log.d(TAG, "Received 'Download Complete' - message.");
              removeDownload(downloader);
              DownloadStatus status = downloader.getResult();
              boolean successful = status.isSuccessful();

              final int type = status.getFeedfileType();
              if (successful) {
                if (type == Feed.FEEDFILETYPE_FEED) {
                  handleCompletedFeedDownload(downloader.getDownloadRequest());
                } else if (type == FeedImage.FEEDFILETYPE_FEEDIMAGE) {
                  handleCompletedImageDownload(status, downloader.getDownloadRequest());
                } else if (type == FeedMedia.FEEDFILETYPE_FEEDMEDIA) {
                  handleCompletedFeedMediaDownload(status, downloader.getDownloadRequest());
                }
              } else {
                numberOfDownloads.decrementAndGet();
                if (!status.isCancelled()) {
                  if (status.getReason() == DownloadError.ERROR_UNAUTHORIZED) {
                    postAuthenticationNotification(downloader.getDownloadRequest());
                  } else if (status.getReason() == DownloadError.ERROR_HTTP_DATA_ERROR
                      && Integer.valueOf(status.getReasonDetailed())
                          == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {

                    Log.d(TAG, "Requested invalid range, restarting download from the beginning");
                    FileUtils.deleteQuietly(
                        new File(downloader.getDownloadRequest().getDestination()));
                    DownloadRequester.getInstance()
                        .download(DownloadService.this, downloader.getDownloadRequest());
                  } else {
                    Log.e(TAG, "Download failed");
                    saveDownloadStatus(status);
                    handleFailedDownload(status, downloader.getDownloadRequest());
                  }
                }
                sendDownloadHandledIntent();
                queryDownloadsAsync();
              }
            } catch (InterruptedException e) {
              if (BuildConfig.DEBUG) Log.d(TAG, "DownloadCompletionThread was interrupted");
            } catch (ExecutionException e) {
              e.printStackTrace();
              numberOfDownloads.decrementAndGet();
            }
          }
          if (BuildConfig.DEBUG) Log.d(TAG, "End of downloadCompletionThread");
        }
Example #13
0
  Object doExecute(String requestName, Statement statement, Method method, Object[] args)
      throws IllegalAccessException, InvocationTargetException {
    assert requestName != null;
    assert statement != null;
    assert method != null;

    // on ignore les requêtes explain exécutées par DatabaseInformations
    if (!sqlCounter.isDisplayed() || requestName.startsWith("explain ")) {
      ACTIVE_CONNECTION_COUNT.incrementAndGet();
      try {
        return method.invoke(statement, args);
      } finally {
        ACTIVE_CONNECTION_COUNT.decrementAndGet();
      }
    }

    final long start = System.currentTimeMillis();
    boolean systemError = true;
    try {
      ACTIVE_CONNECTION_COUNT.incrementAndGet();

      // note perf: selon un paramètre current-sql(/requests)-disabled,
      // on pourrait ici ne pas binder un nouveau contexte à chaque requête sql
      sqlCounter.bindContext(requestName, requestName, null, -1);

      final Object result = method.invoke(statement, args);
      systemError = false;
      return result;
    } catch (final InvocationTargetException e) {
      if (e.getCause() instanceof SQLException) {
        final int errorCode = ((SQLException) e.getCause()).getErrorCode();
        if (errorCode >= 20000 && errorCode < 30000) {
          // Dans Oracle par exemple, les erreurs 20000 à 30000 sont standardisées
          // comme étant des erreurs lancées par l'application dans des procédures stockées
          // pour être traitées comme des erreurs de saisies ou comme des règles de gestion.
          // Ce ne sont donc pas des erreurs systèmes.
          systemError = false;
        }
      }
      throw e;
    } finally {
      // Rq : on n'utilise pas la création du statement et l'appel à la méthode close du statement
      // comme début et fin d'une connexion active, car en fonction de l'application
      // la méthode close du statement peut ne jamais être appelée
      // (par exemple, seule la méthode close de la connection peut être appelée ce qui ferme aussi
      // le statement)
      // Rq : pas de temps cpu pour les requêtes sql car c'est 0 ou quasiment 0
      ACTIVE_CONNECTION_COUNT.decrementAndGet();
      final long duration = Math.max(System.currentTimeMillis() - start, 0);
      sqlCounter.addRequest(requestName, duration, -1, systemError, -1);
    }
  }
  /**
   * Create a new WebView.
   *
   * @param frameSize The size of the WebView rectangle.
   * @throws UnsupportedOperationException if this class is instantiated on a non-Windows operating
   *     system.
   * @throws WWRuntimeException if creating the native web browser window fails for any reason. For
   *     example, because the process has run out of User Object handles (see documentation <a
   *     href="#limits">above</a>).
   */
  public WindowsWebView(Dimension frameSize) {
    if (frameSize == null) {
      String message = Logging.getMessage("nullValue.SizeIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (!Configuration.isWindowsOS()) {
      String message =
          Logging.getMessage(
              "NativeLib.UnsupportedOperatingSystem",
              "Windows WebView",
              System.getProperty("os.name"));
      Logging.logger().severe(message);
      throw new UnsupportedOperationException(message);
    }

    this.frameSize = frameSize;

    try {
      // Increment the instance counter
      instances.incrementAndGet();

      // Make sure that the message loop thread is running
      this.ensureMessageLoopRunning();

      // Create the web view
      this.webViewWindowPtr = WindowsWebViewJNI.newWebViewWindow(webViewMessageLoop);
      if (this.webViewWindowPtr == 0) {
        String message = Logging.getMessage("WebView.NativeExceptionInitializingWebView");
        Logging.logger().severe(message);
        throw new WWRuntimeException(message);
      }

      WindowsWebViewJNI.setFrameSize(
          this.webViewWindowPtr, this.frameSize.width, this.frameSize.height);

      this.observerPtr = WindowsWebViewJNI.newNotificationAdapter(this);

      WindowsWebViewJNI.addWindowUpdateObserver(this.webViewWindowPtr, observerPtr);
    } catch (RuntimeException e) {
      // If the WebView was not created successfully do not increment the instance counter.
      instances.decrementAndGet();
      this.handleWebViewCreationError();
      throw e;
    } catch (Error e) {
      // If the WebView was not created successfully do not increment the instance counter.
      instances.decrementAndGet();
      this.handleWebViewCreationError();
      throw e;
    }
  }
    @Override
    public void run() {
      // long startTime = System.nanoTime();
      synchronized (configFile) {
        if (pendingDiskWrites.get() > 1) {
          // Writes can be skipped, because they are stored in a queue (in the executor).
          // Only the last is actually written.
          pendingDiskWrites.decrementAndGet();
          // LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() -
          // startTime) + " nsec.");
          return;
        }
        try {
          Files.createParentDirs(configFile);

          if (!configFile.exists()) {
            try {
              LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString()));
              if (!configFile.createNewFile()) {
                LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
                return;
              }
            } catch (IOException ex) {
              LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex);
              return;
            }
          }

          final FileOutputStream fos = new FileOutputStream(configFile);
          try {
            final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8);

            try {
              writer.write(data);
            } finally {
              writer.close();
            }
          } finally {
            fos.close();
          }
        } catch (IOException e) {
          LOGGER.log(Level.SEVERE, e.getMessage(), e);
        } finally {
          // LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() -
          // startTime) + " nsec.");
          pendingDiskWrites.decrementAndGet();
        }
      }
    }
    public void start() {
      if (scrollId.getContext().length == 0) {
        listener.onFailure(
            new SearchPhaseExecutionException(
                "query", "no nodes to search on", ShardSearchFailure.EMPTY_ARRAY));
        return;
      }

      ScrollIdForNode[] context = scrollId.getContext();
      for (int i = 0; i < context.length; i++) {
        ScrollIdForNode target = context[i];
        DiscoveryNode node = nodes.get(target.getNode());
        if (node != null) {
          executePhase(i, node, target.getScrollId());
        } else {
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Node ["
                    + target.getNode()
                    + "] not available for scroll request ["
                    + scrollId.getSource()
                    + "]");
          }
          successfulOps.decrementAndGet();
          if (counter.decrementAndGet() == 0) {
            finishHim();
          }
        }
      }

      for (ScrollIdForNode target : scrollId.getContext()) {
        DiscoveryNode node = nodes.get(target.getNode());
        if (node == null) {
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Node ["
                    + target.getNode()
                    + "] not available for scroll request ["
                    + scrollId.getSource()
                    + "]");
          }
          successfulOps.decrementAndGet();
          if (counter.decrementAndGet() == 0) {
            finishHim();
          }
        }
      }
    }
  @Override
  @SuppressWarnings("unchecked")
  public V load(K key) {
    File file = getFile(key);
    if (!file.exists()) return null;

    log.tracef("Loading state from %s", file);
    try {
      FileInputStream inputStream = null;
      try {
        inputStream = FISAction.open(file);
        SimpleDataInput input = new SimpleDataInput(Marshalling.createByteInput(inputStream));
        int version = input.readInt();
        MarshallingConfiguration config =
            this.passivationManager.getMarshallingConfiguration(version);
        Unmarshaller unmarshaller = this.marshallerFactory.createUnmarshaller(config);
        unmarshaller.start(input);
        try {
          V value = (V) unmarshaller.readObject();
          unmarshaller.finish();
          counter.decrementAndGet();
          return value;
        } finally {
          unmarshaller.close();
        }
      } finally {
        safeClose(inputStream);
        DeleteFileAction.delete(file);
      }
    } catch (Exception e) {
      throw EjbMessages.MESSAGES.activationFailed(e, key);
    }
  }
Example #18
0
 /** Records an execution failure. */
 void recordFailure() {
   try {
     state.get().recordFailure();
   } finally {
     currentExecutions.decrementAndGet();
   }
 }
Example #19
0
 /** Records an execution success. */
 public void recordSuccess() {
   try {
     state.get().recordSuccess();
   } finally {
     currentExecutions.decrementAndGet();
   }
 }
Example #20
0
  private void unjoinChat() {
    if (thisSession.getUserProperties().containsKey("USER")) {
      LOG.debug("unjoinChat(): " + thisSession.getUserProperties().get("USER"));

      sessionService.removeOnSessionDestroyedListener(callback);

      if (isHttpSessionValid) {
        int sessionIdleTime =
            (int) ((System.currentTimeMillis() - httpSession.getLastAccessedTime()) / 1000);
        LOG.debug("Max idle timeout: " + (sessionIdleTime + defaultSessionTimeout));
        httpSession.setMaxInactiveInterval(sessionIdleTime + defaultSessionTimeout);
      }

      int userNb = usersLoggedIn.decrementAndGet();

      Message infoMsg = new Message();

      infoMsg.TYPE = "INFO";
      infoMsg.SUBTYPE = "JOIN";
      infoMsg.INFO_MSG = thisSession.getUserProperties().get("USER") + " has left the building";
      infoMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!";
      infoMsg.USER_LIST = buildUserList(false);

      thisSession.getUserProperties().clear();

      broadcastMessage(infoMsg, false);
    }
  }
 public HistoryFileInfo remove(JobId key) {
   HistoryFileInfo ret = cache.remove(key);
   if (ret != null) {
     mapSize.decrementAndGet();
   }
   return ret;
 }
 /** Notify controller is ready */
 public void notifyReady() {
   if (readySelectorHandlerCounter.decrementAndGet() == 0) {
     for (ControllerStateListener stateListener : stateListeners) {
       stateListener.onReady();
     }
   }
 }
Example #23
0
    /**
     * Remove the node from the runnable indices
     *
     * @param node node to remove
     */
    public void deleteRunnable(ClusterNode node) {
      String host = node.getHost();

      if (LOG.isDebugEnabled()) {
        LOG.debug(node.getName() + " deleted from runnable list for type: " + type);
      }

      NodeContainer nodeContainer = hostToRunnableNodes.get(host);
      if (nodeContainer != null) {
        synchronized (nodeContainer) {
          if (nodeContainer.removeNode(node)) {
            /**
             * We are not removing the nodeContainer from runnable nodes map since we are
             * synchronizing operations with runnable indices on it
             */
            hostsWithRunnableNodes.decrementAndGet();
          }
        }
      }

      Node rack = node.hostNode.getParent();

      nodeContainer = rackToRunnableNodes.get(rack);
      if (nodeContainer != null) {
        synchronized (nodeContainer) {
          /**
           * We are not removing the nodeContainer from runnable nodes map since we are
           * synchronizing operations with runnable indices on it
           */
          nodeContainer.removeNode(node);
        }
      }
    }
  @Override
  public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain)
      throws IOException, ServletException {

    try {
      HttpServletResponse hrsp = (HttpServletResponse) rsp;
      if (maxConnections > 0) {

        if (active.getAndIncrement() > maxConnections) {
          String msg = maxConnectionMessage;
          if (msg == null)
            msg =
                "Too many simultaneous requests (this is a small server, after all, this is not a commercial service)";
          hrsp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
          return;
        }
      }

      Coordination c = coordinator.begin("osgi.enroute.webrequest." + active.incrementAndGet(), 0);
      try {
        chain.doFilter(req, rsp);
        c.end();
      } catch (Throwable t) {
        c.fail(t);
        throw t;
      }
    } finally {
      active.decrementAndGet();
    }
  }
Example #25
0
  /**
   * Take a byte buffer from the pool. The caller is responsible of calling release() once for the
   * returned buffer to return it to the pool.
   */
  public ByteBuffer take() {
    ByteBuffer buffer = availPool.poll();
    if (buffer != null) return buffer;

    if (numBuffers.incrementAndGet() <= maxBuffers) {
      log.debug("increasing buffer pool size to {}", numBuffers.get());
      ByteBuffer buf = BytesUtil.instance.allocateDirect(bufSize);
      bufferPool.put(buf, PRESENT);
      return buf;
    } else {
      numBuffers.decrementAndGet();
      /* Temporary buffers are non-direct because the NIO library has its
       * own cache for them, managing this case more cleverly than we
       * we can from here. The library will get the buffer from its cache
       * when a write is requested, so it will be able to release it
       * immediately, whereas we would leave the task up to the garbage
       * collector.
       *
       * The price we pay for allocating a non-direct buffer is one extra
       * copy at write-time.
       */
      log.info("pool is empty, allocating a temporary buffer");
      return BytesUtil.instance.allocate(bufSize);
    }
  }
Example #26
0
 public Http11Processor poll() {
   Http11Processor result = super.poll();
   if (result != null) {
     size.decrementAndGet();
   }
   return result;
 }
  private ProBInstance startProlog() {
    ProcessHandle processTuple = processProvider.get();
    Process process = processTuple.getProcess();
    String key = processTuple.getKey();
    final BufferedReader stream =
        new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));

    Map<Class<? extends AbstractCliPattern<?>>, AbstractCliPattern<?>> cliInformation =
        extractCliInformation(stream);

    Integer port = ((PortPattern) cliInformation.get(PortPattern.class)).getValue();
    Long userInterruptReference =
        ((InterruptRefPattern) cliInformation.get(InterruptRefPattern.class)).getValue();

    ProBConnection connection = new ProBConnection(key, port);

    try {
      processCounter.incrementAndGet();
      connection.connect();
      ProBInstance cli =
          new ProBInstance(
              process, stream, userInterruptReference, connection, home, osInfo, processCounter);
      processes.add(new WeakReference<ProBInstance>(cli));
      return cli;
    } catch (IOException e) {
      processCounter.decrementAndGet();
      logger.error("Error connecting to Prolog binary.", e);
      return null;
    }
  }
Example #28
0
  /**
   * Best-effort attempt to remove an argument from a batch. This may get invoked when a
   * cancellation occurs somewhere downstream. This method finds the first occurrence of an argument
   * in the batch, and removes that occurrence.
   *
   * <p>This is currently O(n). If an O(1) approach is needed, then we need to refactor internals to
   * use a Map instead of Queue. My first pass at this is fairly naive, on the suspicion that
   * unsubscription will be rare enough to not cause a perf problem.
   *
   * @param arg argument to remove from batch
   */
  /* package-private */ void remove(RequestArgumentType arg) {
    if (batchStarted.get()) {
      // nothing we can do
      return;
    }

    if (batchLock.readLock().tryLock()) {
      try {
        /* double-check now that we have the lock - if the batch is started, deleting is useless */
        if (batchStarted.get()) {
          return;
        }

        for (CollapsedRequest<ResponseType, RequestArgumentType> collapsedRequest :
            batchArgumentQueue) {
          if (arg.equals(collapsedRequest.getArgument())) {
            batchArgumentQueue.remove(collapsedRequest);
            count.decrementAndGet();
            return; // just remove a single instance
          }
        }
      } finally {
        batchLock.readLock().unlock();
      }
    }
  }
  @Override
  public void handlePerspective(
      final Message<Event, Object> action, final PerspectiveLayout perspectiveLayout) {
    if (action.messageBodyEquals(MessageUtil.INIT)) {

      perspectiveLayout.registerRootComponent(createRoot());
      GridPane.setVgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS);
      GridPane.setHgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS);

      // register left panel
      perspectiveLayout.registerTargetLayoutComponent("content0", this.content1);
      perspectiveLayout.registerTargetLayoutComponent("content1", this.content2);
      perspectiveLayout.registerTargetLayoutComponent("content2", this.content3);
      ApplicationLauncherPerspectiveMessaginTest.latch.countDown();
    } else {
      if (counter.get() > 1) {
        counter.decrementAndGet();
        context.send("id10", "message");
      } else {
        System.out.println("Perspective id12: FINISH");
        if (wait.getCount() > 0) wait.countDown();
        if (PerspectiveMessagingTestP1.wait.getCount() > 0) context.send("id10", "message");
      }
    }
  }
Example #30
0
    private Driver createDriver(
        DriverContext driverContext, @Nullable ScheduledSplit partitionedSplit) {
      Driver driver = driverFactory.createDriver(driverContext);

      // record driver so other threads add unpartitioned sources can see the driver
      // NOTE: this MUST be done before reading unpartitionedSources, so we see a consistent view of
      // the unpartitioned sources
      drivers.add(new WeakReference<>(driver));

      if (partitionedSplit != null) {
        // TableScanOperator requires partitioned split to be added before the first call to process
        driver.updateSource(
            new TaskSource(partitionedSourceId, ImmutableSet.of(partitionedSplit), true));
      }

      // add unpartitioned sources
      for (TaskSource source : unpartitionedSources.values()) {
        driver.updateSource(source);
      }

      pendingCreation.decrementAndGet();
      closeDriverFactoryIfFullyCreated();

      return driver;
    }