コード例 #1
0
ファイル: ChannelGroup.java プロジェクト: applyhhj/iotcloud2
  public void removeChannel(Channel channel) {
    lock.lock();
    try {
      if (channel.getDirection() == Direction.OUT) {
        BrokerHost registeredHost = null;
        for (Map.Entry<BrokerHost, List<Channel>> e : brokerHostToProducerChannelMap.entrySet()) {
          List<Channel> channels = e.getValue();
          Iterator<Channel> channelIterator = channels.iterator();
          while (channelIterator.hasNext()) {
            Channel c = channelIterator.next();
            if (c.equals(channel)) {
              registeredHost = e.getKey();
              channelIterator.remove();

              // if there are no more channels remove the producer
              if (channels.size() == 0) {
                Manageable producer = producers.remove(registeredHost);
                producer.stop();
              }
              break;
            }
          }
          if (registeredHost != null) {
            break;
          }
        }
      } else if (channel.getDirection() == Direction.IN) {
        BrokerHost registeredHost = null;
        for (Map.Entry<BrokerHost, List<Channel>> e : brokerHostToConsumerChannelMap.entrySet()) {
          List<Channel> channels = e.getValue();
          Iterator<Channel> channelIterator = channels.iterator();
          while (channelIterator.hasNext()) {
            Channel c = channelIterator.next();
            if (c.equals(channel)) {
              registeredHost = e.getKey();
              channelIterator.remove();

              // if there are no more channels remove the producer
              if (channels.size() == 0) {
                ConsumingWorker worker = consumingWorkers.remove(registeredHost);
                worker.stop();

                Manageable consumer = consumers.remove(registeredHost);
                consumer.stop();
              }
              break;
            }
          }
          if (registeredHost != null) {
            break;
          }
        }
      }
    } finally {
      lock.unlock();
    }
  }
 @Test
 public void removeFromMap() {
   HazelcastClient hClient = getHazelcastClient();
   Map map = hClient.getMap("removeFromMap");
   assertNull(map.put("a", "b"));
   assertEquals("b", map.get("a"));
   assertEquals("b", map.remove("a"));
   assertNull(map.remove("a"));
   assertNull(map.get("a"));
 }
コード例 #3
0
 private void handleFail(Object id) {
   Tuple failed = _inputs.remove(id);
   if (failed == null) {
     throw new RuntimeException("Failed a non-existent or already acked/failed id: " + id);
   }
   _collector.fail(failed);
 }
コード例 #4
0
 @Override
 public void unregisterService(final URI serviceUri) throws IOException {
   registered.remove(serviceUri.toString());
   for (final DiscoveryAgent agent : agents) {
     agent.unregisterService(serviceUri);
   }
 }
コード例 #5
0
 @Override
 public void serviceRemoved(final URI service) {
   services.remove(service.toString());
   for (final DiscoveryListener discoveryListener : getListeners()) {
     executor.execute(new ServiceRemovedTask(discoveryListener, service));
   }
 }
コード例 #6
0
ファイル: RpcContext.java プロジェクト: rx78zlm/dubbo
 /**
  * set value.
  *
  * @param key
  * @param value
  * @return context
  */
 public RpcContext set(String key, Object value) {
   if (value == null) {
     values.remove(key);
   } else {
     values.put(key, value);
   }
   return this;
 }
コード例 #7
0
 void completed(InetAddress remote, String cfname) {
   logger.debug("Repair completed for {} on {}", remote, cfname);
   RepairJob job = activeJobs.get(cfname);
   if (job.completedSynchronizationJob(remote)) {
     activeJobs.remove(cfname);
     if (activeJobs.isEmpty()) completed.signalAll();
   }
 }
コード例 #8
0
ファイル: RpcContext.java プロジェクト: rx78zlm/dubbo
 /**
  * set attachment.
  *
  * @param key
  * @param value
  * @return context
  */
 public RpcContext setAttachment(String key, String value) {
   if (value == null) {
     attachments.remove(key);
   } else {
     attachments.put(key, value);
   }
   return this;
 }
コード例 #9
0
ファイル: Gossiper.java プロジェクト: Jashinta/570
  /** Removes the endpoint from Gossip but retains endpoint state */
  public void removeEndpoint(InetAddress endpoint) {
    // do subscribers first so anything in the subscriber that depends on gossiper state won't get
    // confused
    for (IEndpointStateChangeSubscriber subscriber : subscribers_) subscriber.onRemove(endpoint);

    liveEndpoints_.remove(endpoint);
    unreachableEndpoints_.remove(endpoint);
    // do not remove endpointState until aVeryLongTime
    FailureDetector.instance.remove(endpoint);
    justRemovedEndpoints_.put(endpoint, System.currentTimeMillis());
  }
