java.util.concurrent.CopyOnWriteArrayList Java Examples

The following examples show how to use java.util.concurrent.CopyOnWriteArrayList. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeMethod(alwaysRun=true)
@Override
public void setUp() throws Exception {
    super.setUp();
    
    events = new CopyOnWriteArrayList<SensorEvent<FailureDescriptor>>();
    eventListener = new SensorEventListener<FailureDescriptor>() {
        @Override public void onEvent(SensorEvent<FailureDescriptor> event) {
            events.add(event);
        }
    };
    
    e1 = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    e1.enrichers().add(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp());
    
    app.getManagementContext().getSubscriptionManager().subscribe(e1, HASensors.ENTITY_FAILED, eventListener);
    app.getManagementContext().getSubscriptionManager().subscribe(e1, HASensors.ENTITY_RECOVERED, eventListener);
}
 
Example #2
Source File: WebSocketSampleApplicationTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testWebSocket() {
    Flux<String> originalMessages = Flux.just("first", "second");
    List<String> responseMessages = new CopyOnWriteArrayList<>();

    disposable = client.execute(serviceUri, session -> {
        // Convert strings to WebSocket messages and send them
        Mono<Void> outputMono = session.send(originalMessages.map(session::textMessage));

        Mono<Void> inputMono = session.receive() // Receive a messages stream
            .map(WebSocketMessage::getPayloadAsText) // Extract a payload from each message
            .doOnNext(responseMessages::add) // Store the payload to a collection
            .then();

        return outputMono.then(inputMono); // Start receiving messages after sending.
    }).subscribe(); // Subscribe to the socket. Original messages will be sent and then we'll start receiving responses.

    await()
        .atMost(2, SECONDS)
        .until(() -> responseMessages, contains("FIRST", "SECOND"));
}
 
Example #3
Source File: MissionManager.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Adds a new mission to the mission list.
 * 
 * @param newMission new mission to be added
 */
public void addMission(Mission newMission) {
	if (newMission == null) {
		throw new IllegalArgumentException("newMission is null");
	}

	if (!onGoingMissions.contains(newMission)) {
		onGoingMissions.add(newMission);

		// Update listeners.
		if (listeners == null) {
			listeners = new CopyOnWriteArrayList<>();//Collections.synchronizedList(new ArrayList<MissionManagerListener>());
		}

		synchronized (listeners) {
			Iterator<MissionManagerListener> i = listeners.iterator();
			while (i.hasNext()) {
				i.next().addMission(newMission);
			}
		}

		// recordMission(newMission);

		logger.fine("Added a new '" + newMission.getName() + "' mission.");
	}
}
 
Example #4
Source File: PixelMatrix.java    From tilesfx with Apache License 2.0 6 votes vote down vote up
public PixelMatrix(final double PREFERRED_WIDTH, final double PREFERRED_HEIGHT, final int COLS, final int ROWS, final Color DOT_ON_COLOR, final Color DOT_OFF_COLOR, final PixelShape DOT_SHAPE, final MatrixFont FONT) {
    preferredWidth         = PREFERRED_WIDTH;
    preferredHeight        = PREFERRED_HEIGHT;
    pixelOnColor           = convertToInt(DOT_ON_COLOR);
    pixelOffColor          = convertToInt(DOT_OFF_COLOR);
    pixelShape             = DOT_SHAPE;
    cols                   = COLS;
    rows                   = ROWS;
    matrix                 = new int[cols][rows];
    matrixFont             = FONT;
    characterWidth         = matrixFont.getCharacterWidth();
    characterHeight        = matrixFont.getCharacterHeight();
    characterWidthMinusOne = characterWidth - 1;
    useSpacer              = true;
    squarePixels           = true;
    innerShadowEnabled     = false;
    spacerSizeFactor       = DEFAULT_SPACER_SIZE_FACTOR;
    sizeListener           = o -> resize();
    clickHandler           = e -> checkForClick(e);
    listeners              = new CopyOnWriteArrayList<>();
    initGraphics();
    registerListeners();
}
 
