@Override public void update(int tick) { sortEntities(); @SuppressWarnings("unchecked") List<Entity> sorted = (List<Entity>) entities.clone(); Collections.reverse(sorted); for (Entity entity : sorted) { entity.update(tick); if (entity.isDead()) { if (entity.equals(selectedEntity)) selectedEntity = null; entities.remove(entity); } } for (Projectile p : projectiles) { p.update(tick); if (p.isDead()) projectiles.remove(p); } for (Animation a : animations) { a.update(tick); if (a.isDead()) animations.remove(a); } }
public void setClients(Collection<IMailClient> clients) { synchronized (_mutex) { _clients.clear(); _clients.addAll(clients); _iter = newIterator(); } }
/** * Removes the specified driver from the {@code DriverManager}'s list of registered drivers. * * <p>If a {@code null} value is specified for the driver to be removed, then no action is taken. * * <p>If a security manager exists and its {@code checkPermission} denies permission, then a * {@code SecurityException} will be thrown. * * <p>If the specified driver is not found in the list of registered drivers, then no action is * taken. If the driver was found, it will be removed from the list of registered drivers. * * <p>If a {@code DriverAction} instance was specified when the JDBC driver was registered, its * deregister method will be called prior to the driver being removed from the list of registered * drivers. * * @param driver the JDBC Driver to remove * @exception SQLException if a database access error occurs * @throws SecurityException if a security manager exists and its {@code checkPermission} method * denies permission to deregister a driver. * @see SecurityManager#checkPermission */ @CallerSensitive public static synchronized void deregisterDriver(Driver driver) throws SQLException { if (driver == null) { return; } SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(DEREGISTER_DRIVER_PERMISSION); } println("DriverManager.deregisterDriver: " + driver); DriverInfo aDriver = new DriverInfo(driver, null); if (registeredDrivers.contains(aDriver)) { if (isDriverAllowed(driver, Reflection.getCallerClass())) { DriverInfo di = registeredDrivers.get(registeredDrivers.indexOf(aDriver)); // If a DriverAction was specified, Call it to notify the // driver that it has been deregistered if (di.action() != null) { di.action().deregister(); } registeredDrivers.remove(aDriver); } else { // If the caller does not have permission to load the driver then // throw a SecurityException. throw new SecurityException(); } } else { println(" couldn't find driver to unload"); } }
/** * Einen Listener wieder austragen * * @param listen */ public void removeListener(HeartListener listen) { // remove the listener from the three lists // actually, it's contained in only one of them, but we don't know which one highFrequencyListeners.remove(listen); mediumFrequencyListeners.remove(listen); lowFrequencyListeners.remove(listen); }
/** * 第一步:通过subscriptionsByEventType得到该事件类型所有订阅者信息队列,根据优先级将当前订阅者信息插入到订阅者队列subscriptionsByEventType中; * 第二步:在typesBySubscriber中得到当前订阅者订阅的所有事件队列,将此事件保存到队列typesBySubscriber中,用于后续取消订阅; 第三步:检查这个事件是否是 * Sticky 事件,如果是则从stickyEvents事件保存队列中取出该事件类型最后一个事件发送给当前订阅者。 * * @param subscriber * @param subscriberMethod * @param sticky * @param priority */ private void subscribe( Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) { Class<?> eventType = subscriberMethod.eventType; CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); // 通过subscriptionsByEventType得到该事件类型所有订阅者信息队列 Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority); // 根据当前的eventType,在subscriptionsByEventType生成对应的key-value(没有则加入,有则跳过次处理) if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<Subscription>(); subscriptionsByEventType.put(eventType, subscriptions); } else { if (subscriptions.contains(newSubscription)) { throw new EventBusException( "Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } } // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations // again) // subscriberMethod.method.setAccessible(true); // 根据优先级将当前订阅者信息插入到订阅者队列subscriptionsByEventType中; int size = subscriptions.size(); for (int i = 0; i <= size; i++) { if (i == size || newSubscription.priority > subscriptions.get(i).priority) { subscriptions.add(i, newSubscription); break; } } // 在typesBySubscriber中得到当前订阅者订阅的所有事件队列,将此事件保存到队列typesBySubscriber中,用于后续取消订阅; List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<Class<?>>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); // 检查这个事件是否是 Sticky 事件,如果是,则从stickyEvents事件保存队列中取出该事件类型最后一个事件发送给当前订阅者。 if (sticky) { if (eventInheritance) { // Existing sticky events of all subclasses of eventType have to be considered. // Note: Iterating over all events may be inefficient with lots of sticky events, // thus data structure should be changed to allow a more efficient lookup // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>). Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet(); for (Map.Entry<Class<?>, Object> entry : entries) { Class<?> candidateEventType = entry.getKey(); if (eventType.isAssignableFrom( candidateEventType)) { // 是用来判断一个类Class1和另一个类Class2是否相同或是另一个类的超类或接口 Object stickyEvent = entry.getValue(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }
/** This method register a FermatTyrusPacketProcessor object with this server */ public void registerFermatPacketProcessor(FermatTyrusPacketProcessor fermatPacketProcessor) { // Validate if a previous list created if (packetProcessorsRegister.containsKey(fermatPacketProcessor.getFermatPacketType())) { /* * Add to the existing list */ packetProcessorsRegister .get(fermatPacketProcessor.getFermatPacketType()) .add(fermatPacketProcessor); } else { /* * Create a new list and add the fermatPacketProcessor */ CopyOnWriteArrayList<FermatTyrusPacketProcessor> fermatPacketProcessorList = new CopyOnWriteArrayList<>(); fermatPacketProcessorList.add(fermatPacketProcessor); /* * Add to the packetProcessorsRegister */ packetProcessorsRegister.put( fermatPacketProcessor.getFermatPacketType(), fermatPacketProcessorList); } }
/** Adds a random obstacle to the ArrayList of obstacles. */ public void addRandomObstacle() { if (new Random().nextBoolean()) { obstacles.add(new BadObstacle(paintGreen)); } else { obstacles.add(new GoodObstacle(paintBlue)); } }
/** * postSingleEventForEventType 函数在subscriptionsByEventType查找该事件订阅者订阅者队列,调用 postToSubscription * 函数向每个订阅者发布事件。 * * @param event * @param postingState * @param eventClass * @return */ private boolean postSingleEventForEventType( Object event, PostingThreadState postingState, Class<?> eventClass) { CopyOnWriteArrayList<Subscription> subscriptions; synchronized (this) { subscriptions = subscriptionsByEventType.get(eventClass); } if (subscriptions != null && !subscriptions.isEmpty()) { for (Subscription subscription : subscriptions) { postingState.event = event; postingState.subscription = subscription; boolean aborted = false; try { postToSubscription(subscription, event, postingState.isMainThread); aborted = postingState.canceled; } finally { postingState.event = null; postingState.subscription = null; postingState.canceled = false; } if (aborted) { break; } } return true; } return false; }
// private ArrayList<RegistryEntry> readFromRegister(String key, Session session) { private String readFromRegister(String key, Session session) { // TODO Auto-generated method stub // Map<String, String> resultMap = new HashMap<String, String>(); String CLID = null, STATUS = null; String cqlStr = "SELECT * from consistify.registry WHERE key='" + key + "'"; Statement statement = new SimpleStatement(cqlStr); ResultSet results = session.execute(statement); CopyOnWriteArrayList<RegistryEntry> rList = new CopyOnWriteArrayList<RegistryEntry>(); RegistryEntry r = null; Scheduler scheduler = new Scheduler(); for (Row aRow : results) { // if (!resultMap.containsKey(aRow.getKey())) { if (aRow.getString("CREATETIME") != null && aRow.getString("key").equalsIgnoreCase(key)) { r = new RegistryEntry(); r.setKey(aRow.getString("key")); // System.out.println("**222*CLID:=="+aRow.getString("CLID")); r.setCLID(aRow.getString("CLID")); r.setDEADLINE(aRow.getString("DEADLINE")); r.setINDEX(aRow.getString("INDIC")); r.setLATENCYDEP(aRow.getString("LATENCYDEP")); r.setWAITINGTIME(aRow.getString("WAITINGTIME")); r.setSTATUS(aRow.getString("STATUS")); r.setCREATETIME(aRow.getString("CREATETIME")); rList.add(r); } // resultMap.put(aRow.getKey(), ++rowCnt); // System.out.println(aRow.getKey() + ":" + rowCnt); // } } // CLID = scheduler.schedule(rList).split(":")[0]; CLID = scheduler.schedule(rList); // System.out.println("****CLID:="+CLID); return CLID; }
protected void advanceInitializers(IOFSwitchExt sw) { CopyOnWriteArrayList<IOFInitializerListener> initializers = initializerMap.get(sw); // Remove first initializer if it exists Iterator<IOFInitializerListener> it = initializers.iterator(); if (it.hasNext()) { IOFInitializerListener initializer = it.next(); initializers.remove(initializer); log.debug("Remaining initializers for switch {}: {}", sw, initializers); } if (it.hasNext()) { IOFInitializerListener initializer = it.next(); queueInitializer(sw, initializer); } else { /** * Must synchronize here to ensure we don't transition into active while simultaneously being * disconnected. */ synchronized (sw) { if (!OFSwitchState.DISCONNECTED.equals(sw.getState())) { sw.transitionToState(OFSwitchState.ACTIVE); // Add switch to active list addActiveSwitch(sw); } initializerMap.remove(sw); } } }
/** * Connect provider to this pipe. Doesn't allow to connect one provider twice. Does register event * listeners if instance of IPipeConnectionListener is given. * * @param provider Provider * @param paramMap Parameters passed with connection, used in concrete pipe implementations * @return <code>true</code> if provider was added, <code>false</code> otherwise */ public boolean subscribe(IProvider provider, Map<String, Object> paramMap) { // register event listener if given if (provider instanceof IPipeConnectionListener) { listeners.add((IPipeConnectionListener) provider); } return providers.addIfAbsent(provider); }
public ParseMessage(String msg) { FMValue = msg.substring(3, 5); // first one is starting index,last one is end+1 ToValue = msg.substring(9, 11); // NPVal = Character.getNumericValue(msg.charAt(15)); HCVal = Character.getNumericValue(msg.charAt(20)); msgNumber = Integer.parseInt(msg.substring(25, 28)); int i = msg.indexOf("DATA"); int j = msg.indexOf("VL"); if (i != (j + 4)) { VLNode = msg.substring(j + 3, i); } else VLNode = ""; DATA_Val = msg.substring(i + 5); if (NPVal == 2) { int k = msg.indexOf("registered as"); RegisteredName = "" + msg.charAt(k + 14) + msg.charAt(k + 15); } if (NPVal == 6) { String str = new String(DATA_Val); arr = new CopyOnWriteArrayList<>(); int m = 0; do { int k = str.indexOf(","); arr.add(new Node(str.substring(m, k))); str = str.substring(k + 1); } while (str.indexOf(",") != -1); arr.add(new Node(str)); } }
/** @param channelTopics the channelTopics to set */ public void setChannelTopics(List<String> channelTopics) { m_channelTopics.clear(); for (String topic : channelTopics) { m_channelTopics.add(topic); } }
/** * Disconnects consumer from this pipe. Fires pipe connection event. * * @param consumer Consumer that should be removed * @return <code>true</code> on success, <code>false</code> otherwise */ public boolean unsubscribe(IConsumer consumer) { if (consumers.remove(consumer)) { fireConsumerConnectionEvent(consumer, PipeConnectionEvent.CONSUMER_DISCONNECT, null); listeners.remove(consumer); return true; } else { return false; } }
public void finishVerification( ActionListener<VerifyResponse> listener, List<DiscoveryNode> nodes, CopyOnWriteArrayList<VerificationFailure> errors) { listener.onResponse( new RepositoriesService.VerifyResponse( nodes.toArray(new DiscoveryNode[nodes.size()]), errors.toArray(new VerificationFailure[errors.size()]))); }
/** * Disconnects provider from this pipe. Fires pipe connection event. * * @param provider Provider that should be removed * @return <code>true</code> on success, <code>false</code> otherwise */ public boolean unsubscribe(IProvider provider) { if (providers.remove(provider)) { fireProviderConnectionEvent(provider, PipeConnectionEvent.PROVIDER_DISCONNECT, null); listeners.remove(provider); return true; } else { return false; } }
/** * Connect consumer to this pipe. Doesn't allow to connect one consumer twice. Does register event * listeners if instance of IPipeConnectionListener is given. * * @param consumer Consumer * @param paramMap Parameters passed with connection, used in concrete pipe implementations * @return <code>true</code> if consumer was added, <code>false</code> otherwise */ public boolean subscribe(IConsumer consumer, Map<String, Object> paramMap) { // if consumer is listener object register it as listener if (consumer instanceof IPipeConnectionListener) { listeners.addIfAbsent((IPipeConnectionListener) consumer); } // pipe is possibly used by dozens of threads at once (like many subscribers for one server // stream) return consumers.addIfAbsent(consumer); }
static { // Create list of customers cList.add( new Customer.CustomerBuilder() .id() .firstName("George") .lastName("Washington") .email("*****@*****.**") .city("Mt Vernon") .state("VA") .birthday("1732-02-23") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("John") .lastName("Adams") .email("*****@*****.**") .city("Braintree") .state("MA") .birthday("1735-10-30") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("Thomas") .lastName("Jefferson") .email("*****@*****.**") .city("CharlottesVille") .state("VA") .birthday("1743-04-13") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("James") .lastName("Madison") .email("*****@*****.**") .city("Orange") .state("VA") .birthday("1751-03-16") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("James") .lastName("Monroe") .email("*****@*****.**") .city("New York") .state("NY") .birthday("1758-04-28") .build()); }
/** {@inheritDoc} */ public void setItem(int index) { if (index < 0 || index >= items.size()) { return; } stop(); currentItemIndex = index; IPlayItem item = items.get(currentItemIndex); play(item); }
/** Rest Api handlers. */ public static void createRESTHandler() { get( "/api/elevators", (req, res) -> { CopyOnWriteArrayList<ElevatorModel> models = new CopyOnWriteArrayList<ElevatorModel>(); for (Elevator e : ElevatorController.getInstance().getElevatorList()) { models.add(e.getElevatorModel()); } return models; }, new JsonTransformer()); get( "/api/floors", (req, res) -> { return Floor.getInstance(); }, new JsonTransformer()); get( "/api/requestElevator/:floor", (req, res) -> { String floor = req.params(":floor"); ElevatorControllerInterface.requestElevator(Integer.valueOf(floor)); return "Elevator request submitted"; }); post( "/api/addPeopleOnFloor", (req, res) -> { Map<String, String> keyValueMap = keyValues(req.body()); String floorNumber = keyValueMap.get("floorNumber"); String peopleCount = keyValueMap.get("peopleCount"); String destinationFloor = keyValueMap.get("destinationFloor"); if (floorNumber == null || peopleCount == null || destinationFloor == null) { return "Invalid request format, POST [url] body:floorNumber=1&peopleCount=10&destinationFloor=5"; } Floor.getInstance() .addPersonOnFloor( Integer.valueOf(floorNumber), Integer.valueOf(peopleCount), Integer.valueOf(destinationFloor)); return Floor.getInstance().getCountOfPeopleWaitingOnFloor(Integer.valueOf(floorNumber)); }, new JsonTransformer()); get( "/api/events", (req, res) -> { return ElevatorRecorder.getAll(); }, new JsonTransformer()); }
public void removeDialog(Dialog d) { for (int i = 0; i < dialogs.size(); i++) { DialogWrapper p = dialogs.get(i); if (p.getDialog().equals(d)) { p.release(); dialogs.remove(i); return; } } }
/** Move to the previous item updating the currentItemIndex. */ protected void moveToPrevious() { if (currentItemIndex >= items.size()) { currentItemIndex = items.size() - 1; } if (controller != null) { currentItemIndex = controller.previousItem(this, currentItemIndex); } else { currentItemIndex = defaultController.previousItem(this, currentItemIndex); } }
/** * Disassociates given {@link View}. If view is not associated, nothing happens. * * @param view View to be disassociated */ public void removeView(final View view) { for (int i = 0; i < mViewList.size(); i++) { final ViewWeakReference reference = mViewList.get(i); final View item = reference.get(); if (item == null || item == view) { // Always remove null references to reduce Set size mViewList.remove(reference); } } }
/** * Producer method for partition collection * * @return Returns collection of partitions using copy on write list */ @PartitionType(implementation = COPY_ON_WRITE_LIST) @Produces public Collection<Partition> createPartitionCollection() { final CopyOnWriteArrayList<Partition> collection = new CopyOnWriteArrayList<>(); for (int i = 0; i < DEFAULT_MAX_PART; i++) { final String partitionName = "Partition-" + i; collection.add(new CoWPartitionImpl(DEFAULT_MAX_SESSIONS_PER_PARTITION, partitionName)); } return collection; }
public static void scheduleNewTorchUpdate(int dimID, List<BlockVec3> torches) { CopyOnWriteArrayList<BlockVec3> updateList = TickHandlerServer.scheduledTorchUpdates.get(dimID); if (updateList == null) { updateList = new CopyOnWriteArrayList<BlockVec3>(); } updateList.addAll(torches); TickHandlerServer.scheduledTorchUpdates.put(dimID, updateList); }
public void verify( String repository, String verificationToken, final ActionListener<VerifyResponse> listener) { final DiscoveryNodes discoNodes = clusterService.state().nodes(); final DiscoveryNode localNode = discoNodes.localNode(); final ObjectContainer<DiscoveryNode> masterAndDataNodes = discoNodes.masterAndDataNodes().values(); final List<DiscoveryNode> nodes = newArrayList(); for (ObjectCursor<DiscoveryNode> cursor : masterAndDataNodes) { DiscoveryNode node = cursor.value; Version version = node.getVersion(); // Verification wasn't supported before v1.4.0 - no reason to send verification request to // these nodes if (version != null && version.onOrAfter(Version.V_1_4_0)) { nodes.add(node); } } final CopyOnWriteArrayList<VerificationFailure> errors = new CopyOnWriteArrayList<>(); final AtomicInteger counter = new AtomicInteger(nodes.size()); for (final DiscoveryNode node : nodes) { if (node.equals(localNode)) { try { doVerify(repository, verificationToken); } catch (Throwable t) { logger.warn("[{}] failed to verify repository", t, repository); errors.add(new VerificationFailure(node.id(), ExceptionsHelper.detailedMessage(t))); } if (counter.decrementAndGet() == 0) { finishVerification(listener, nodes, errors); } } else { transportService.sendRequest( node, ACTION_NAME, new VerifyNodeRepositoryRequest(repository, verificationToken), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty response) { if (counter.decrementAndGet() == 0) { finishVerification(listener, nodes, errors); } } @Override public void handleException(TransportException exp) { errors.add( new VerificationFailure(node.id(), ExceptionsHelper.detailedMessage(exp))); if (counter.decrementAndGet() == 0) { finishVerification(listener, nodes, errors); } } }); } } }
/** * Only use this for AIR blocks (any type of BlockAir) * * @param dimID * @param changeAdd List of <ScheduledBlockChange> */ public static void scheduleNewBlockChange(int dimID, List<ScheduledBlockChange> changeAdd) { CopyOnWriteArrayList<ScheduledBlockChange> changeList = TickHandlerServer.scheduledBlockChanges.get(dimID); if (changeList == null) { changeList = new CopyOnWriteArrayList<ScheduledBlockChange>(); } changeList.addAll(changeAdd); TickHandlerServer.scheduledBlockChanges.put(dimID, changeList); }
private void addToHistory( final List<? extends PsiElement> elements, final FindUsagesOptions findUsagesOptions) { SearchData data = createSearchData(elements, findUsagesOptions); myFindUsagesHistory.remove(data); myFindUsagesHistory.add(data); // todo configure history depth limit if (myFindUsagesHistory.size() > 15) { myFindUsagesHistory.remove(0); } }
/** * Associates given {@link View}. If view has been already added, nothing happens. * * @param view View to be associated */ public void addView(final View view) { for (int i = 0; i < mViewList.size(); i++) { final ViewWeakReference reference = mViewList.get(i); final View item = reference.get(); if (item == null) { // Always remove null references to reduce Set size mViewList.remove(reference); } } mViewList.addIfAbsent(new ViewWeakReference(view)); }
@Override public synchronized void add(int index, Layer layer) { if (mLayerList.contains(layer)) throw new IllegalArgumentException("layer added twice"); if (layer instanceof UpdateListener) mMap.events.bind((UpdateListener) layer); if (layer instanceof InputListener) mMap.input.bind((InputListener) layer); mLayerList.add(index, layer); mDirtyLayers = true; }