コード例 #10
0
  static void removeFromLayers(Shape shape) {
    if (!layerOf.containsKey(shape)) return;

    int oldLayer = layerOf.get(shape);
    layerContents.get(oldLayer).remove(shape);
    if (layerContents.get(oldLayer).isEmpty()) {
      layerContents.remove(oldLayer);
      layers.remove((Integer) oldLayer);
    }
    layerOf.remove(shape);
  }
コード例 #11
0
ファイル: CanvasItemImpl.java プロジェクト: umaxfun/loadui
  @Override
  public void setLimit(@Nonnull String counterName, long counterValue) {
    if (counterValue > 0) limits.put(counterName, counterValue);
    else limits.remove(counterName);

    StringBuilder s = new StringBuilder();
    for (Entry<String, Long> e : limits.entrySet())
      s.append(e.getKey()).append('=').append(e.getValue().toString()).append(';');
    setAttribute(LIMITS_ATTRIBUTE, s.toString());

    if (TIMER_COUNTER.equals(counterName)) fixTimeLimit();
    fireBaseEvent(LIMITS);
  }
コード例 #12
0
ファイル: Executing.java プロジェクト: rhusar/JGroups
 protected void handleTaskRejectedResponse(Address source, long requestId) {
   Runnable runnable = _awaitingReturn.remove(new Owner(source, requestId));
   if (runnable != null) {
     _awaitingConsumer.add(runnable);
     Long taskRequestId = _requestId.get(runnable);
     if (taskRequestId != requestId) {
       log.warn("Task Request Id doesn't match in rejection");
     }
     sendToCoordinator(RUN_REQUEST, taskRequestId, local_addr);
   } else {
     log.error(Util.getMessage("ErrorResubmittingTaskForRequestId") + requestId);
   }
 }
コード例 #13
0
ファイル: Gossiper.java プロジェクト: Jashinta/570
  void doStatusCheck() {
    long now = System.currentTimeMillis();

    Set<InetAddress> eps = endpointStateMap_.keySet();
    for (InetAddress endpoint : eps) {
      if (endpoint.equals(localEndpoint_)) continue;

      FailureDetector.instance.interpret(endpoint);
      EndpointState epState = endpointStateMap_.get(endpoint);
      if (epState != null) {
        long duration = now - epState.getUpdateTimestamp();

        if (StorageService.instance.getTokenMetadata().isMember(endpoint))
          epState.setHasToken(true);
        // check if this is a fat client. fat clients are removed automatically from
        // gosip after FatClientTimeout
        if (!epState.getHasToken()
            && !epState.isAlive()
            && !justRemovedEndpoints_.containsKey(endpoint)
            && (duration > FatClientTimeout_)) {
          logger_.info(
              "FatClient "
                  + endpoint
                  + " has been silent for "
                  + FatClientTimeout_
                  + "ms, removing from gossip");
          removeEndpoint(
              endpoint); // will put it in justRemovedEndpoints to respect quarantine delay
          evictFromMembership(endpoint); // can get rid of the state immediately
        }

        if (!epState.isAlive() && (duration > aVeryLongTime_)) {
          evictFromMembership(endpoint);
        }
      }
    }

    if (!justRemovedEndpoints_.isEmpty()) {
      Map<InetAddress, Long> copy = new HashMap<InetAddress, Long>(justRemovedEndpoints_);
      for (Map.Entry<InetAddress, Long> entry : copy.entrySet()) {
        if ((now - entry.getValue()) > QUARANTINE_DELAY) {
          if (logger_.isDebugEnabled())
            logger_.debug(
                QUARANTINE_DELAY + " elapsed, " + entry.getKey() + " gossip quarantine over");
          justRemovedEndpoints_.remove(entry.getKey());
        }
      }
    }
  }