Example #5
Source File: SingleProjectBuildTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Test
public void buildWithAdvancedOptionsTest() throws Exception {
    // given
    BuildOptions originalBuildOptions = new BuildOptions(true, true, true, true, RebuildMode.FORCE);
    DatastoreMock datastoreMock = new DatastoreMock();
    TestProjectConfigurationBuilder configurationBuilder = new TestProjectConfigurationBuilder(datastoreMock);
    List<BuildStatusChangedEvent> receivedStatuses = new CopyOnWriteArrayList<>();

    // when
    BuildCoordinator coordinator = buildCoordinatorFactory.createBuildCoordinator(datastoreMock).coordinator;
    BuildTask buildTask = buildProject(
            configurationBuilder.build(1, "c1-java"),
            coordinator,
            receivedStatuses::add,
            originalBuildOptions);

    // then
    List<BuildRecord> buildRecords = datastoreMock.getBuildRecords();
    Assert.assertEquals("Wrong datastore results count.", 1, buildRecords.size());
    Assert.assertEquals(originalBuildOptions, buildTask.getBuildOptions());
}
 
Example #6
Source File: ProcessDrawer.java    From rapidminer-studio with GNU Affero General Public License v3.0 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 #7
Source File: Window.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new window with the specified max window size.  This
 * constructor enables automatic recurring tasks to be executed (such as
 * expiration of requests).
 * @param size The maximum number of requests permitted to
 *      be outstanding (unacknowledged) at a given time.  Must be > 0.
 * @param executor The scheduled executor service to execute
 *      recurring tasks (such as expiration of requests).
 * @param monitorInterval The number of milliseconds between executions of
 *      monitoring tasks.
 * @param listener A listener to send window events to
 * @param monitorThreadName The thread name we'll change to when a monitor
 *      run is executed.  Null if no name change is required.
 */
public Window(int size, ScheduledExecutorService executor, long monitorInterval, WindowListener<K,R,P> listener, String monitorThreadName) {
    if (size <= 0) {
        throw new IllegalArgumentException("size must be > 0");
    }
    this.maxSize = size;
    this.futures = new ConcurrentHashMap<K,DefaultWindowFuture<K,R,P>>(size*2);
    this.lock = new ReentrantLock();
    this.completedCondition = this.lock.newCondition();
    this.pendingOffers = new AtomicInteger(0);
    this.pendingOffersAborted = new AtomicBoolean(false);
    this.executor = executor;
    this.monitorInterval = monitorInterval;
    this.listeners = new CopyOnWriteArrayList<UnwrappedWeakReference<WindowListener<K,R,P>>>();
    if (listener != null) {
        this.listeners.add(new UnwrappedWeakReference<WindowListener<K,R,P>>(listener));
    }
    if (this.executor != null) {
        this.monitor = new WindowMonitor(this, monitorThreadName);
        this.monitorHandle = this.executor.scheduleWithFixedDelay(this.monitor, this.monitorInterval, this.monitorInterval, TimeUnit.MILLISECONDS);
    } else {
        this.monitor = null;
        this.monitorHandle = null;
    }
}
 
Example #8
Source File: EventBusBridgeTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatEventBusMessagesAreOnlyTransferredToOneStompClientsInP2P() throws InterruptedException {
  List<Frame> frames = new CopyOnWriteArrayList<>();
  server.stompHandler().bridge(new BridgeOptions()
          .addOutboundPermitted(new PermittedOptions().setAddress("/toStomp"))
          .setPointToPoint(true)
  );

  clients.add(StompClient.create(vertx).connect(ar -> {
    final StompClientConnection connection = ar.result();
    connection.subscribe("/toStomp", frames::add,
        f -> {
          clients.add(StompClient.create(vertx).connect(ar2 -> {
            final StompClientConnection connection2 = ar2.result();
            connection2.subscribe("/toStomp", frames::add, receipt -> {
              vertx.eventBus().publish("/toStomp", "Hello from Vert.x", new DeliveryOptions().addHeader("foo", "bar"));
            });
          }));
        });
  }));

  Thread.sleep(500);
  assertThat(frames).hasSize(1);
}
 
Example #9
Source File: MultiSubscribeTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeWithItemFailureAndCompletion() {
    List<Long> items = new CopyOnWriteArrayList<>();
    AtomicBoolean completion = new AtomicBoolean();
    AtomicReference<Throwable> failure = new AtomicReference<>();

    Multi.createFrom().ticks().every(Duration.ofMillis(10))
            .transform().byTakingFirstItems(10)
            .subscribe().with(items::add, failure::set, () -> completion.set(true));

    await().until(() -> items.size() > 5);
    await().until(completion::get);
    assertThat(items).contains(1L, 2L, 3L, 4L, 5L);
    assertThat(failure.get()).isNull();
    assertThat(completion).isTrue();
}
 
