protected void sendUpdates() {
    // get the current version
    int currentVersion = version.get();
    //
    boolean persist = isPersistentObject();
    // get read-only version of events
    ConcurrentLinkedQueue<ISharedObjectEvent> events =
        new ConcurrentLinkedQueue<ISharedObjectEvent>(ownerMessage.getEvents());
    // clear out previous events
    ownerMessage.getEvents().clear();
    //
    if (!events.isEmpty()) {
      // Send update to "owner" of this update request
      SharedObjectMessage syncOwner = new SharedObjectMessage(null, name, currentVersion, persist);
      syncOwner.addEvents(events);
      if (source != null) {
        // Only send updates when issued through RTMP request
        Channel channel = ((RTMPConnection) source).getChannel((byte) 3);
        if (channel != null) {
          // ownerMessage.acquire();
          channel.write(syncOwner);
          log.debug("Owner: {}", channel);
        } else {
          log.warn("No channel found for owner changes!?");
        }
      }
    }
    // clear owner events
    events.clear();
    // get read-only version of sync events
    events.addAll(syncEvents);
    // clear out previous events
    syncEvents.clear();
    if (!events.isEmpty()) {
      // Synchronize updates with the current listeners of this shared
      for (IEventListener listener : currentListeners) {
        if (listener == source) {
          // Don't re-send update to active client
          log.debug("Skipped {}", source);
          continue;
        }
        if (!(listener instanceof RTMPConnection)) {
          log.warn("Can't send sync message to unknown connection {}", listener);
          continue;
        }
        // Create a new sync message for every client to avoid
        // concurrent access through multiple threads
        // TODO: perhaps we could cache the generated message
        SharedObjectMessage syncMessage =
            new SharedObjectMessage(null, name, currentVersion, persist);
        syncMessage.addEvents(events);

        Channel channel = ((RTMPConnection) listener).getChannel((byte) 3);
        log.debug("Send to {}", channel);
        channel.write(syncMessage);
      }
    }
  }
 private void initSDCardPath() {
   if (!mExternalPathList.isEmpty()) {
     mSDCardPath = mExternalPathList.peek();
   } else if (!mInternalPathList.isEmpty()) {
     mSDCardPath = mInternalPathList.peek();
   } else {
     mSDCardPath = Environment.getExternalStorageDirectory().getPath();
   }
   Log.i(TAG, "initSDCardPath() === > SDCARD PATH = (" + mSDCardPath + ")");
 }
Example #3
0
  void sendPartitionInfos() {
    // check if the ExecutionVertex has already been archived and thus cleared the
    // partial partition infos queue
    if (partialInputChannelDeploymentDescriptors != null
        && !partialInputChannelDeploymentDescriptors.isEmpty()) {

      PartialInputChannelDeploymentDescriptor partialInputChannelDeploymentDescriptor;

      List<IntermediateDataSetID> resultIDs = new ArrayList<IntermediateDataSetID>();
      List<InputChannelDeploymentDescriptor> inputChannelDeploymentDescriptors =
          new ArrayList<InputChannelDeploymentDescriptor>();

      while ((partialInputChannelDeploymentDescriptor =
              partialInputChannelDeploymentDescriptors.poll())
          != null) {
        resultIDs.add(partialInputChannelDeploymentDescriptor.getResultId());
        inputChannelDeploymentDescriptors.add(
            partialInputChannelDeploymentDescriptor.createInputChannelDeploymentDescriptor(this));
      }

      UpdatePartitionInfo updateTaskMessage =
          createUpdateTaskMultiplePartitionInfos(
              attemptId, resultIDs, inputChannelDeploymentDescriptors);

      sendUpdatePartitionInfoRpcCall(assignedResource, updateTaskMessage);
    }
  }
 public void checkqueue() {
   if (!ismoving && !movequeue.isEmpty()) {
     ismoving = true;
     UI.instance.mainview.moveto = movequeue.poll();
     movequeue.remove(0);
   }
 }
 public String getNextInboundMessage() {
   String result = null;
   if (!inboundCommandQueue.isEmpty()) {
     result = inboundCommandQueue.poll();
   }
   return result;
 }
  /**
   * Releases any resources held by the writer.
   *
   * @param shutdownWrapped If the wrapped writer should be closed as well.
   */
  public void shutdown(boolean shutdownWrapped) {
    stopRequested.set(true);

    // Wait for publisher thread to terminate
    while (writerThread != null && writerThread.isAlive()) {
      try {
        // Interrupt the thread if its blocking
        writerThread.interrupt();
        writerThread.join();
      } catch (InterruptedException ex) {
        // Ignore; we gotta wait..
      }
    }

    // The writer writerThread SHOULD have drained the queue.
    // If not, handle outstanding requests ourselves,
    // and push them to the writer.
    while (!queue.isEmpty()) {
      String message = queue.poll();
      writer.writeRecord(message);
    }

    // Shutdown the wrapped writer.
    if (shutdownWrapped && writer != null) writer.shutdown();

    DirectoryServer.deregisterShutdownListener(this);
  }