コード例 #14
0
ファイル: Executing.java プロジェクト: rhusar/JGroups
  protected void handleTaskSubmittedRequest(
      Runnable runnable, Address source, long requestId, long threadId) {
    // We store in our map so that when that task is
    // finished so that we can send back to the owner
    // with the results
    _running.put(runnable, new Owner(source, requestId));
    // We give the task to the thread that is now waiting for it to be returned
    // If we can't offer then we have to respond back to
    // caller that we can't handle it.  They must have
    // gotten our address when we had a consumer, but
    // they went away between then and now.
    boolean received;
    try {
      _tasks.put(threadId, runnable);

      CyclicBarrier barrier = _taskBarriers.remove(threadId);
      if (received = (barrier != null)) {
        // Only wait 10 milliseconds, in case if the consumer was
        // stopped between when we were told it was available and now
        barrier.await(10, TimeUnit.MILLISECONDS);
      }
    } catch (InterruptedException e) {
      if (log.isDebugEnabled()) log.debug("Interrupted while handing off task");
      Thread.currentThread().interrupt();
      received = false;
    } catch (BrokenBarrierException e) {
      if (log.isDebugEnabled())
        log.debug(
            "Consumer " + threadId + " has been interrupted, " + "must retry to submit elsewhere");
      received = false;
    } catch (TimeoutException e) {
      if (log.isDebugEnabled())
        log.debug("Timeout waiting to hand off to barrier, consumer " + threadId + " must be slow");
      // This should only happen if the consumer put the latch then got
      // interrupted but hadn't yet removed the latch, should almost never
      // happen
      received = false;
    }

    if (!received) {
      // Clean up the tasks request
      _tasks.remove(threadId);
      if (log.isDebugEnabled()) log.debug("Run rejected not able to pass off to consumer");
      // If we couldn't hand off the task we have to tell the client
      // and also reupdate the coordinator that our consumer is ready
      sendRequest(source, Type.RUN_REJECTED, requestId, null);
      _running.remove(runnable);
    }
  }
コード例 #15
0
ファイル: Gossiper.java プロジェクト: Jashinta/570
 void isAlive(InetAddress addr, EndpointState epState, boolean value) {
   epState.isAlive(value);
   if (value) {
     liveEndpoints_.add(addr);
     unreachableEndpoints_.remove(addr);
     for (IEndpointStateChangeSubscriber subscriber : subscribers_)
       subscriber.onAlive(addr, epState);
   } else {
     liveEndpoints_.remove(addr);
     unreachableEndpoints_.put(addr, System.currentTimeMillis());
     for (IEndpointStateChangeSubscriber subscriber : subscribers_)
       subscriber.onDead(addr, epState);
   }
   if (epState.isAGossiper()) return;
   epState.isAGossiper(true);
 }
コード例 #16
0
 /**
  * Retrieves the response from the queue matching the given key, blocking until it is received.
  *
  * @param k Response
  * @return Response
  * @throws InterruptedException if interrupted while waiting
  */
 public synchronized V take(K k) throws InterruptedException {
   final V v = taken.remove(k);
   if (v != null) {
     return v;
   }
   // Take the laundry out of the machine. If it's ours, leave with it.
   // If it's someone else's, fold it neatly and put it on the pile.
   for (; ; ) {
     final Pair<K, V> pair = queue.take();
     if (pair.left.equals(k)) {
       return pair.right;
     } else {
       taken.put(pair.left, pair.right);
     }
   }
 }
コード例 #17
0
ファイル: Executing.java プロジェクト: rhusar/JGroups
  protected void handleValueResponse(Address source, long requestId, Object value) {
    Runnable runnable = _awaitingReturn.remove(new Owner(source, requestId));

    if (runnable != null) {
      _requestId.remove(runnable);
    }
    // We can only notify of success if it was a future
    if (runnable instanceof RunnableFuture<?>) {
      RunnableFuture<?> future = (RunnableFuture<?>) runnable;
      ExecutorNotification notifier = notifiers.remove(future);
      if (notifier != null) {
        notifier.resultReturned(value);
      }
    } else {
      log.warn("Runnable was not found in awaiting");
    }
  }
コード例 #18
0
 /**
  * Remove the segment's data from the data container and cache store because we no longer own it.
  *
  * @param removedSegments to be cancelled and discarded
  */
 private void cancelTransfers(Set<Integer> removedSegments) {
   synchronized (this) {
     List<Integer> segmentsToCancel = new ArrayList<Integer>(removedSegments);
     while (!segmentsToCancel.isEmpty()) {
       int segmentId = segmentsToCancel.remove(0);
       InboundTransferTask inboundTransfer = transfersBySegment.remove(segmentId);
       if (inboundTransfer != null) { // we need to check the transfer was not already completed
         Set<Integer> cancelledSegments = new HashSet<Integer>(removedSegments);
         cancelledSegments.retainAll(inboundTransfer.getSegments());
         segmentsToCancel.removeAll(cancelledSegments);
         inboundTransfer.cancelSegments(
             cancelledSegments); // this will also remove it from transfersBySource if the entire
                                 // task gets cancelled
       }
     }
   }
 }