Example #10
Source File: DemoPlayer.java    From Exoplayer_VLC with Apache License 2.0 6 votes vote down vote up
public DemoPlayer(RendererBuilder rendererBuilder) {
  this.rendererBuilder = rendererBuilder;
  //###AXT:: --> try to start the player without internal buffering. We do buffering in Raw Sample sources
  // player = ExoPlayer.Factory.newInstance(RENDERER_COUNT, 1000, 5000);
  player = ExoPlayer.Factory.newInstance(RENDERER_COUNT, -1, -1);
  //###AXT:: <--
  player.addListener(this);
  playerControl = new PlayerControl(player);
  mainHandler = new Handler();
  listeners = new CopyOnWriteArrayList<Listener>();
  lastReportedPlaybackState = STATE_IDLE;
  rendererBuildingState = RENDERER_BUILDING_STATE_IDLE;
  selectedTracks = new int[RENDERER_COUNT];
  // Disable text initially.
  selectedTracks[TYPE_TEXT] = DISABLED_TRACK;
}
 
Example #11
Source File: BaseRecycleAdapter.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public void remoteItem(int position) {
    MediaModel mediaModel = (MediaModel) this.modelList.get(position);
    String localPath = mediaModel.getFileLocalPath();
    String formateDate = mediaModel.getFormatDate();
    this.modelNoHeadList.remove(mediaModel);
    this.modelList.remove(mediaModel);
    if (this.stateHashMap != null && localPath != null) {
        CopyOnWriteArrayList<T> internalList = (CopyOnWriteArrayList) this.stateHashMap.get(formateDate);
        if (internalList != null) {
            Iterator it = internalList.iterator();
            while (it.hasNext()) {
                MediaModel cacheModel = (MediaModel) it.next();
                if (cacheModel != null && localPath.equals(cacheModel.getFileLocalPath())) {
                    internalList.remove(cacheModel);
                }
            }
            if (internalList.size() < this.internalListBound) {
                this.modelList.remove(internalList.get(0));
            }
        }
    }
}
 
Example #12
Source File: PluginPackageManagerNative.java    From Neptune with Apache License 2.0 5 votes vote down vote up
/**
 * 异步执行下一个Action
 */
private void executeNextAction(final CopyOnWriteArrayList<Action> actions, final String packageName) {
    mActionExecutor.execute(new Runnable() {
        @Override
        public void run() {

            synchronized (actions) {  // Action列表加锁同步
                if (actions.size() > 0) {
                    PluginDebugLog.installFormatLog(TAG, "start find can execute action ...");
                    Iterator<Action> iterator = actions.iterator();
                    while (iterator.hasNext()) {
                        Action action = iterator.next();
                        if (action.meetCondition()) {
                            PluginDebugLog.installFormatLog(TAG,
                                    "doAction for %s and action is %s", packageName,
                                    action.toString());
                            action.doAction();
                            break;  //跳出循环
                        } else {
                            PluginDebugLog.installFormatLog(TAG,
                                    "remove deprecate action of %s,and action:%s "
                                    , packageName, action.toString());
                            actions.remove(action);
                        }
                    }

                    if (actions.isEmpty()) {
                        PluginDebugLog.installFormatLog(TAG,
                                "executeNextAction remove empty action list of %s", packageName);
                        sActionMap.remove(packageName);
                    }
                }
            }
        }
    });
}
 
Example #13
Source File: AbstractRegistryService.java    From dubbox with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #14
Source File: ArrayWidgetProperty.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected List<WPE> restrictValue(final List<WPE> requested_value)
{
    if (requested_value instanceof CopyOnWriteArrayList)
        return requested_value;
    return new CopyOnWriteArrayList<>(requested_value);
}
 
Example #15
Source File: DownFwService.java    From FimiX8-RE with MIT License 5 votes vote down vote up
private void reportProgress(DownState state, int progress, String name) {
    if (!state.equals(DownState.StopDown)) {
        CopyOnWriteArrayList<IDownProgress> list = DownNoticeMananger.getDownNoticManger().getNoticeList();
        if (list != null && list.size() > 0) {
            Iterator it = list.iterator();
            while (it.hasNext()) {
                ((IDownProgress) it.next()).onProgress(state, progress, name);
            }
        }
    }
}
 