Example #7
0
  /** Selects on sockets and informs their Communicator when there is something to do. */
  public void communicate(int timeout) {

    try {
      selector.select(timeout);
    } catch (IOException e) {
      // Not really sure why/when this happens yet
      return;
    }

    Iterator<SelectionKey> keys = selector.selectedKeys().iterator();

    while (keys.hasNext()) {
      SelectionKey key = keys.next();
      keys.remove();
      if (!key.isValid()) continue; // WHY
      Communicator communicator = (Communicator) key.attachment();

      if (key.isReadable()) communicator.onReadable();
      if (key.isWritable()) communicator.onWritable();
      if (key.isAcceptable()) communicator.onAcceptable();
    }

    // Go through the queue and handle each communicator
    while (!queue.isEmpty()) {
      Communicator c = queue.poll();
      c.onMemo();
    }
  }
 public void run() {
   // while (queue.size()>0) {
   while (!queue
       .isEmpty()) { // 这里不要用size()==0会非常耗时  会遍历一遍整个队列  而isEmpty()则是看看队列对头是否为空 要是为空则整个队列的大小就是0
     // while(queue.size()!=0){
     System.out.println(queue.poll());
   }
   latch.countDown();
 }
    void offer(Action action) {
      if (DEBUG) {
        assertOnIcThread();
        Log.d(
            LOGTAG, "offer: Action(" + getConstantName(Action.class, "TYPE_", action.mType) + ")");
      }
      /* Events don't need update because they generate text/selection
      notifications which will do the updating for us */
      if (action.mType != Action.TYPE_EVENT
          && action.mType != Action.TYPE_ACKNOWLEDGE_FOCUS
          && action.mType != Action.TYPE_SET_HANDLER) {
        action.mShouldUpdate = mUpdateGecko;
      }
      if (mActions.isEmpty()) {
        mActionsActive.acquireUninterruptibly();
        mActions.offer(action);
      } else
        synchronized (this) {
          // tryAcquire here in case Gecko thread has just released it
          mActionsActive.tryAcquire();
          mActions.offer(action);
        }

      switch (action.mType) {
        case Action.TYPE_EVENT:
        case Action.TYPE_SET_SELECTION:
        case Action.TYPE_SET_SPAN:
        case Action.TYPE_REMOVE_SPAN:
        case Action.TYPE_SET_HANDLER:
          onImeSynchronize();
          break;

        case Action.TYPE_REPLACE_TEXT:
          // try key events first
          sendCharKeyEvents(action);

          // fall-through

        case Action.TYPE_COMPOSE_TEXT:
          onImeReplaceText(
              action.mStart,
              action.mEnd,
              action.mSequence.toString(),
              action.mType == Action.TYPE_COMPOSE_TEXT);
          break;

        case Action.TYPE_ACKNOWLEDGE_FOCUS:
          onImeAcknowledgeFocus();
          break;

        default:
          throw new IllegalStateException("Action not processed");
      }

      ++mIcUpdateSeqno;
    }
Example #10
0
 private void scheduleNext() {
   if (!queue.isEmpty() && running.compareAndSet(false, true)) {
     try {
       executor.execute(runner);
     } catch (Throwable t) {
       running.set(false);
       throw t;
     }
   }
 }
  /**
   * Adds log messages for rendering.
   *
   * @param lines Builder of lines to render this frame.
   */
  private void renderLogMessages(ImmutableList.Builder<String> lines) {
    if (logEvents.isEmpty()) {
      return;
    }

    lines.add("Log:");
    for (LogEvent logEvent : logEvents) {
      formatLogEvent(logEvent, lines);
    }
  }
