Example #1
0
 @Override
 public final void add(final EventType elem) {
   do {
     if (isFreeLock.compareAndSet(true, false)) {
       final RokkaQueue<EventType> tq = actualRokkaQueueRef.get();
       if (tq.add(elem)) {
         boolean callSignalConsumer = false;
         if (signalEnabled.compareAndSet(true, false)) // && tq.getPosition() == 1
         {
           callSignalConsumer = true;
         }
         isFreeLock.set(true);
         if (callSignalConsumer) {
           signalConsumer.signal(this);
         }
         return;
       } else {
         isFreeLock.set(true);
         try {
           Thread.yield();
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
     }
   } while (true);
 }
Example #2
0
  @Override
  public final boolean add(final EventType elem, final int timeOut) {
    long startTime = System.currentTimeMillis();

    do {
      if (isFreeLock.compareAndSet(true, false)) {
        final RokkaQueue<EventType> tq = actualRokkaQueueRef.get();
        if (tq.add(elem)) {
          boolean callSignalConsumer = false;
          if (signalEnabled.compareAndSet(true, false)) {
            callSignalConsumer = true;
          }
          isFreeLock.set(true);
          if (callSignalConsumer) {
            signalConsumer.signal(this);
          }
          return true;
        } else {
          isFreeLock.set(true);
          try {
            Thread.yield();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    } while (startTime + timeOut > System.currentTimeMillis());
    return false;
  }
Example #3
0
  public synchronized void warmUp() throws Exception {
    if (endpointDone.compareAndSet(false, true)) {
      // endpoints should only be started once as they can be reused on other routes
      // and whatnot, thus their lifecycle is to start once, and only to stop when Camel shutdown
      for (Route route : routes) {
        // ensure endpoint is started first (before the route services, such as the consumer)
        ServiceHelper.startService(route.getEndpoint());
      }
    }

    if (warmUpDone.compareAndSet(false, true)) {

      for (Route route : routes) {
        // warm up the route first
        route.warmUp();

        LOG.debug("Starting services on route: {}", route.getId());
        List<Service> services = route.getServices();

        // callback that we are staring these services
        route.onStartingServices(services);

        // gather list of services to start as we need to start child services as well
        Set<Service> list = new LinkedHashSet<Service>();
        for (Service service : services) {
          list.addAll(ServiceHelper.getChildServices(service));
        }

        // split into consumers and child services as we need to start the consumers
        // afterwards to avoid them being active while the others start
        List<Service> childServices = new ArrayList<Service>();
        for (Service service : list) {

          // inject the route
          if (service instanceof RouteAware) {
            ((RouteAware) service).setRoute(route);
          }

          if (service instanceof Consumer) {
            inputs.put(route, (Consumer) service);
          } else {
            childServices.add(service);
          }
        }
        startChildService(route, childServices);

        // fire event
        EventHelper.notifyRouteAdded(camelContext, route);
      }

      // ensure lifecycle strategy is invoked which among others enlist the route in JMX
      for (LifecycleStrategy strategy : camelContext.getLifecycleStrategies()) {
        strategy.onRoutesAdd(routes);
      }

      // add routes to camel context
      camelContext.addRouteCollection(routes);
    }
  }
Example #4
0
  /**
   * process trade message
   *
   * @param tradeMessage
   */
  public void processTrade(Trade trade) {
    if (logger.isTraceEnabled()) {
      logger.trace("processTrade:" + trade);
    }

    if (_recentTrades.size() >= MarketInterface._maxRecentTrades) {
      ((LinkedList<Trade>) _recentTrades).removeFirst();
    }

    ((LinkedList<Trade>) _recentTrades).addLast(trade);

    if (MDFUtil.canProcessTrade(trade)) {
      if (_statistics == null) {
        _statistics = new MarketStatistics();
      }

      if (!trade.isAdjusted()) {
        _statistics.setLastTradeQuantity(trade.getTradeMessage().Quantity);
        _statistics.setLastTradePrice(trade.getTradeMessage().Price);
        _statistics.setLastTradeDateTime(trade.getTradeMessage().DateTime);
      } else {
        ListIterator<Trade> list =
            ((LinkedList<Trade>) _recentTrades).listIterator(_recentTrades.size());
        Trade lastTradeEligibleForLastDeal = null;
        while (list.hasPrevious()) {
          lastTradeEligibleForLastDeal = (Trade) list.previous();
          if (!lastTradeEligibleForLastDeal.isCancelled()
              && (lastTradeEligibleForLastDeal.getInvestigationStatus() == null
                  || lastTradeEligibleForLastDeal.getInvestigationStatus().getStatus()
                      != InvestigationStatus.STATUS_UNDER_INVESTIGATION)) {
            break;
          }
        }
        int qty = trade.getTradeMessage().Quantity;
        long price = trade.getTradeMessage().Price;
        long dateTime = trade.getTradeMessage().DateTime;

        if (lastTradeEligibleForLastDeal != null
            && lastTradeEligibleForLastDeal.getTradeMessage().DateTime
                > trade.getTradeMessage().DateTime) {
          qty = lastTradeEligibleForLastDeal.getTradeMessage().Quantity;
          price = lastTradeEligibleForLastDeal.getTradeMessage().Price;
          dateTime = lastTradeEligibleForLastDeal.getTradeMessage().DateTime;
        }
        _statistics.setLastTradeQuantity(qty);
        _statistics.setLastTradePrice(price);
        _statistics.setLastTradeDateTime(dateTime);
      }

      // ((LinkedList<Trade>)_recentTrades).addLast(trade);
    }

    _orderUpdated.compareAndSet(false, true);

    _tradeHistoryUpdated.compareAndSet(false, true);

    return;
  }
Example #5
0
 public void addRequestNum() {
   reqNum++;
   System.out.println("requestNum.incrementAndGet=" + requestNum.incrementAndGet());
   if (errorControll.compareAndSet(true, false)) {
     System.out.println("#errorNum.incrementAndGet=" + errorNum.incrementAndGet());
   } else {
     errorControll.compareAndSet(false, true);
     System.out.println("#errorControll.compareAndSet(false, true);");
   }
 }
  @Override
  public void apply() {
    if (mLeakCanaryAlreadyEnabled.compareAndSet(false, true)) {
      mLeakCanaryProxy.init();
    }

    if (mStethoAlreadyEnabled.compareAndSet(false, true)) {
      Stetho.initializeWithDefaults(mRestestApplication);
      mOkHttpClient.interceptors().add(new StethoInterceptor());
    }
  }
Example #7
0
 /** {@inheritDoc} */
 public void execute(ISchedulingService service) {
   // ensure the job is not already running
   if (running.compareAndSet(false, true)) {
     // get now
     long now = System.currentTimeMillis();
     // get the current bytes read count on the connection
     long currentReadBytes = getReadBytes();
     // get our last bytes read count
     long previousReadBytes = lastBytesRead.get();
     log.debug(
         "Time now: {} current read count: {} last read count: {}",
         new Object[] {now, currentReadBytes, previousReadBytes});
     if (currentReadBytes > previousReadBytes) {
       log.debug("Client is still alive, no ping needed");
       // client has sent data since last check and thus is not dead. No need to ping
       if (lastBytesRead.compareAndSet(previousReadBytes, currentReadBytes)) {
         // update the timestamp to match our update
         lastBytesReadTime = now;
       }
     } else {
       // client didn't send response to ping command and didn't sent data for too long,
       // disconnect
       long lastPingTime = lastPingSent.get();
       long lastPongTime = lastPongReceived.get();
       if (lastPongTime > 0
           && (lastPingTime - lastPongTime > maxInactivity)
           && !(now - lastBytesReadTime < maxInactivity)) {
         log.debug("Keep alive job name {}", keepAliveJobName);
         if (log.isTraceEnabled()) {
           log.trace("Scheduled job list");
           for (String jobName : service.getScheduledJobNames()) {
             log.trace("Job: {}", jobName);
           }
         }
         service.removeScheduledJob(keepAliveJobName);
         keepAliveJobName = null;
         log.warn(
             "Closing {}, with id {}, due to too much inactivity ({} ms), last ping sent {} ms ago",
             new Object[] {
               RTMPConnection.this, getId(), (lastPingTime - lastPongTime), (now - lastPingTime)
             });
         // Add the following line to (hopefully) deal with a very common support request
         // on the Red5 list
         log.warn(
             "This often happens if YOUR Red5 application generated an exception on start-up. Check earlier in the log for that exception first!");
         onInactive();
       }
       // send ping command to client to trigger sending of data
       ping();
     }
     // reset running flag
     running.compareAndSet(true, false);
   }
 }
Example #8
0
    /**
     * This method is used to detect the following special initialization case. IF no FactoryManager
     * can be found for key, AND this call to getApplicationFactoryManager() *does* have a current
     * FacesContext BUT a previous call to getApplicationFactoryManager *did not* have a current
     * FacesContext
     *
     * @param facesContext the current FacesContext for this request
     * @return true if the current execution falls into the special initialization case.
     */
    private boolean detectSpecialInitializationCase(FacesContext facesContext) {
      boolean result = false;
      if (null == facesContext) {
        logNullFacesContext.compareAndSet(false, true);
      } else {
        logNonNullFacesContext.compareAndSet(false, true);
      }
      result = logNullFacesContext.get() && logNonNullFacesContext.get();

      return result;
    }
Example #9
0
  public void initialize() {
    logger.info("Initialize...");

    if (_statistics != null) {
      _statistics = null;
    }

    _recentTrades.clear();

    _orderUpdated.compareAndSet(false, true);
    _tradeHistoryUpdated.compareAndSet(false, true);
  }
Example #10
0
 /** Calls close on the tree object */
 public void close() throws IOException {
   synchronized (this) {
     try {
       if (isClosed.compareAndSet(false, true) && isOpen.compareAndSet(true, false)) {
         if (used.get() > 0 || active.size() > 0) {
           log.warn("closing with leases={}, active queries={}", used, active.size());
         }
       }
       cancelActiveThreads();
     } finally {
       tree.close();
     }
   }
 }
  @Override
  public void close() {
    if (stopped.compareAndSet(false, true)) { // make sure we only stop once
      try {
        worker.close();
      } catch (Exception e) {
        log.workerException(e);
      }

      this.allIndexesManager.stop();
      this.timingSource.stop();

      serviceManager.releaseAllServices();

      for (Analyzer an : this.analyzers.values()) {
        an.close();
      }
      for (AbstractDocumentBuilder documentBuilder :
          this.documentBuildersContainedEntities.values()) {
        documentBuilder.close();
      }
      for (EntityIndexBinding entityIndexBinding : this.indexBindingForEntities.values()) {
        entityIndexBinding.getDocumentBuilder().close();
      }

      // unregister statistic mbean
      if (statisticsMBeanName != null) {
        JMXRegistrar.unRegisterMBean(statisticsMBeanName);
      }
    }
  }
 @Override
 public synchronized void close() {
   if (closed.compareAndSet(false, true)) {
     FutureUtils.cancel(scheduledFuture);
     scheduledFuture = null;
   }
 }
  @RequestMapping(
      value = "/import",
      method = {RequestMethod.GET, RequestMethod.POST})
  @ResponseBody
  public Map<String, Object> input(Date beginDate, Date endDate) {
    Map<String, Object> rsMap = new HashMap<String, Object>();
    boolean success = false;
    String message = "";

    if (isRun.compareAndSet(false, true)) {
      logger.info("Begin order import");

      try {
        orderBizHandler.input(cfgList, beginDate, endDate);

        success = true;
      } catch (Exception exp) {
        logger.error("Importing TAOBAO order error ", exp);
        message = exp.getMessage();
      } finally {
        isRun.set(false);
        logger.info("End import");
      }
    } else {
      logger.error("Import is running!");
    }

    rsMap.put("success", success);
    rsMap.put("message", message);

    return rsMap;
  }
Example #14
0
 public synchronized void cancel() throws SQLException {
   if (openResultSet != null) {
     openResultSet.cancel();
   }
   // If there is an open result set, it probably just set the same flag.
   cancelFlag.compareAndSet(false, true);
 }
  /**
   * Check if a configuration update is needed.
   *
   * <p>There are two main reasons that can trigger a configuration update. Either there is a
   * configuration update happening in the cluster, or operations added to the queue can not find
   * their corresponding node. For the latter, see the {@link #pastReconnThreshold()} method for
   * further details.
   *
   * <p>If a configuration update is needed, a resubscription for configuration updates is
   * triggered. Note that since reconnection takes some time, the method will also wait a time
   * period given by {@link #getMinReconnectInterval()} before the resubscription is triggered.
   */
  void checkConfigUpdate() {
    if (needsReconnect || pastReconnThreshold()) {
      long now = System.currentTimeMillis();
      long intervalWaited = now - this.configProviderLastUpdateTimestamp;
      if (intervalWaited < this.getMinReconnectInterval()) {
        LOGGER.log(
            Level.FINE,
            "Ignoring config update check. Only {0}ms out"
                + " of a threshold of {1}ms since last update.",
            new Object[] {intervalWaited, this.getMinReconnectInterval()});
        return;
      }

      if (doingResubscribe.compareAndSet(false, true)) {
        resubConfigUpdate();
      } else {
        LOGGER.log(Level.CONFIG, "Duplicate resubscribe for config updates" + " suppressed.");
      }
    } else {
      LOGGER.log(
          Level.FINE,
          "No reconnect required, though check requested."
              + " Current config check is {0} out of a threshold of {1}.",
          new Object[] {configThresholdCount, maxConfigCheck});
    }
  }
 public void close() throws NamingException {
   if (closed.compareAndSet(false, true)) {
     for (CloseTask closeTask : closeTasks) {
       closeTask.close(false);
     }
   }
 }
 /**
  * Writes response metadata to the channel if not already written previously and channel is
  * active.
  *
  * @param responseMetadata the {@link HttpResponse} that needs to be written.
  * @param listener the {@link GenericFutureListener} that needs to be attached to the write.
  * @return {@code true} if response metadata was written to the channel in this call. {@code
  *     false} otherwise.
  */
 private boolean maybeWriteResponseMetadata(
     HttpResponse responseMetadata, GenericFutureListener<ChannelFuture> listener) {
   long writeProcessingStartTime = System.currentTimeMillis();
   boolean writtenThisTime = false;
   if (responseMetadataWritten.compareAndSet(false, true)) {
     // we do some manipulation here for chunking. According to the HTTP spec, we can have either a
     // Content-Length
     // or Transfer-Encoding:chunked, never both. So we check for Content-Length - if it is not
     // there, we add
     // Transfer-Encoding:chunked. Note that sending HttpContent chunks data anyway - we are just
     // explicitly specifying
     // this in the header.
     if (!HttpHeaders.isContentLengthSet(responseMetadata)) {
       // This makes sure that we don't stomp on any existing transfer-encoding.
       HttpHeaders.setTransferEncodingChunked(responseMetadata);
     }
     logger.trace(
         "Sending response with status {} on channel {}",
         responseMetadata.getStatus(),
         ctx.channel());
     ChannelPromise writePromise = ctx.newPromise().addListener(listener);
     ctx.writeAndFlush(responseMetadata, writePromise);
     writtenThisTime = true;
     long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime;
     nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime);
   }
   return writtenThisTime;
 }
Example #18
0
    @Override
    public void shutdown(final Callback<None> callback) {
      if (_shutdown.compareAndSet(false, true)) {
        _client.shutdown(
            new Callback<None>() {
              @Override
              public void onSuccess(None none) {
                try {
                  callback.onSuccess(none);
                } finally {
                  clientShutdown();
                }
              }

              @Override
              public void onError(Throwable e) {
                try {
                  callback.onError(e);
                } finally {
                  clientShutdown();
                }
              }
            });
      } else {
        callback.onError(new IllegalStateException("shutdown has already been requested."));
      }
    }
 /**
  * Computes the default Hadoop configuration path.
  *
  * @param environmentVariables the current environment variables
  * @return the detected configuration path, or {@code null} if the configuration path is not found
  * @since 0.6.0
  */
 public static URL getConfigurationPath(Map<String, String> environmentVariables) {
   if (environmentVariables == null) {
     throw new IllegalArgumentException("environmentVariables must not be null"); // $NON-NLS-1$
   }
   File conf = getConfigurationDirectory(environmentVariables);
   if (conf == null) {
     // show warning only the first time
     if (SAW_HADOOP_CONF_MISSING.compareAndSet(false, true)) {
       LOG.warn("Hadoop configuration path is not found");
     }
     return null;
   }
   if (conf.isDirectory() == false) {
     LOG.warn(
         MessageFormat.format(
             "Failed to load default Hadoop configurations ({0} is not a valid installation path)",
             conf));
     return null;
   }
   try {
     return conf.toURI().toURL();
   } catch (MalformedURLException e) {
     LOG.warn(
         MessageFormat.format(
             "Failed to load default Hadoop configurations ({0} is unrecognized to convert URL)",
             conf),
         e);
     return null;
   }
 }
  public boolean shouldNotify() {
    if (mParentRequest != null) {
      return mParentRequest.shouldNotify();
    }

    return mNotified.compareAndSet(true, false);
  }
 @Override
 public Set loadAllKeys() {
   if (first.compareAndSet(true, false)) {
     throw new IllegalStateException("Intentional exception");
   }
   return singleton("key");
 }
  /**
   * Closes all connected clients sockets, then closes the underlying ServerSocketChannel,
   * effectively killing the server socket selectorthread, freeing the port the server was bound to
   * and stops all internal workerthreads.
   *
   * <p>If this method is called before the server is started it will never start.
   *
   * @param timeout Specifies how many milliseconds shall pass between initiating the close
   *     handshakes with the connected clients and closing the servers socket channel.
   * @throws IOException When {@link ServerSocketChannel}.close throws an IOException
   * @throws InterruptedException
   */
  public void stop(int timeout) throws IOException, InterruptedException {
    if (!isclosed.compareAndSet(false, true)) {
      return;
    }

    synchronized (connections) {
      for (WebSocket ws : connections) {
        ws.close(CloseFrame.GOING_AWAY);
      }
    }
    synchronized (this) {
      if (selectorthread != null) {
        if (Thread.currentThread() != selectorthread) {}

        if (selectorthread != Thread.currentThread()) {
          selectorthread.interrupt();
          selectorthread.join();
        }
      }
      if (decoders != null) {
        for (WebSocketWorker w : decoders) {
          w.interrupt();
        }
      }
      if (server != null) {
        server.close();
      }
    }
  }
 public void finalize() {
   if (closed.compareAndSet(false, true)) {
     for (CloseTask closeTask : closeTasks) {
       closeTask.close(true);
     }
   }
 }
  /**
   * Will only ever be accessed by a single thread. Rechecks the target update time again in case a
   * second write thread was blocking the current one. {@link #lastUpdateRun} gets set to a negative
   * value to specify that this method is currently running.
   */
  public void doUpdate() {

    // Check whether entry is required.
    if (!state.get().checkNeedsUpdate(forceUpdateInterval)) {
      return;
    }

    // Prevent recursion!
    // ------------------
    // To prevent another call from entering this block it's
    // necessary to set active
    if (!active.compareAndSet(false, true)) {
      return;
    }

    try {
      final Set<String> ids = sessions.keySet();
      log.info("Synchronizing session cache. Count = " + ids.size());
      final StopWatch sw = new Slf4JStopWatch();
      for (String id : ids) {
        reload(id);
      }

      sw.stop("omero.sessions.synchronization");
      log.info(String.format("Synchronization took %s ms.", sw.getElapsedTime()));

    } catch (Exception e) {
      log.error("Error synchronizing cache", e);
    } finally {
      active.set(false);
    }
  }
  /**
   * If received lostAdvName: <br>
   * Stop the scheduled timer. <br>
   * set isReachable to false
   *
   * @param args @param args Event handler argument
   */
  private void handleLostAdvName(Map<String, Object> args) {
    String foundSender = (String) args.get("SENDER");

    Log.d(
        TAG,
        "Received lostAdvertisedName of sender: '"
            + foundSender
            + "', my sender name is: '"
            + sender
            + "'");
    if (foundSender == null || !foundSender.equals(sender)) {
      Log.v(TAG, "Received sender: '" + foundSender + "' doesn't belong to this device");
      return;
    }

    stopDeviceFoundVerificationService();

    // Atomically sets the value to the given updated value if the current value == the expected
    // value.
    // Returns - true if successful. False return indicates that the actual value was not equal to
    // the expected value
    if (isReachable.compareAndSet(true, false)) {
      boolean newVal = isReachable.get();
      Log.d(TAG, "The device: '" + deviceId + "' isReachable set to: '" + newVal + "'");
      deviceRegistry.reachabilityChanged(this, newVal);
    }
  } // handleLostAdvName
 private void updateCurrentlyServingReplica(
     ScannerCallable scanner, Result[] result, AtomicBoolean done, ExecutorService pool) {
   if (done.compareAndSet(false, true)) {
     if (currentScannerCallable != scanner) replicaSwitched.set(true);
     currentScannerCallable = scanner;
     // store where to start the replica scanner from if we need to.
     if (result != null && result.length != 0) this.lastResult = result[result.length - 1];
     if (LOG.isTraceEnabled()) {
       LOG.trace(
           "Setting current scanner as "
               + currentScannerCallable.scannerId
               + " associated with "
               + currentScannerCallable.getHRegionInfo().getReplicaId());
     }
     // close all outstanding replica scanners but the one we heard back from
     outstandingCallables.remove(scanner);
     for (ScannerCallable s : outstandingCallables) {
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Closing scanner "
                 + s.scannerId
                 + " because this was slow and another replica succeeded");
       }
       // Submit the "close" to the pool since this might take time, and we don't
       // want to wait for the "close" to happen yet. The "wait" will happen when
       // the table is closed (when the awaitTermination of the underlying pool is called)
       s.setClose();
       RetryingRPC r = new RetryingRPC(s);
       pool.submit(r);
     }
     // now clear outstandingCallables since we scheduled a close for all the contained scanners
     outstandingCallables.clear();
   }
 }
 /**
  * Start the CachedDirectoryLookupService.
  *
  * <p>It is thread safe.
  */
 @Override
 public void start() {
   if (isStarted.compareAndSet(false, true)) {
     super.start();
     initCacheSyncTask();
   }
 }
Example #28
0
  /**
   * @param cancel {@code True} to close with cancellation.
   * @throws GridException If failed.
   */
  @Override
  public void close(boolean cancel) throws GridException {
    if (!closed.compareAndSet(false, true)) return;

    busyLock.block();

    if (log.isDebugEnabled())
      log.debug("Closing data loader [ldr=" + this + ", cancel=" + cancel + ']');

    GridException e = null;

    try {
      // Assuming that no methods are called on this loader after this method is called.
      if (cancel) {
        cancelled = true;

        for (Buffer buf : bufMappings.values()) buf.cancelAll();
      } else doFlush();

      ctx.event().removeLocalEventListener(discoLsnr);

      ctx.io().removeMessageListener(topic);
    } catch (GridException e0) {
      e = e0;
    }

    fut.onDone(null, e);

    if (e != null) throw e;
  }
 @Override
 public void finish() {
   if (finished.compareAndSet(false, true)) {
     consumeRemaining();
     downstream.finish();
   }
 }
Example #30
0
 private void performShutdown() {
   if (myShutDown.compareAndSet(false, true)) {
     LOG.info("VFS dispose started");
     FSRecords.dispose();
     LOG.info("VFS dispose completed");
   }
 }