Example #16
Source File: EVCacheClientPoolManager.java    From EVCache with Apache License 2.0 5 votes vote down vote up
@Inject
public EVCacheClientPoolManager(IConnectionBuilder connectionFactoryprovider, EVCacheNodeList evcacheNodeList, EVCacheConfig evcConfig) {
    instance = this;

    this.connectionFactoryProvider = connectionFactoryprovider;
    this.evcacheNodeList = evcacheNodeList;
    this.evcConfig = evcConfig;
    this.evcacheEventListenerList = new CopyOnWriteArrayList<EVCacheEventListener>();

    String clientCurrentInstanceId = null;
    if(clientCurrentInstanceId == null) clientCurrentInstanceId= System.getenv("EC2_INSTANCE_ID");
    if(clientCurrentInstanceId == null) clientCurrentInstanceId= System.getenv("NETFLIX_INSTANCE_ID");
    if(log.isInfoEnabled()) log.info("\nClient Current InstanceId from env = " + clientCurrentInstanceId);
    if(clientCurrentInstanceId == null && EVCacheConfig.getInstance().getPropertyRepository() != null) clientCurrentInstanceId = EVCacheConfig.getInstance().getPropertyRepository().get("EC2_INSTANCE_ID", String.class).orElse(null).get();
    if(clientCurrentInstanceId == null && EVCacheConfig.getInstance().getPropertyRepository() != null) clientCurrentInstanceId = EVCacheConfig.getInstance().getPropertyRepository().get("NETFLIX_INSTANCE_ID", String.class).orElse(null).get();

    if(clientCurrentInstanceId != null && !clientCurrentInstanceId.equalsIgnoreCase("localhost")) {
        this.defaultReadTimeout = EVCacheConfig.getInstance().getPropertyRepository().get("default.read.timeout", Integer.class).orElse(20);
        if(log.isInfoEnabled()) log.info("\nClient Current InstanceId = " + clientCurrentInstanceId + " which is probably a cloud location. The default.read.timeout = " + defaultReadTimeout);
    } else { //Assuming this is not in cloud so bump up the timeouts
        this.defaultReadTimeout = EVCacheConfig.getInstance().getPropertyRepository().get("default.read.timeout", Integer.class).orElse(750);
        if(log.isInfoEnabled()) log.info("\n\nClient Current InstanceId = " + clientCurrentInstanceId + ". Probably a non-cloud instance. The default.read.timeout = " + defaultReadTimeout + "\n\n");
    }
    this.logEnabledApps = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheClientPoolManager.log.apps", String.class).orElse("*");
    this.defaultRefreshInterval = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheClientPoolManager.refresh.interval", Integer.class).orElse(60);

    this.asyncExecutor = new EVCacheScheduledExecutor(Runtime.getRuntime().availableProcessors(),Runtime.getRuntime().availableProcessors(), 30, TimeUnit.SECONDS, new ThreadPoolExecutor.CallerRunsPolicy(), "scheduled");
    asyncExecutor.prestartAllCoreThreads();
    this.syncExecutor = new EVCacheExecutor(Runtime.getRuntime().availableProcessors(),Runtime.getRuntime().availableProcessors(), 30, TimeUnit.SECONDS, new ThreadPoolExecutor.CallerRunsPolicy(), "pool");
    syncExecutor.prestartAllCoreThreads();

    initAtStartup();
}
 
Example #17
Source File: SdlSession.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onProtocolSessionEndedNACKed(SessionType sessionType,
                                         byte sessionID, String correlationID) {
    this.sessionListener.onProtocolSessionEndedNACKed(sessionType, sessionID, correlationID);
    if(serviceListeners != null && serviceListeners.containsKey(sessionType)){
        CopyOnWriteArrayList<ISdlServiceListener> listeners = serviceListeners.get(sessionType);
        for(ISdlServiceListener listener:listeners){
            listener.onServiceError(this, sessionType, "End "+ sessionType.toString() +" Service NACK'ed");
        }
    }
}
 
Example #18
Source File: AnnotatedEventManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void updateMethods()
{
    methods.clear();
    for (Object listener : listeners)
    {
        boolean isClass = listener instanceof Class;
        Class<?> c = isClass ? (Class) listener : listener.getClass();
        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods)
        {
            if (!m.isAnnotationPresent(SubscribeEvent.class) || (isClass && !Modifier.isStatic(m.getModifiers())))
            {
                continue;
            }
            Class<?>[] pType  = m.getParameterTypes();
            if (pType.length == 1 && GenericEvent.class.isAssignableFrom(pType[0]))
            {
                Class<?> eventClass = pType[0];
                if (!methods.containsKey(eventClass))
                {
                    methods.put(eventClass, new ConcurrentHashMap<>());
                }

                if (!methods.get(eventClass).containsKey(listener))
                {
                    methods.get(eventClass).put(listener, new CopyOnWriteArrayList<>());
                }

                methods.get(eventClass).get(listener).add(m);
            }
        }
    }
}
 