コード例 #19
0
  /**
   * Remove a record telling what entity caps node a user has.
   *
   * @param user the user (Full JID)
   */
  public void removeUserCapsNode(String user) {
    Caps caps = userCaps.remove(user);

    // Fire userCapsNodeRemoved.
    if (caps != null) {
      UserCapsNodeListener[] listeners;

      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeRemoved(user, nodeVer, false);
      }
    }
  }
コード例 #20
0
ファイル: Executing.java プロジェクト: zhujinfei5151/JGroups
  protected void handleExceptionResponse(Address source, long requestId, Throwable throwable) {
    Runnable runnable = _awaitingReturn.remove(new Owner(source, requestId));

    if (runnable != null) {
      _requestId.remove(runnable);
    }
    // We can only notify of exception if it was a future
    if (runnable instanceof RunnableFuture<?>) {
      RunnableFuture<?> future = (RunnableFuture<?>) runnable;
      ExecutorNotification notifier = notifiers.remove(future);
      if (notifier != null) {
        notifier.throwableEncountered(throwable);
      }
    } else {
      // All we can do is log the error since their is no
      // way to return this to the user since they don't
      // have a future object.
      log.error("Runtime Error encountered from cluster execute(Runnable) method", throwable);
    }
  }
コード例 #21
0
ファイル: ProcessStoreImpl.java プロジェクト: rrialq/ode
  public Collection<QName> undeploy(final String duName) {
    try {
      exec(
          new Callable<Collection<QName>>() {
            public Collection<QName> call(ConfStoreConnection conn) {
              DeploymentUnitDAO dudao = conn.getDeploymentUnit(duName);
              if (dudao != null) dudao.delete();
              return null;
            }
          });
    } catch (Exception ex) {
      __log.error(
          "Error synchronizing with data store; " + duName + " may be reappear after restart!");
    }

    Collection<QName> undeployed = Collections.emptyList();
    DeploymentUnitDir du;
    _rw.writeLock().lock();
    try {
      du = _deploymentUnits.remove(duName);
      if (du != null) {
        undeployed = toPids(du.getProcessNames(), du.getVersion());
      }

      for (QName pn : undeployed) {
        fireEvent(new ProcessStoreEvent(ProcessStoreEvent.Type.UNDEPLOYED, pn, du.getName()));
        __log.info(__msgs.msgProcessUndeployed(pn));
      }

      _processes.keySet().removeAll(undeployed);
    } finally {
      _rw.writeLock().unlock();
    }

    return undeployed;
  }
コード例 #22
0
    void completed(Differencer differencer) {
      logger.debug(
          String.format(
              "[repair #%s] Repair completed between %s and %s on %s",
              getName(), differencer.r1.endpoint, differencer.r2.endpoint, differencer.cfname));
      RepairJob job = activeJobs.get(differencer.cfname);
      if (job == null) {
        assert terminated;
        return;
      }

      if (job.completedSynchronization(differencer)) {
        activeJobs.remove(differencer.cfname);
        String remaining =
            activeJobs.size() == 0
                ? ""
                : String.format(
                    " (%d remaining column family to sync for this session)", activeJobs.size());
        logger.info(
            String.format(
                "[repair #%s] %s is fully synced%s", getName(), differencer.cfname, remaining));
        if (activeJobs.isEmpty()) completed.signalAll();
      }
    }
コード例 #23
0
ファイル: RpcContext.java プロジェクト: rx78zlm/dubbo
 /**
  * remove attachment.
  *
  * @param key
  * @return context
  */
 public RpcContext removeAttachment(String key) {
   attachments.remove(key);
   return this;
 }
コード例 #24
0
 @ManagedOperation
 public void logAllMessages(boolean b) {
   log.info("logAllMessagesForUsers[" + config.getUsername() + "] = " + b);
   if (b) logAllMessagesForUsers.put(config.getUsername(), false);
   else logAllMessagesForUsers.remove(config.getUsername());
 }
コード例 #25
0
ファイル: RpcContext.java プロジェクト: rx78zlm/dubbo
 /**
  * remove value.
  *
  * @param key
  * @return value
  */
 public RpcContext remove(String key) {
   values.remove(key);
   return this;
 }
