Java Code Examples for java.util.concurrent.CopyOnWriteArrayList

The following are top voted examples for showing how to use java.util.concurrent.CopyOnWriteArrayList. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: ListDefaults.java   Source Code and License 6 votes vote down vote up
@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()]);
}
 
Example 2
Project: GitHub   File: EventBus.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 3
Project: litiengine   File: Emitter.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 4
Project: Transwarp-Sample-Code   File: kafkaProducer.java   Source Code and License 6 votes vote down vote up
/**
 * 创建列表,将多个文件夹下文件以及子文件夹文件加入列表中
 * @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;
}
 
Example 5
Project: OKEventBus   File: OKEventBus.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 6
Project: litiengine   File: TileLayer.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 7
Project: mycat-src-1.6.1-RELEASE   File: TestSelectPerf.java   Source Code and License 6 votes vote down vote up
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) );
}
 
Example 8
Project: VASSAL-src   File: DefaultMultiEventListenerSupport.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 9
Project: litiengine   File: Effect.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example 10
Project: metacom-android   File: AndroidJSTPConnection.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 11
Project: java-rxjava   File: TracingObserverTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 12
Project: wcs-android-sdk   File: InternalRequest.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 13
Project: elasticsearch_my   File: RemoteClusterConnectionTests.java   Source Code and License 6 votes vote down vote up
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());
            }
        }
    }
}
 
Example 14
Project: Progetto-A   File: PartitaOfflineConsoleView.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param model modello partita offline
 */
public PartitaOfflineConsoleView(PartitaOfflineModel model) {
    this.listeners = new CopyOnWriteArrayList<>();
    this.model = model;
    this.model.addObserver(this);
    scanner = new Scanner(System.in);
}
 
Example 15
Project: openjdk-jdk10   File: CopyOnWriteArrayListTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
}
 
Example 16
Project: Towan   File: Tower.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 17
Project: rapidminer   File: ProcessDrawer.java   Source Code and License 6 votes vote down vote up
/**
 * 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>();
}
 
Example 18
Project: Elasticsearch   File: TransportBroadcastReplicationAction.java   Source Code and License 6 votes vote down vote up
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));
}
 
Example 19
Project: http2client-benchmark   File: Http2ClientExample.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 20
Project: NotifyTools   File: PropertyUtilsBean.java   Source Code and License 5 votes vote down vote up
/** 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();
}
 
Example 21
Project: elasticsearch_my   File: FlushIT.java   Source Code and License 5 votes vote down vote up
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());
    }
}
 
Example 22
Project: GitHub   File: AbstractEventBusTest.java   Source Code and License 5 votes vote down vote up
public AbstractEventBusTest(boolean collectEventsReceived) {
    if (collectEventsReceived) {
        eventsReceived = new CopyOnWriteArrayList<Object>();
    } else {
        eventsReceived = null;
    }
}
 
Example 23
Project: openjdk-jdk10   File: CopyOnWriteArrayListTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
}
 
Example 24
Project: dubbo-transaction   File: InvokerChainContext.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 25
Project: neatle   File: Device.java   Source Code and License 5 votes vote down vote up
@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);
        }
    }
}
 
Example 26
Project: spring-boot-start-current   File: DefaultInjectionAttackHandler.java   Source Code and License 5 votes vote down vote up
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 );
}
 
Example 27
Project: litiengine   File: AnimationController.java   Source Code and License 5 votes vote down vote up
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);
  }
}
 
Example 28
Project: Nird2   File: LifecycleManagerImpl.java   Source Code and License 5 votes vote down vote up
@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>();
}
 
Example 29
Project: openjdk-jdk10   File: CopyOnWriteArrayListTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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());
}
 
Example 30
Project: Progetto-A   File: PartitaOnlineConsoleView.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @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);
 
}
 
Example 31
Project: litiengine   File: Trigger.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: BiglyBT   File: ImageLoader.java   Source Code and License 5 votes vote down vote up
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();
						}
					}
				});
	}
}
 
Example 33
Project: openjdk-jdk10   File: CopyOnWriteArrayListTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 34
Project: litiengine   File: MovableEntity.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 35
Project: circularplot   File: PlotItem.java   Source Code and License 5 votes vote down vote up
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<>();
}
 
Example 36
Project: dble   File: GetConnectionHandler.java   Source Code and License 5 votes vote down vote up
public GetConnectionHandler(
        CopyOnWriteArrayList<BackendConnection> consToStore,
        int totalNumber) {
    super();
    this.successCons = consToStore;
    this.total = totalNumber;
}
 
Example 37
Project: hekate   File: BackPressureRequestTest.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 38
Project: osc-core   File: JobEngine.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 39
Project: monarch   File: SystemManagementService.java   Source Code and License 5 votes vote down vote up
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>();
}
 
Example 40
Project: starcor.xul   File: XulSubscriberMethodHunter.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
        }
    }
}