Example #12
0
 public MemcachedClient getMClient() {
   // TODO Auto-generated method stub
   MemcachedClient mc;
   if (availablePool.isEmpty()) {
     mc = createMClient();
   } else {
     mc = availablePool.poll();
     busyPool.add(mc);
   }
   return mc;
 }
Example #13
0
  void notifyDroneConnectionFailed(final ConnectionResult result) {
    if (droneListeners.isEmpty()) return;

    handler.post(
        new Runnable() {
          @Override
          public void run() {
            for (DroneListener listener : droneListeners) listener.onDroneConnectionFailed(result);
          }
        });
  }
 @Override
 public void run() {
   for (Map.Entry<String, ConcurrentLinkedQueue<HttpRequestTrace>> entry :
       connectionIdToRequestTracesMap.entrySet()) {
     final ConcurrentLinkedQueue<HttpRequestTrace> httpRequestTraces = entry.getValue();
     removeOldRequestTraces(httpRequestTraces);
     if (httpRequestTraces.isEmpty()) {
       removeOrphanEntry(entry);
     }
   }
 }
Example #15
0
  void notifyDroneServiceInterrupted(final String errorMsg) {
    if (droneListeners.isEmpty()) return;

    handler.post(
        new Runnable() {
          @Override
          public void run() {
            for (DroneListener listener : droneListeners)
              listener.onDroneServiceInterrupted(errorMsg);
          }
        });
  }
Example #16
0
    /** Remove the head of the queue. Throw if queue is empty. */
    void poll() {
      if (DEBUG) {
        ThreadUtils.assertOnGeckoThread();
      }
      if (mActions.poll() == null) {
        throw new IllegalStateException("empty actions queue");
      }

      synchronized (this) {
        if (mActions.isEmpty()) {
          mActionsActive.release();
        }
      }
    }
Example #17
0
 void syncWithGecko() {
   if (DEBUG) {
     assertOnIcThread();
   }
   if (mFocused && !mActions.isEmpty()) {
     if (DEBUG) {
       Log.d(LOGTAG, "syncWithGecko blocking on thread " + Thread.currentThread().getName());
     }
     mActionsActive.acquireUninterruptibly();
     mActionsActive.release();
   } else if (DEBUG && !mFocused) {
     Log.d(LOGTAG, "skipped syncWithGecko (no focus)");
   }
 }
 private boolean queueQuery(QuerySpec queryData) {
   queryData.searchQuery = mSearchQuery;
   Boolean queuedQuery;
   synchronized (mQueryQueue) {
     queuedQuery = false;
     Boolean doQueryNow = mQueryQueue.isEmpty();
     mQueryQueue.add(queryData);
     queuedQuery = true;
     if (doQueryNow) {
       doQuery(queryData);
     }
   }
   return queuedQuery;
 }