コード例 #26
0
ファイル: DocBuilder.java プロジェクト: ashishlal/echidna_2.0
  @SuppressWarnings("unchecked")
  public void execute() {
    dataImporter.store(DataImporter.STATUS_MSGS, statusMessages);
    document = dataImporter.getConfig().document;
    final AtomicLong startTime = new AtomicLong(System.currentTimeMillis());
    statusMessages.put(
        TIME_ELAPSED,
        new Object() {
          public String toString() {
            return getTimeElapsedSince(startTime.get());
          }
        });

    statusMessages.put(DataImporter.MSG.TOTAL_QUERIES_EXECUTED, importStatistics.queryCount);
    statusMessages.put(DataImporter.MSG.TOTAL_ROWS_EXECUTED, importStatistics.rowsCount);
    statusMessages.put(DataImporter.MSG.TOTAL_DOC_PROCESSED, importStatistics.docCount);
    statusMessages.put(DataImporter.MSG.TOTAL_DOCS_SKIPPED, importStatistics.skipDocCount);

    List<String> entities = requestParameters.entities;

    // Trigger onImportStart
    if (document.onImportStart != null) {
      invokeEventListener(document.onImportStart);
    }
    AtomicBoolean fullCleanDone = new AtomicBoolean(false);
    // we must not do a delete of *:* multiple times if there are multiple root entities to be run
    Properties lastIndexTimeProps = new Properties();
    lastIndexTimeProps.setProperty(
        LAST_INDEX_KEY,
        DataImporter.DATE_TIME_FORMAT.get().format(dataImporter.getIndexStartTime()));
    for (DataConfig.Entity e : document.entities) {
      if (entities != null && !entities.contains(e.name)) continue;
      lastIndexTimeProps.setProperty(
          e.name + "." + LAST_INDEX_KEY, DataImporter.DATE_TIME_FORMAT.get().format(new Date()));
      root = e;
      String delQuery = e.allAttributes.get("preImportDeleteQuery");
      if (dataImporter.getStatus() == DataImporter.Status.RUNNING_DELTA_DUMP) {
        cleanByQuery(delQuery, fullCleanDone);
        doDelta();
        delQuery = e.allAttributes.get("postImportDeleteQuery");
        if (delQuery != null) {
          fullCleanDone.set(false);
          cleanByQuery(delQuery, fullCleanDone);
        }
      } else {
        cleanByQuery(delQuery, fullCleanDone);
        doFullDump();
        delQuery = e.allAttributes.get("postImportDeleteQuery");
        if (delQuery != null) {
          fullCleanDone.set(false);
          cleanByQuery(delQuery, fullCleanDone);
        }
      }
      statusMessages.remove(DataImporter.MSG.TOTAL_DOC_PROCESSED);
    }

    if (stop.get()) {
      // Dont commit if aborted using command=abort
      statusMessages.put("Aborted", DataImporter.DATE_TIME_FORMAT.get().format(new Date()));
      rollback();
    } else {
      // Do not commit unnecessarily if this is a delta-import and no documents were created or
      // deleted
      if (!requestParameters.clean) {
        if (importStatistics.docCount.get() > 0 || importStatistics.deletedDocCount.get() > 0) {
          finish(lastIndexTimeProps);
        }
      } else {
        // Finished operation normally, commit now
        finish(lastIndexTimeProps);
      }

      if (writer != null) {
        writer.finish();
      }

      if (document.onImportEnd != null) {
        invokeEventListener(document.onImportEnd);
      }
    }

    statusMessages.remove(TIME_ELAPSED);
    statusMessages.put(DataImporter.MSG.TOTAL_DOC_PROCESSED, "" + importStatistics.docCount.get());
    if (importStatistics.failedDocCount.get() > 0)
      statusMessages.put(
          DataImporter.MSG.TOTAL_FAILED_DOCS, "" + importStatistics.failedDocCount.get());

    statusMessages.put("Time taken ", getTimeElapsedSince(startTime.get()));
    LOG.info("Time taken = " + getTimeElapsedSince(startTime.get()));
  }