Example #19
Source File: RoleMatcher.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private void add(ConcurrentMap<String, Collection<Class<?>>> map,
		String pattern, Class<?> role) {
	Collection<Class<?>> list = map.get(pattern);
	if (list == null) {
		list = new CopyOnWriteArrayList<Class<?>>();
		Collection<Class<?>> o = map.putIfAbsent(pattern, list);
		if (o != null) {
			list = o;
		}
	}
	if (!list.contains(role)) {
		list.add(role);
	}
}
 
Example #20
Source File: Solution.java    From JavaRushTasks with MIT License 5 votes vote down vote up
public static void main(String... args) {    //it's correct line
    CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.remove("B");
    List<String> collection = Arrays.asList(new String[]{"B", "C", "D", "B"});

    list.addAllAbsent(collection);

    for (String string : list) {
        System.out.println(string);
    }
}
 
Example #21
Source File: TcpBulkServer.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
public Acceptor(ServerSocketChannel serverSocketChannel, long limit) {
    this.serverSocketChannel = serverSocketChannel;
    this.clients = new CopyOnWriteArrayList<>();
    this.limit = limit;

    this.setName("Acceptor thread");
}
 
Example #22
Source File: CopyOnWriteArrayListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * removeAll removes all elements from the given collection
 */
public void testRemoveAll() {
    CopyOnWriteArrayList full = populatedArray(3);
    assertTrue(full.removeAll(Arrays.asList(one, two)));
    assertEquals(1, full.size());
    assertFalse(full.removeAll(Arrays.asList(one, two)));
    assertEquals(1, full.size());
}
 
Example #23
Source File: PipelineBuilderTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLimitInFlightProcessesWhenProcessingAsync() throws Exception {
  final List<String> output = new ArrayList<>();
  final List<CompletableFuture<String>> futures = new CopyOnWriteArrayList<>();
  final Pipeline<Integer> pipeline =
      PipelineBuilder.createPipelineFrom(
              "input", asList(1, 2, 3, 4, 5, 6, 7).iterator(), 10, NO_OP_LABELLED_2_COUNTER)
          .thenProcessAsync(
              "createFuture",
              value -> {
                final CompletableFuture<String> future = new CompletableFuture<>();
                futures.add(future);
                return future;
              },
              3)
          .andFinishWith("end", output::add);
  final CompletableFuture<?> result = pipeline.start(executorService);

  waitForSize(futures, 3);

  assertThat(result).isNotDone();

  // Completing one task should cause another to be started.
  futures.get(1).complete("2");
  waitForSize(futures, 4);

  futures.get(0).complete("1");
  futures.get(2).complete("3");
  futures.get(3).complete("4");

  waitForSize(futures, 7);
  futures.get(4).complete("5");
  futures.get(5).complete("6");
  futures.get(6).complete("7");

  result.get(10, SECONDS);
  assertThat(output).containsExactly("2", "1", "3", "4", "5", "6", "7");
}
 
Example #24
Source File: CopyOnWriteArrayListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testRemoveAll() {
    CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
    list.addAll(Arrays.asList("a", "b", "c", "d", "e"));

    list.removeAll(Arrays.asList());
    assertEquals(Arrays.asList("a", "b", "c", "d", "e"), list);

    list.removeAll(Arrays.asList("e"));
    assertEquals(Arrays.asList("a", "b", "c", "d"), list);

    list.removeAll(Arrays.asList("b", "c"));
    assertEquals(Arrays.asList("a", "d"), list);
}
 
Example #25
Source File: CopyOnWriteArrayListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testSubListAndSizePreservingStructuralChanges() {
    CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
    list.addAll(Arrays.asList("a", "b", "c", "d", "e"));
    List<String> bcd = list.subList(1, 4);
    list.clear();
    list.addAll(Arrays.asList("A", "B", "C", "D", "E"));
    try {
        bcd.get(1);
        fail();
    } catch (ConcurrentModificationException expected) {
    }
}
 