Example #19
0
 private synchronized void drainBuffer() {
   logger.debug("draining buffer");
   UILogger.getInstance().add("draining buffer");
   while (!notificationsBuffer.isEmpty()) {
     final ApnsNotification notification = notificationsBuffer.poll();
     try {
       sendMessage(notification, true);
     } catch (NetworkIOException ex) {
       // at this point we are retrying the submission of messages but failing to connect to APNS,
       // therefore
       // notify the client of this
       delegate.messageSendFailed(notification, ex);
     }
   }
 }
    public void run() {
      while (!this.server.isStopped()) {
        try {

          if (!queue.isEmpty()) {
            // System.out.println("queue not empty");
            this.free = false;
            flag = 0;
            WorkSet set = queue.poll();
            synchronized (refineSet) {
              if (set.sequence != refineSet.get(set)) {
                LOG.info("Job queue cache hit, the row is obsolete " + set.getRow());
                System.out.println("cache hits");
                continue;
              } else {
                refineSet.remove(set);
              }
            }
            // System.out.println("get job");
            set.getR()
                .updateCCIndex(set.getIndexSpec(), set.getRow(), set.getColumnValues(), set.d);

          } else {

            // System.out.println("queue is empty");
            try {
              this.free = true;
              if (flag >= this.sleepTime.length - 1) {

                flushTable();

                // System.out.println(this.getId()
                // + ":there is no jobs");
                sleep(this.sleepTime[flag]);
              } else {
                // flushTable();
                sleep(this.sleepTime[flag++]);
              }
            } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        } catch (Exception e) {
          continue;
        }
      }
    }
Example #21
0
 @Override
 protected void flush() {
   if (changes.isEmpty()) return;
   ImmutableSet.Builder<ScoreboardChange> changesBuilder = ImmutableSet.builder();
   ScoreboardChange pending;
   while ((pending = this.changes.poll()) != null) {
     changesBuilder.add(pending);
   }
   ImmutableSet<ScoreboardChange> changes = changesBuilder.build();
   for (ScoreboardChange change : changes) {
     change.execute(buffer);
   }
   swapBuffer();
   for (ScoreboardChange change : changes) {
     change.execute(buffer);
   }
 }
  /**
   * https://issues.apache.org/jira/browse/WICKET-5316
   *
   * @throws Exception
   */
  @Test
  public void failToReleaseUnderLoad() throws Exception {
    final Duration duration = Duration.seconds(20); /* seconds */
    final ConcurrentLinkedQueue<Exception> errors = new ConcurrentLinkedQueue<Exception>();
    final long endTime = System.currentTimeMillis() + duration.getMilliseconds();

    // set the synchronizer timeout one second longer than the test runs to prevent
    // starvation to become an issue
    final PageAccessSynchronizer sync =
        new PageAccessSynchronizer(duration.add(Duration.ONE_SECOND));

    final CountDownLatch latch = new CountDownLatch(100);
    for (int count = 0; count < 100; count++) {
      new Thread() {
        @Override
        public void run() {
          try {
            while (System.currentTimeMillis() < endTime) {
              try {
                logger.debug(Thread.currentThread().getName() + " locking");
                sync.lockPage(0);
                Thread.sleep(1);
                logger.debug(Thread.currentThread().getName() + " locked");
                sync.unlockAllPages();
                logger.debug(Thread.currentThread().getName() + " unlocked");
                Thread.sleep(5);
              } catch (InterruptedException e) {
                throw new RuntimeException(e);
              }
            }
          } catch (Exception e) {
            logger.error(e.getMessage(), e);
            errors.add(e);
          } finally {
            latch.countDown();
          }
        }
      }.start();
    }
    latch.await();
    if (!errors.isEmpty()) {
      logger.error("Number of lock errors that occurred: {}", errors.size());
      throw errors.remove();
    }
  }
  // Handle any requests that have been made against the client.
  private void handleInputQueue() {
    if (!addedQueue.isEmpty()) {
      getLogger().debug("Handling queue");
      // If there's stuff in the added queue.  Try to process it.
      Collection<MemcachedNode> toAdd = new HashSet<MemcachedNode>();
      // Transfer the queue into a hashset.  There are very likely more
      // additions than there are nodes.
      Collection<MemcachedNode> todo = new HashSet<MemcachedNode>();
      try {
        MemcachedNode qa = null;
        while ((qa = addedQueue.remove()) != null) {
          todo.add(qa);
        }
      } catch (NoSuchElementException e) {
        // Found everything
      }

      // Now process the queue.
      for (MemcachedNode qa : todo) {
        boolean readyForIO = false;
        if (qa.isActive()) {
          if (qa.getCurrentWriteOp() != null) {
            readyForIO = true;
            getLogger().debug("Handling queued write %s", qa);
          }
        } else {
          toAdd.add(qa);
        }
        qa.copyInputQueue();
        if (readyForIO) {
          try {
            if (qa.getWbuf().hasRemaining()) {
              handleWrites(qa.getSk(), qa);
            }
          } catch (IOException e) {
            getLogger().warn("Exception handling write", e);
            queueReconnect(qa);
          }
        }
        qa.fixupOps();
      }
      addedQueue.addAll(toAdd);
    }
  }
Example #24
0
 void flushOneOrMoreLedgers(boolean doAll) throws IOException {
   if (ledgersToFlush.isEmpty()) {
     ledgersToFlush.addAll(pageMapAndList.getActiveLedgers());
   }
   Long potentiallyDirtyLedger;
   while (null != (potentiallyDirtyLedger = ledgersToFlush.poll())) {
     if (!ledgersFlushing.add(potentiallyDirtyLedger)) {
       continue;
     }
     try {
       flushSpecificLedger(potentiallyDirtyLedger);
     } finally {
       ledgersFlushing.remove(potentiallyDirtyLedger);
     }
     if (!doAll) {
       break;
     }
   }
 }
  public void run() {
    HawtDispatchQueue original = HawtDispatcher.CURRENT_QUEUE.get();
    HawtDispatcher.CURRENT_QUEUE.set(this);
    executing.set(Boolean.TRUE);
    try {
      Runnable runnable;
      while ((runnable = externalQueue.poll()) != null) {
        localQueue.add(runnable);
      }
      while (true) {
        if (isSuspended()) {
          return;
        }
        runnable = localQueue.poll();
        if (runnable == null) {
          return;
        }
        try {
          runnable.run();
        } catch (Throwable e) {
          Thread thread = Thread.currentThread();
          thread.getUncaughtExceptionHandler().uncaughtException(thread, e);
        }
      }
    } finally {

      // Posts any deferred events.  This ensures
      // the next events generated by this dispatch
      // queue are received in order.
      for (Runnable runnable : sourceQueue) {
        runnable.run();
      }
      sourceQueue.clear();

      executing.remove();
      HawtDispatcher.CURRENT_QUEUE.set(original);
      triggered.set(false);
      boolean empty = externalQueue.isEmpty() && localQueue.isEmpty();
      if (!isSuspended() && !empty) {
        triggerExecution();
      }
    }
  }
  @Override
  public boolean registerListener(NotificationListener listener) throws IOException {
    checkNotNull(listener);

    checkError();

    synchronized (lock) {
      if (isReleased || !returnedBuffers.isEmpty()) {
        return false;
      }

      if (registeredListener == null) {
        registeredListener = listener;

        return true;
      }
    }

    throw new IllegalStateException("Already registered listener.");
  }
Example #27
0
  public void run() {
    while (!this.stoped) {
      try {
        synchronized (enQueSignal) {
          while (mq.isEmpty() == true && stoped == false) {
            try {
              enQueSignal.wait(1);
            } catch (InterruptedException e) {

            }
            // System.out.println("sender wake up");
          }
          processMessage();
        }
      } catch (Exception e) {
        e.printStackTrace();
      } catch (Throwable t) {
        t.printStackTrace();
      }
    }
  }
Example #28
0
  void notifyAttributeUpdated(final String attributeEvent, final Bundle extras) {
    // Update the bundle classloader
    if (extras != null) extras.setClassLoader(contextClassLoader);

    if (AttributeEvent.STATE_UPDATED.equals(attributeEvent)) {
      getAttributeAsync(
          AttributeType.STATE,
          new OnAttributeRetrievedCallback<State>() {
            @Override
            public void onRetrievalSucceed(State state) {
              if (state.isFlying()) resetFlightTimer();
              else stopTimer();
            }

            @Override
            public void onRetrievalFailed() {
              stopTimer();
            }
          });
    } else if (AttributeEvent.SPEED_UPDATED.equals(attributeEvent)) {
      checkForGroundCollision();
    }

    if (droneListeners.isEmpty()) return;

    handler.post(
        new Runnable() {
          @Override
          public void run() {
            for (DroneListener listener : droneListeners) {
              try {
                listener.onDroneEvent(attributeEvent, extras);
              } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
              }
            }
          }
        });
  }
  // Apply common parent filter
  private boolean isReliable(
      ConcurrentLinkedQueue<Node> originallist, ConcurrentHashMap<Node, int[]> intermap) {

    ConcurrentLinkedQueue<Node> lowest = new ConcurrentLinkedQueue<Node>();
    for (Node entry : originallist) {

      boolean toAdd = true;
      if (isSignificant(intermap.get(entry), this._STATMIN)) {
        for (Node node : lowest) {
          // For each node already in the list,
          if (isChild(entry, node)) {
            // if entry is child of an existing node, remove the
            // node
            lowest.remove(node);
          } else if (isChild(node, entry)) {
            // if entry is parent of an existing node, dont add the
            // entry
            toAdd = false;
            break;
          }
        }
        if (toAdd) lowest.add(entry);
      }
    }

    if (lowest.isEmpty()) return false;

    // Then for each lowest entry, if one is not reliable, return false
    for (Node node : lowest) {
      if (getReliabilityScore(intermap.get(node), this._STATMIN) < 0.9) {
        return false;
      }
    }

    return true;
  }
 public boolean workPending() {
   synchronized (messageQueue) {
     return messageQueue.isEmpty() && !working;
   }
 }