コード例 #27
0
ファイル: Executing.java プロジェクト: rhusar/JGroups
  public Object down(Event evt) {
    switch (evt.getType()) {
      case ExecutorEvent.TASK_SUBMIT:
        Runnable runnable = evt.getArg();
        // We are limited to a number of concurrent request id's
        // equal to 2^63-1.  This is quite large and if it
        // overflows it will still be positive
        long requestId = Math.abs(counter.getAndIncrement());
        if (requestId == Long.MIN_VALUE) {
          // TODO: need to fix this it isn't safe for concurrent modifications
          counter.set(0);
          requestId = Math.abs(counter.getAndIncrement());
        }

        // Need to make sure to put the requestId in our map before
        // adding the runnable to awaiting consumer in case if
        // coordinator sent a consumer found and their original task
        // is no longer around
        // see https://issues.jboss.org/browse/JGRP-1744
        _requestId.put(runnable, requestId);

        _awaitingConsumer.add(runnable);

        sendToCoordinator(RUN_REQUEST, requestId, local_addr);
        break;
      case ExecutorEvent.CONSUMER_READY:
        Thread currentThread = Thread.currentThread();
        long threadId = currentThread.getId();
        _consumerId.put(threadId, PRESENT);
        try {
          for (; ; ) {
            CyclicBarrier barrier = new CyclicBarrier(2);
            _taskBarriers.put(threadId, barrier);

            // We only send to the coordinator that we are ready after
            // making the barrier, wait for request to come and let
            // us free
            sendToCoordinator(Type.CONSUMER_READY, threadId, local_addr);

            try {
              barrier.await();
              break;
            } catch (BrokenBarrierException e) {
              if (log.isDebugEnabled())
                log.debug(
                    "Producer timed out before we picked up"
                        + " the task, have to tell coordinator"
                        + " we are still good.");
            }
          }
          // This should always be non nullable since the latch
          // was freed
          runnable = _tasks.remove(threadId);
          _runnableThreads.put(runnable, currentThread);
          return runnable;
        } catch (InterruptedException e) {
          if (log.isDebugEnabled()) log.debug("Consumer " + threadId + " stopped via interrupt");
          sendToCoordinator(Type.CONSUMER_UNREADY, threadId, local_addr);
          Thread.currentThread().interrupt();
        } finally {
          // Make sure the barriers are cleaned up as well
          _taskBarriers.remove(threadId);
          _consumerId.remove(threadId);
        }
        break;
      case ExecutorEvent.TASK_COMPLETE:
        Object arg = evt.getArg();
        Throwable throwable = null;
        if (arg instanceof Object[]) {
          Object[] array = (Object[]) arg;
          runnable = (Runnable) array[0];
          throwable = (Throwable) array[1];
        } else {
          runnable = (Runnable) arg;
        }
        Owner owner = _running.remove(runnable);
        // This won't remove anything if owner doesn't come back
        _runnableThreads.remove(runnable);

        Object value = null;
        boolean exception = false;
        if (throwable != null) {
          // InterruptedException is special telling us that
          // we interrupted the thread while waiting but still got
          // a task therefore we have to reject it.
          if (throwable instanceof InterruptedException) {
            if (log.isDebugEnabled())
              log.debug("Run rejected due to interrupted exception returned");
            sendRequest(owner.address, Type.RUN_REJECTED, owner.requestId, null);
            break;
          }
          value = throwable;
          exception = true;
        } else if (runnable instanceof RunnableFuture<?>) {
          RunnableFuture<?> future = (RunnableFuture<?>) runnable;

          boolean interrupted = false;
          boolean gotValue = false;

          // We have the value, before we interrupt at least get it!
          while (!gotValue) {
            try {
              value = future.get();
              gotValue = true;
            } catch (InterruptedException e) {
              interrupted = true;
            } catch (ExecutionException e) {
              value = e.getCause();
              exception = true;
              gotValue = true;
            }
          }

          if (interrupted) {
            Thread.currentThread().interrupt();
          }
        }

        if (owner != null) {
          final Type type;
          final Object valueToSend;
          if (value == null) {
            type = Type.RESULT_SUCCESS;
            valueToSend = value;
          }
          // Both serializable values and exceptions would go in here
          else if (value instanceof Serializable
              || value instanceof Externalizable
              || value instanceof Streamable) {
            type = exception ? Type.RESULT_EXCEPTION : Type.RESULT_SUCCESS;
            valueToSend = value;
          }
          // This would happen if the value wasn't serializable,
          // so we have to send back to the client that the class
          // wasn't serializable
          else {
            type = Type.RESULT_EXCEPTION;
            valueToSend = new NotSerializableException(value.getClass().getName());
          }

          if (local_addr.equals(owner.getAddress())) {
            if (log.isTraceEnabled())
              log.trace(
                  "[redirect] <--> ["
                      + local_addr
                      + "] "
                      + type.name()
                      + " ["
                      + value
                      + (owner.requestId != -1 ? " request id: " + owner.requestId : "")
                      + "]");
            if (type == Type.RESULT_SUCCESS) {
              handleValueResponse(local_addr, owner.requestId, valueToSend);
            } else if (type == Type.RESULT_EXCEPTION) {
              handleExceptionResponse(local_addr, owner.requestId, (Throwable) valueToSend);
            }
          } else {
            sendRequest(owner.getAddress(), type, owner.requestId, valueToSend);
          }
        } else {
          if (log.isTraceEnabled()) {
            log.trace("Could not return result - most likely because it was interrupted");
          }
        }
        break;
      case ExecutorEvent.TASK_CANCEL:
        Object[] array = evt.getArg();
        runnable = (Runnable) array[0];

        if (_awaitingConsumer.remove(runnable)) {
          _requestId.remove(runnable);
          ExecutorNotification notification = notifiers.remove(runnable);
          if (notification != null) {
            notification.interrupted(runnable);
          }
          if (log.isTraceEnabled())
            log.trace("Cancelled task " + runnable + " before it was picked up");
          return Boolean.TRUE;
        }
        // This is guaranteed to not be null so don't take cost of auto unboxing
        else if (array[1] == Boolean.TRUE) {
          owner = removeKeyForValue(_awaitingReturn, runnable);
          if (owner != null) {
            Long requestIdValue = _requestId.remove(runnable);
            // We only cancel if the requestId is still available
            // this means the result hasn't been returned yet and
            // we still have a chance to interrupt
            if (requestIdValue != null) {
              if (requestIdValue != owner.getRequestId()) {
                log.warn("Cancelling requestId didn't match waiting");
              }
              sendRequest(owner.getAddress(), Type.INTERRUPT_RUN, owner.getRequestId(), null);
            }
          } else {
            if (log.isTraceEnabled()) log.warn("Couldn't interrupt server task: " + runnable);
          }
          ExecutorNotification notification = notifiers.remove(runnable);
          if (notification != null) {
            notification.interrupted(runnable);
          }
          return Boolean.TRUE;
        } else {
          return Boolean.FALSE;
        }
      case ExecutorEvent.ALL_TASK_CANCEL:
        array = evt.getArg();

        // This is a RunnableFuture<?> so this cast is okay
        @SuppressWarnings("unchecked")
        Set<Runnable> runnables = (Set<Runnable>) array[0];
        Boolean booleanValue = (Boolean) array[1];

        List<Runnable> notRan = new ArrayList<>();

        for (Runnable cancelRunnable : runnables) {
          // Removed from the consumer
          if (!_awaitingConsumer.remove(cancelRunnable) && booleanValue == Boolean.TRUE) {
            synchronized (_awaitingReturn) {
              owner = removeKeyForValue(_awaitingReturn, cancelRunnable);
              if (owner != null) {
                Long requestIdValue = _requestId.remove(cancelRunnable);
                if (requestIdValue != owner.getRequestId()) {
                  log.warn("Cancelling requestId didn't match waiting");
                }
                sendRequest(owner.getAddress(), Type.INTERRUPT_RUN, owner.getRequestId(), null);
              }
              ExecutorNotification notification = notifiers.remove(cancelRunnable);
              if (notification != null) {
                log.trace("Notifying listener");
                notification.interrupted(cancelRunnable);
              }
            }
          } else {
            _requestId.remove(cancelRunnable);
            notRan.add(cancelRunnable);
          }
        }
        return notRan;
      case Event.SET_LOCAL_ADDRESS:
        local_addr = evt.getArg();
        break;

      case Event.VIEW_CHANGE:
        handleView(evt.getArg());
        break;
    }
    return down_prot.down(evt);
  }