Example #26
Source File: SerializerPojo.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
public SerializerPojo(CopyOnWriteArrayList<ClassInfo> registered){
    if(registered == null)
        registered = new CopyOnWriteArrayList<ClassInfo>();
    this.registered = registered;
    oldSize = registered.size();
    for(int i=0;i<registered.size();i++)
    {
        ClassInfo ci = registered.get(i);
        Class clazz = classForName(ci.name);
        class2classId.put(clazz, i);
        classId2class.put(i, clazz);

    }
}
 
Example #27
Source File: LocalAdapter.java    From NClientV2 with Apache License 2.0 5 votes vote down vote up
public LocalAdapter(LocalActivity cont, ArrayList<LocalGallery> myDataset) {
    this.context=cont;
    dataset=new CopyOnWriteArrayList<>(myDataset);
    colCount=cont.getColCount();
    galleryDownloaders= DownloadQueue.getDownloaders();
    lastQuery=cont.getQuery();
    filter=new ArrayList<>(myDataset);
    filter.addAll(galleryDownloaders);

    DownloadQueue.addObserver(observer);
    sortElements();
}
 
Example #28
Source File: ConnectionPool.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public ConnectionPool(final Host host, final Client client, final Optional<Integer> overrideMinPoolSize,
                      final Optional<Integer> overrideMaxPoolSize) {
    this.host = host;
    this.client = client;
    this.cluster = client.cluster;
    poolLabel = String.format("Connection Pool {host=%s}", host);

    final Settings.ConnectionPoolSettings settings = settings();
    this.minPoolSize = overrideMinPoolSize.orElse(settings.minSize);
    this.maxPoolSize = overrideMaxPoolSize.orElse(settings.maxSize);
    this.minSimultaneousUsagePerConnection = settings.minSimultaneousUsagePerConnection;
    this.maxSimultaneousUsagePerConnection = settings.maxSimultaneousUsagePerConnection;
    this.minInProcess = settings.minInProcessPerConnection;

    this.connections = new CopyOnWriteArrayList<>();

    try {
        for (int i = 0; i < minPoolSize; i++)
            this.connections.add(new Connection(host.getHostUri(), this, settings.maxInProcessPerConnection));
    } catch (ConnectionException ce) {
        // ok if we don't get it initialized here - when a request is attempted in a connection from the
        // pool it will try to create new connections as needed.
        logger.debug("Could not initialize connections in pool for {} - pool size at {}", host, this.connections.size());
        considerHostUnavailable();
    }

    this.open = new AtomicInteger(connections.size());

    logger.info("Opening connection pool on {} with core size of {}", host, minPoolSize);
}
 
Example #29
Source File: PriceTest.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    // Check we don't have any prices
    List<Price> prices = RestAssured.get("/prices/all").as(new TypeRef<List<Price>>() {});
    Assertions.assertTrue(prices.isEmpty());

    // Stream the prices
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(PRICES_SSE_ENDPOINT);
    List<Double> received = new CopyOnWriteArrayList<>();
    SseEventSource source = SseEventSource.target(target).build();
    source.register(inboundSseEvent -> received.add(Double.valueOf(inboundSseEvent.readData())));
    source.open();

    // Send the prices
    Price p1 = new Price();
    p1.value = 1.0;
    Price p2 = new Price();
    p2.value = 4.0;
    Price p3 = new Price();
    p3.value = 2.0;
    RestAssured.given().header("Content-Type", "application/json").body(p1).post("/").then().statusCode(204);
    RestAssured.given().header("Content-Type", "application/json").body(p2).post("/").then().statusCode(204);
    RestAssured.given().header("Content-Type", "application/json").body(p3).post("/").then().statusCode(204);

    await().atMost(100000, MILLISECONDS).until(() -> received.size() == 3);
    source.close();

    Assertions.assertTrue(received.contains(p1.value));
    Assertions.assertTrue(received.contains(p2.value));
    Assertions.assertTrue(received.contains(p3.value));

    prices = RestAssured.get("/prices/all").as(new TypeRef<List<Price>>() {});
    Assertions.assertEquals(prices.size(), 3);
}
 
Example #30
Source File: CopyOnWriteArrayListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_sort() {
    List<Double> l = new CopyOnWriteArrayList<>(new Double[] {5.0, 2.0, -3.0});
    l.sort((v1, v2) -> v1.compareTo(v2));
    assertEquals(-3.0, l.get(0));
    assertEquals(2.0, l.get(1));
    assertEquals(5.0, l.get(2));
}