Java 类java.util.concurrent.CopyOnWriteArrayList 实例源码
项目:openjdk-jdk10
文件:ListDefaults.java
@DataProvider(name="listProvider", parallel=true)
public static Object[][] listCases() {
final List<Object[]> cases = new LinkedList<>();
cases.add(new Object[] { Collections.emptyList() });
cases.add(new Object[] { new ArrayList<>() });
cases.add(new Object[] { new LinkedList<>() });
cases.add(new Object[] { new Vector<>() });
cases.add(new Object[] { new Stack<>() });
cases.add(new Object[] { new CopyOnWriteArrayList<>() });
cases.add(new Object[] { Arrays.asList() });
List<Integer> l = Arrays.asList(42);
cases.add(new Object[] { new ArrayList<>(l) });
cases.add(new Object[] { new LinkedList<>(l) });
cases.add(new Object[] { new Vector<>(l) });
Stack<Integer> s = new Stack<>(); s.addAll(l);
cases.add(new Object[]{s});
cases.add(new Object[] { new CopyOnWriteArrayList<>(l) });
cases.add(new Object[] { l });
return cases.toArray(new Object[0][cases.size()]);
}
项目:GitHub
文件:EventBus.java
public boolean hasSubscriberForEvent(Class<?> eventClass) {
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
if (eventTypes != null) {
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(clazz);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
return true;
}
}
}
return false;
}
项目:litiengine
文件:Emitter.java
public Emitter(final Point2D origin) {
super();
this.colors = new ArrayList<>();
this.finishedConsumer = new CopyOnWriteArrayList<>();
final EmitterInfo info = this.getClass().getAnnotation(EmitterInfo.class);
this.maxParticles = info.maxParticles();
this.spawnAmount = info.spawnAmount();
this.spawnRate = info.spawnRate();
this.timeToLive = info.emitterTTL();
this.particleMinTTL = info.particleMinTTL();
this.particleMaxTTL = info.particleMaxTTL();
this.particleUpdateDelay = info.particleUpdateRate();
this.particles = new CopyOnWriteArrayList<>();
this.setLocation(origin);
this.activateOnInit = info.activateOnInit();
this.groundRenderable = g -> renderParticles(g, ParticleRenderType.GROUND);
this.overlayRenderable = g -> renderParticles(g, ParticleRenderType.OVERLAY);
}
项目:Transwarp-Sample-Code
文件:kafkaProducer.java
/**
* 创建列表,将多个文件夹下文件以及子文件夹文件加入列表中
* @param folders 文件夹集合
* @return 文件列表
*/
private static CopyOnWriteArrayList<String> addFiles(String[] folders) {
CopyOnWriteArrayList<String> fileList = new CopyOnWriteArrayList<>();
for (String folder : folders) {
File file = new File(folder);
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (!f.isDirectory()) {
fileList.add(f.toString());
} else {
recursion(f.toString(), fileList);
}
}
}
}
return fileList;
}
项目:OKEventBus
文件:OKEventBus.java
public boolean hasSubscriberForEvent(Class<?> eventClass) {
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
if (eventTypes != null) {
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(clazz);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
return true;
}
}
}
return false;
}
项目:litiengine
文件:TileLayer.java
@Override
public List<ITile> getTiles() {
if (this.tileList != null) {
return this.tileList;
}
this.tileList = new CopyOnWriteArrayList<>();
if (this.data == null) {
return this.tileList;
}
this.tiles = new Tile[this.getWidth()][this.getHeight()];
for (int i = 0; i < this.getData().size(); i++) {
final int x = i % this.getWidth();
final int y = i / this.getWidth();
final Tile tile = this.getData().get(i);
tile.setTileCoordinate(new Point(x, y));
this.tileList.add(tile);
this.tiles[x][y] = tile;
}
return this.tileList;
}
项目:mycat-src-1.6.1-RELEASE
文件:TestSelectPerf.java
public static void report(CopyOnWriteArrayList<SelectJob> jobs) {
double tps = 0;
long maxTTL = 0;
long minTTL = Integer.MAX_VALUE;
long ttlCount = 0;
long ttlSum = 0;
DecimalFormat df = new DecimalFormat("0.00");
for (SelectJob job : jobs) {
double jobTps = job.getTPS();
if (jobTps > 0) {
tps += job.getTPS();
if (job.getMaxTTL() > maxTTL) {
maxTTL = job.getMaxTTL();
}
if (job.getMinTTL() < minTTL) {
minTTL = job.getMinTTL();
}
ttlCount += job.getValidTTLCount();
ttlSum += job.getValidTTLSum();
}
}
double avgSum =(ttlCount > 0) ? (ttlSum+0.0) / ttlCount : 0;
System.out.println("finishend:" + finshiedCount.get() + " failed:"
+ failedCount.get() + " qps:" + df.format(tps) + ",query time min:"
+ minTTL + "ms,max:" + maxTTL + "ms,avg:" + df.format(avgSum) );
}
项目:VASSAL-src
文件:DefaultMultiEventListenerSupport.java
protected List<EventListener<?>> registerType(Class<?> c) {
// ensure that a listener list exists for class c
listeners.putIfAbsent(c, new CopyOnWriteArrayList<EventListener<?>>());
final Set<EventListener<?>> lset = new HashSet<EventListener<?>>();
// make a set of all listeners for every supertype of c
for (Map.Entry<Class<?>,List<EventListener<?>>> e : listeners.entrySet()) {
final Class<?> other = e.getKey();
if (other.isAssignableFrom(c)) {
lset.addAll(e.getValue());
}
}
final List<EventListener<?>> list = listeners.get(c);
list.addAll(lset);
return list;
}
项目:litiengine
文件:Effect.java
/**
* Instantiates a new effect.
*
* @param ability
* the ability
* @param targets
* the targets
*/
protected Effect(final Ability ability, final EffectTarget... targets) {
this.appliedConsumer = new CopyOnWriteArrayList<>();
this.ceasedConsumer = new CopyOnWriteArrayList<>();
this.appliances = new ArrayList<>();
this.followUpEffects = new CopyOnWriteArrayList<>();
this.ability = ability;
this.targetPriorityComparator = new EntityDistanceComparator(this.getAbility().getExecutor());
this.duration = ability.getAttributes().getDuration().getCurrentValue();
if (targets == null || targets.length == 0) {
this.effectTargets = new EffectTarget[] { EffectTarget.NONE };
} else {
this.effectTargets = targets;
}
}
项目:metacom-android
文件:AndroidJSTPConnection.java
public AndroidJSTPConnection(String host, int port, boolean usesSSL, Context context) {
mListeners = new CopyOnWriteArrayList<>();
mTaggedCacheCalls = new ConcurrentHashMap<>();
mConnectionState = STATE_NOT_CONNECTED;
mNeedsRestoration = true;
mContext = context;
TCPTransport transport = new TCPTransport(host, port, usesSSL);
mConnection = new Connection(transport, this);
mConnection.addSocketListener(this);
mBroadcastManager = LocalBroadcastManager.getInstance(mContext);
initNetworkReceiver();
}
项目:java-rxjava
文件:TracingObserverTest.java
@Test
public void two_parallel() throws Exception {
List<Integer> result = new CopyOnWriteArrayList<>();
executeParallelObservable("first_parallel", result);
executeParallelObservable("second_parallel", result);
await().atMost(15, TimeUnit.SECONDS).until(reportedSpansSize(mockTracer), equalTo(2));
assertEquals(10, result.size());
List<MockSpan> spans = mockTracer.finishedSpans();
assertEquals(2, spans.size());
assertNotEquals(spans.get(0).context().traceId(), spans.get(1).context().traceId());
assertNull(mockTracer.scopeManager().active());
}
项目:wcs-android-sdk
文件:InternalRequest.java
public void cancelRequests(Context context, Object tag) {
List<CancellationHandler> requestList = requestMap.get(context);
if (requestList != null) {
List<CancellationHandler> cancelledHandler = new CopyOnWriteArrayList<CancellationHandler>();
for (CancellationHandler cancellationHandler : requestList) {
boolean shouldCancel = tag == null;
if (!shouldCancel) {
shouldCancel = tag.equals(cancellationHandler.getTag());
}
if (shouldCancel) {
cancellationHandler.cancel();
cancelledHandler.add(cancellationHandler);
}
}
requestList.removeAll(cancelledHandler);
if (requestList.size() == 0) {
requestMap.remove(context);
}
System.gc();
}
}
项目:elasticsearch_my
文件:RemoteClusterConnectionTests.java
public void testDiscoverSingleNode() throws Exception {
List<DiscoveryNode> knownNodes = new CopyOnWriteArrayList<>();
try (MockTransportService seedTransport = startTransport("seed_node", knownNodes, Version.CURRENT);
MockTransportService discoverableTransport = startTransport("discoverable_node", knownNodes, Version.CURRENT)) {
DiscoveryNode seedNode = seedTransport.getLocalDiscoNode();
DiscoveryNode discoverableNode = discoverableTransport.getLocalDiscoNode();
knownNodes.add(seedTransport.getLocalDiscoNode());
knownNodes.add(discoverableTransport.getLocalDiscoNode());
Collections.shuffle(knownNodes, random());
try (MockTransportService service = MockTransportService.createNewService(Settings.EMPTY, Version.CURRENT, threadPool, null)) {
service.start();
service.acceptIncomingRequests();
try (RemoteClusterConnection connection = new RemoteClusterConnection(Settings.EMPTY, "test-cluster",
Arrays.asList(seedNode), service, Integer.MAX_VALUE, n -> true)) {
updateSeedNodes(connection, Arrays.asList(seedNode));
assertTrue(service.nodeConnected(seedNode));
assertTrue(service.nodeConnected(discoverableNode));
assertTrue(connection.assertNoRunningConnections());
}
}
}
}
项目:openjdk-jdk10
文件:CopyOnWriteArrayListTest.java
/**
* sublists contains elements at indexes offset from their base
*/
public void testSubList() {
CopyOnWriteArrayList a = populatedArray(10);
assertTrue(a.subList(1,1).isEmpty());
for (int j = 0; j < 9; ++j) {
for (int i = j ; i < 10; ++i) {
List b = a.subList(j,i);
for (int k = j; k < i; ++k) {
assertEquals(new Integer(k), b.get(k-j));
}
}
}
List s = a.subList(2, 5);
assertEquals(3, s.size());
s.set(2, m1);
assertEquals(a.get(4), m1);
s.clear();
assertEquals(7, a.size());
}
项目:Towan
文件:Tower.java
public Tower(TowerType type, Tile startTile, CopyOnWriteArrayList<Enemy> enemies){
this.type = type;
this.textures = type.textures;
this.range = type.range;
this.cost = type.cost;
this.x = startTile.getX();
this.y = startTile.getY();
this.width = startTile.getWidth();
this.height = startTile.getHeight();
this.enemies = enemies;
this.targeted = false;
this.timeSinceLastShot = 0f;
this.projectiles = new ArrayList<Projectile>();
this.firingSpeed = type.firingSpeed;
this.angle = 0f;
}
项目:rapidminer
文件:ProcessDrawer.java
/**
* Creates a new drawer instance which can be used to draw the process specified in the model.
*
* @param model
* the model containing the data needed to draw the process. See
* {@link ProcessRendererModel} for a minimal configuration
* @param drawHighlight
* if {@code true} will highlight drop area in the process during drag & drop
*/
public ProcessDrawer(final ProcessRendererModel model, final boolean drawHighlight) {
if (model == null) {
throw new IllegalArgumentException("model must not be null!");
}
this.model = model;
this.drawHighlight = drawHighlight;
// prepare decorators for each phase
decorators = new HashMap<>();
for (RenderPhase phase : RenderPhase.drawOrder()) {
decorators.put(phase, new CopyOnWriteArrayList<ProcessDrawDecorator>());
}
// prepare operator decorators
operatorDecorators = new CopyOnWriteArrayList<OperatorDrawDecorator>();
}
项目:Elasticsearch
文件:TransportBroadcastReplicationAction.java
private void finishAndNotifyListener(ActionListener listener, CopyOnWriteArrayList<ShardResponse> shardsResponses) {
logger.trace("{}: got all shard responses", actionName);
int successfulShards = 0;
int failedShards = 0;
int totalNumCopies = 0;
List<ShardOperationFailedException> shardFailures = null;
for (int i = 0; i < shardsResponses.size(); i++) {
ActionWriteResponse shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
// non active shard, ignore
} else {
failedShards += shardResponse.getShardInfo().getFailed();
successfulShards += shardResponse.getShardInfo().getSuccessful();
totalNumCopies += shardResponse.getShardInfo().getTotal();
if (shardFailures == null) {
shardFailures = new ArrayList<>();
}
for (ActionWriteResponse.ShardInfo.Failure failure : shardResponse.getShardInfo().getFailures()) {
shardFailures.add(new DefaultShardOperationFailedException(new BroadcastShardOperationFailedException(new ShardId(failure.index(), failure.shardId()), failure.getCause())));
}
}
}
listener.onResponse(newResponse(successfulShards, failedShards, totalNumCopies, shardFailures));
}
项目:http2client-benchmark
文件:Http2ClientExample.java
public void testMultipleHttp2Post(int round) throws Exception {
final Http2Client client = Http2Client.getInstance();
final List<AtomicReference<ClientResponse>> references = new CopyOnWriteArrayList<>();
final CountDownLatch latch = new CountDownLatch(round);
final ClientConnection connection = client.connect(new URI("https://localhost:8443"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
try {
connection.getIoThread().execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < round; i++) {
AtomicReference<ClientResponse> reference = new AtomicReference<>();
references.add(i, reference);
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
request.getRequestHeaders().put(Headers.HOST, "localhost");
connection.sendRequest(request, client.createClientCallback(reference, latch, "post"));
}
}
});
latch.await(10, TimeUnit.SECONDS);
/*
for (final AtomicReference<ClientResponse> reference : references) {
System.out.println(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
System.out.println(reference.get().getProtocol().toString());
}
*/
} finally {
IoUtils.safeClose(connection);
}
}
项目:NotifyTools
文件:PropertyUtilsBean.java
/** Base constructor */
public PropertyUtilsBean() {
descriptorsCache = new WeakFastHashMap<Class<?>, BeanIntrospectionData>();
descriptorsCache.setFast(true);
mappedDescriptorsCache = new WeakFastHashMap<Class<?>, FastHashMap>();
mappedDescriptorsCache.setFast(true);
introspectors = new CopyOnWriteArrayList<BeanIntrospector>();
resetBeanIntrospectors();
}
项目:elasticsearch_my
文件:FlushIT.java
public void testWaitIfOngoing() throws InterruptedException {
createIndex("test");
ensureGreen("test");
final int numIters = scaledRandomIntBetween(10, 30);
for (int i = 0; i < numIters; i++) {
for (int j = 0; j < 10; j++) {
client().prepareIndex("test", "test").setSource("{}", XContentType.JSON).get();
}
final CountDownLatch latch = new CountDownLatch(10);
final CopyOnWriteArrayList<Throwable> errors = new CopyOnWriteArrayList<>();
for (int j = 0; j < 10; j++) {
client().admin().indices().prepareFlush("test").execute(new ActionListener<FlushResponse>() {
@Override
public void onResponse(FlushResponse flushResponse) {
try {
// don't use assertAllSuccessful it uses a randomized context that belongs to a different thread
assertThat("Unexpected ShardFailures: " + Arrays.toString(flushResponse.getShardFailures()), flushResponse.getFailedShards(), equalTo(0));
latch.countDown();
} catch (Exception ex) {
onFailure(ex);
}
}
@Override
public void onFailure(Exception e) {
errors.add(e);
latch.countDown();
}
});
}
latch.await();
assertThat(errors, emptyIterable());
}
}
项目:GitHub
文件:AbstractEventBusTest.java
public AbstractEventBusTest(boolean collectEventsReceived) {
if (collectEventsReceived) {
eventsReceived = new CopyOnWriteArrayList<Object>();
} else {
eventsReceived = null;
}
}
项目:openjdk-jdk10
文件:CopyOnWriteArrayListTest.java
/**
* Cloned list is equal
*/
public void testClone() {
CopyOnWriteArrayList l1 = populatedArray(SIZE);
CopyOnWriteArrayList l2 = (CopyOnWriteArrayList)(l1.clone());
assertEquals(l1, l2);
l1.clear();
assertFalse(l1.equals(l2));
}
项目:dubbo-transaction
文件:InvokerChainContext.java
public void add(InvokerExchangeFilter.ExchangeObject eo){
if(!_EO_CHILDREN.containsKey(eo.getInvokerId())){
synchronized (_EO_CHILDREN) {
if(!_EO_CHILDREN.containsKey(eo.getInvokerId())) {
_EO_CHILDREN.put(eo.getInvokerId(), new CopyOnWriteArrayList<InvokerExchangeFilter.ExchangeObject>());
}
}
}
_EO_CHILDREN.get(eo.getInvokerId()).add(eo);
_EO_OBJECT.put(eo.getExchangeId(),eo);
}
项目:neatle
文件:Device.java
@Override
public void addCharacteristicsChangedListener(UUID characteristicsUUID, CharacteristicsChangedListener listener) {
synchronized (lock) {
CopyOnWriteArrayList<CharacteristicsChangedListener> list = changeListeners.get(characteristicsUUID);
if (list == null) {
list = new CopyOnWriteArrayList<>();
list.add(listener);
changeListeners.put(characteristicsUUID, list);
} else if (!list.contains(listener)) {
list.add(listener);
}
}
}
项目:spring-boot-start-current
文件:DefaultInjectionAttackHandler.java
private boolean ignoreStringMatchingHandle ( Matcher matcher , String[] ignoreStrings ) {
List< Boolean > matchingResults = new CopyOnWriteArrayList<>();
// 如果找到匹配的
while ( matcher.find() ) {
final String matcherString = matcher.group();
// 忽略结果集
matchingResults.add( ArrayUtils.contains( ignoreStrings , matcherString ) );
}
// 如果其中一个为false
return matchingResults.contains( false );
}
项目:litiengine
文件:AnimationController.java
private AnimationController(final Animation defaultAnimation) {
this.animations = new CopyOnWriteArrayList<>();
this.imageEffects = new CopyOnWriteArrayList<>();
this.playbackFinishedConsumer = new CopyOnWriteArrayList<>();
this.playbackConsumer = new CopyOnWriteArrayList<>();
this.defaultAnimation = defaultAnimation;
if (this.defaultAnimation != null) {
this.animations.add(this.defaultAnimation);
}
}
项目:Nird2
文件:LifecycleManagerImpl.java
@Inject
LifecycleManagerImpl(DatabaseComponent db, EventBus eventBus,
CryptoComponent crypto, AuthorFactory authorFactory,
IdentityManager identityManager) {
this.db = db;
this.eventBus = eventBus;
this.crypto = crypto;
this.authorFactory = authorFactory;
this.identityManager = identityManager;
services = new CopyOnWriteArrayList<Service>();
clients = new CopyOnWriteArrayList<Client>();
executors = new CopyOnWriteArrayList<ExecutorService>();
}
项目:openjdk-jdk10
文件:CopyOnWriteArrayListTest.java
/**
* size returns the number of elements
*/
public void testSize() {
CopyOnWriteArrayList empty = new CopyOnWriteArrayList();
CopyOnWriteArrayList full = populatedArray(SIZE);
assertEquals(SIZE, full.size());
assertEquals(0, empty.size());
}
项目:Progetto-A
文件:PartitaOnlineConsoleView.java
/**
*
* @param controller controller della partita online
*/
public PartitaOnlineConsoleView(PartitaOnlineController controller) {
this.listeners = new CopyOnWriteArrayList<>();
this.controller = controller;
this.controller.addObserver(this);
scanner = new Scanner(System.in);
listeners.add(controller);
}
项目:litiengine
文件:Trigger.java
public Trigger(final TriggerActivation activation, final String name, final String message, final boolean isOneTime, final Map<String, String> arguments) {
super();
this.activatingPredicates = new CopyOnWriteArrayList<>();
this.activatedConsumer = new CopyOnWriteArrayList<>();
this.deactivatedConsumer = new CopyOnWriteArrayList<>();
this.arguments = arguments;
this.activators = new CopyOnWriteArrayList<>();
this.targets = new CopyOnWriteArrayList<>();
this.activated = new CopyOnWriteArrayList<>();
this.setName(name);
this.message = message;
this.isOneTimeTrigger = isOneTime;
this.activationType = activation;
}
项目:BiglyBT
文件:ImageLoader.java
public ImageLoader(/*ClassLoader classLoader,*/Display display,
SkinProperties skinProperties) {
//this.classLoader = classLoader;
File[] files = cache_dir.listFiles();
if ( files != null ){
for (File f: files ){
String name = f.getName();
if ( name.endsWith( ".ico" )){
cached_resources.add( name );
}
}
}
_mapImages = new ConcurrentHashMap<>();
notFound = new ArrayList<>();
this.display = display;
this.skinProperties = new CopyOnWriteArrayList<>();
addSkinProperties(skinProperties);
AEDiagnostics.addWeakEvidenceGenerator(this);
if (GC_INTERVAL > 0) {
periodicEvent = SimpleTimer.addPeriodicEvent("GC_ImageLoader", GC_INTERVAL,
new TimerEventPerformer() {
@Override
public void perform(TimerEvent event) {
if (!collectGarbage()) {
event.cancel();
}
}
});
}
}
项目:openjdk-jdk10
文件:CopyOnWriteArrayListTest.java
/**
* set throws an IndexOutOfBoundsException on a negative index
*/
public void testSet1_IndexOutOfBoundsException() {
CopyOnWriteArrayList c = populatedArray(5);
List[] lists = { c, c.subList(1, c.size() - 1) };
for (List list : lists) {
try {
list.set(-1, "qwerty");
shouldThrow();
} catch (IndexOutOfBoundsException success) {}
}
}
项目:litiengine
文件:MovableEntity.java
public MovableEntity() {
this.entityMovedConsumer = new CopyOnWriteArrayList<>();
final MovementInfo info = this.getClass().getAnnotation(MovementInfo.class);
this.velocity = info.velocity();
this.acceleration = info.acceleration();
this.deceleration = info.deceleration();
this.setTurnOnMove(info.turnOnMove());
}
项目:circularplot
文件:PlotItem.java
public PlotItem(final String NAME, final double VALUE, final String DESCRIPTION, final Color COLOR) {
_name = NAME;
_value = VALUE;
_description = DESCRIPTION;
_color = COLOR;
level = -1;
outgoing = new LinkedHashMap<>();
incoming = new LinkedHashMap<>();
listeners = new CopyOnWriteArrayList<>();
}
项目:dble
文件:GetConnectionHandler.java
public GetConnectionHandler(
CopyOnWriteArrayList<BackendConnection> consToStore,
int totalNumber) {
super();
this.successCons = consToStore;
this.total = totalNumber;
}
项目:hekate
文件:BackPressureRequestTest.java
@Test
public void test() throws Exception {
List<Message<String>> requests = new CopyOnWriteArrayList<>();
createChannel(c -> useBackPressure(c)
.withReceiver(requests::add)
).join();
MessagingChannel<String> sender = createChannel(this::useBackPressure).join().get().forRemotes();
// Enforce back pressure on sender.
List<ResponseFuture<String>> futureResponses = requestUpToHighWatermark(sender);
busyWait("requests received", () -> requests.size() == futureResponses.size());
assertBackPressureEnabled(sender);
// Go down to low watermark.
requests.stream().limit(getLowWatermarkBounds()).forEach(r -> r.reply("ok"));
busyWait("responses received", () ->
futureResponses.stream().filter(CompletableFuture::isDone).count() == getLowWatermarkBounds()
);
// Check that new request can be processed.
get(sender.send("last"));
requests.stream().filter(Message::mustReply).forEach(r -> r.reply("ok"));
for (Future<?> future : futureResponses) {
get(future);
}
}
项目:osc-core
文件:JobEngine.java
public synchronized Job getJobByTask(Task task) {
CopyOnWriteArrayList<Job> activeJobsCopy = new CopyOnWriteArrayList<>(this.activeJobs);
Iterator<Job> it = activeJobsCopy.iterator();
while (it.hasNext()) {
Job job = it.next();
for (TaskNode taskNode : job.getTaskGraph().getGraph().getNodes()) {
if (taskNode.getTask() == task) {
return job;
}
}
}
return null;
}
项目:monarch
文件:SystemManagementService.java
protected SystemManagementService(Cache cache) {
this.cache = cache;
this.system = (InternalDistributedSystem) cache.getDistributedSystem();
// This is a safe check to ensure Management service does not start for a
// system which is disconnected.
// Most likely scenario when this will happen is when a cache is closed and we are at this
// point.
if (!system.isConnected()) {
throw new DistributedSystemDisconnectedException(
LocalizedStrings.InternalDistributedSystem_THIS_CONNECTION_TO_A_DISTRIBUTED_SYSTEM_HAS_BEEN_DISCONNECTED
.toLocalizedString());
}
this.localFilterChain = new LocalFilterChain();
this.jmxAdapter = new MBeanJMXAdapter();
this.repo = new ManagementResourceRepo();
this.notificationHub = new NotificationHub(repo);
if (system.getConfig().getJmxManager()) {
this.agent = new ManagementAgent(system.getConfig());
} else {
this.agent = null;
}
ManagementFunction function = new ManagementFunction(notificationHub);
FunctionService.registerFunction(function);
this.proxyListeners = new CopyOnWriteArrayList<ProxyListener>();
}
项目:starcor.xul
文件:XulSubscriberMethodHunter.java
/**
* remove subscriber methods from map
*/
public void removeMethodsFromMap(Object subscriber) {
Iterator<CopyOnWriteArrayList<XulSubscription>> iterator =
_subscriberMap.values().iterator();
while (iterator.hasNext()) {
CopyOnWriteArrayList<XulSubscription> subscriptions = iterator.next();
if (subscriptions != null) {
List<XulSubscription> foundSubscriptions = new LinkedList<XulSubscription>();
Iterator<XulSubscription> subIterator = subscriptions.iterator();
while (subIterator.hasNext()) {
XulSubscription xulSubscription = subIterator.next();
// 获取引用
Object cacheObject = xulSubscription.getSubscriber();
if ((cacheObject == null)
|| cacheObject.equals(subscriber)) {
xulSubscription.clearXulMessages();
foundSubscriptions.add(xulSubscription);
}
}
// 移除该subscriber的相关的Subscription
subscriptions.removeAll(foundSubscriptions);
}
// 如果针对某个Msg的订阅者数量为空了,那么需要从map中清除
if (subscriptions == null || subscriptions.size() == 0) {
iterator.remove();
}
}
}
项目:dubbox-hystrix
文件:AbstractRegistryService.java
private void addListener(final String service, final NotifyListener listener){
if (listener == null) {
return;
}
List<NotifyListener> listeners = notifyListeners.get(service);
if (listeners == null) {
notifyListeners.putIfAbsent(service, new CopyOnWriteArrayList<NotifyListener>());
listeners = notifyListeners.get(service);
}
if (listeners != null && !listeners.contains(listener)){
listeners.add(listener);
}
}