コード例 #28
0
 public synchronized void setVariable(String variable, String value) {
   if (value == null) variables.remove(value);
   else variables.put(variable, value);
 }
コード例 #29
0
  /**
   * Creates an SCAudioClip from the given URI and adds it to the list of available audio-s.
   *
   * @param uri the path where the audio file could be found
   * @param playback use or not the playback device.
   * @return a newly created <tt>SCAudioClip</tt> from <tt>uri</tt>
   */
  public SCAudioClip createAudio(String uri, boolean playback) {
    SCAudioClip audio;

    synchronized (audiosSyncRoot) {
      final AudioKey key = new AudioKey(uri, playback);

      /*
       * While we want to reuse the SCAudioClip instances, they may be
       * used by a single user at a time. That's why we'll forget about
       * them while they are in use and we'll reclaim them when they are
       * no longer in use.
       */
      audio = (audios == null) ? null : audios.remove(key);

      if (audio == null) {
        try {
          AudioSystem audioSystem = getDeviceConfiguration().getAudioSystem();

          if (audioSystem == null) {
            audio = new JavaSoundClipImpl(uri, this);
          } else if (NoneAudioSystem.LOCATOR_PROTOCOL.equalsIgnoreCase(
              audioSystem.getLocatorProtocol())) {
            audio = null;
          } else {
            audio = new AudioSystemClipImpl(uri, this, audioSystem, playback);
          }
        } catch (Throwable t) {
          if (t instanceof ThreadDeath) throw (ThreadDeath) t;
          else {
            /*
             * Could not initialize a new SCAudioClip instance to be
             * played.
             */
            return null;
          }
        }
      }

      /*
       * Make sure that the SCAudioClip will be reclaimed for reuse when
       * it is no longer in use.
       */
      if (audio != null) {
        if (audios == null) audios = new HashMap<AudioKey, SCAudioClip>();

        /*
         * We have to return in the Map which was active at the time the
         * SCAudioClip was initialized because it may have become
         * invalid if the playback or notify audio device changed.
         */
        final Map<AudioKey, SCAudioClip> finalAudios = audios;
        final SCAudioClip finalAudio = audio;

        audio =
            new SCAudioClip() {
              /**
               * Evaluates a specific <tt>loopCondition</tt> as defined by {@link
               * SCAudioClip#play(int,Callable)}.
               *
               * @param loopCondition the <tt>Callable&lt;Boolean&gt;</tt> which represents the
               *     <tt>loopCondition</tt> to be evaluated
               * @return {@link Boolean#FALSE} if <tt>loopCondition</tt> is <tt>null</tt>;
               *     otherwise, the value returned by invoking {@link Callable#call()} on the
               *     specified <tt>loopCondition</tt>
               * @throws Exception if the specified <tt>loopCondition</tt> throws an
               *     <tt>Exception</tt>
               */
              private Boolean evaluateLoopCondition(Callable<Boolean> loopCondition)
                  throws Exception {
                /*
                 * SCAudioClip.play(int,Callable<Boolean>) is
                 * documented to play the SCAudioClip once only if
                 * the loopCondition is null. The same will be
                 * accomplished by returning Boolean.FALSE.
                 */
                return (loopCondition == null) ? Boolean.FALSE : loopCondition.call();
              }

              /**
               * {@inheritDoc}
               *
               * <p>Returns the wrapped <tt>SCAudioClip</tt> into the cache from it has earlier been
               * retrieved in order to allow its reuse.
               */
              @Override
              protected void finalize() throws Throwable {
                try {
                  synchronized (audios) {
                    finalAudios.put(key, finalAudio);
                  }
                } finally {
                  super.finalize();
                }
              }

              public void play() {
                /*
                 * SCAudioClip.play() is documented to behave as if
                 * loopInterval is negative and/or loopCondition is
                 * null. We have to take care that this instance
                 * does not get garbage collected until the
                 * finalAudio finishes playing so we will delegate
                 * to this instance's implementation of
                 * SCAudioClip.play(int,Callable<Boolean>) instead
                 * of to the finalAudio's.
                 */
                play(-1, null);
              }

              public void play(int loopInterval, final Callable<Boolean> finalLoopCondition) {
                /*
                 * We have to make sure that this instance does not
                 * get garbage collected before the finalAudio
                 * finishes playing. The argument loopCondition of
                 * the method
                 * SCAudioClip.play(int,Callable<Boolean>) will
                 * live/be referenced during that time so we will
                 * use it to hold on to this instance.
                 */
                Callable<Boolean> loopCondition =
                    new Callable<Boolean>() {
                      public Boolean call() throws Exception {
                        return evaluateLoopCondition(finalLoopCondition);
                      }
                    };

                finalAudio.play(loopInterval, loopCondition);
              }

              public void stop() {
                finalAudio.stop();
              }

              /**
               * Determines whether this audio is started i.e. a <tt>play</tt> method was invoked
               * and no subsequent <tt>stop</tt> has been invoked yet.
               *
               * @return <tt>true</tt> if this audio is started; otherwise, <tt>false</tt>
               */
              public boolean isStarted() {
                return finalAudio.isStarted();
              }
            };
      }
    }

    return audio;
  }
コード例 #30
0
ファイル: Gossiper.java プロジェクト: Jashinta/570
 /**
  * Removes the endpoint from gossip completely
  *
  * @param endpoint endpoint to be removed from the current membership.
  */
 void evictFromMembership(InetAddress endpoint) {
   unreachableEndpoints_.remove(endpoint);
   endpointStateMap_.remove(endpoint);
 }