Java Code Examples for java.util.concurrent.CopyOnWriteArrayList

The following examples show how to use java.util.concurrent.CopyOnWriteArrayList. These examples are extracted from open source projects. 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
@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 Project: pnc   Source File: SingleProjectBuildTest.java    License: 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 3
Source Project: mars-sim   Source File: MissionManager.java    License: 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 Project: Exoplayer_VLC   Source File: DemoPlayer.java    License: 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 5
Source Project: FimiX8-RE   Source File: BaseRecycleAdapter.java    License: 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 6
Source Project: vertx-stomp   Source File: EventBusBridgeTest.java    License: 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 7
Source Project: tilesfx   Source File: PixelMatrix.java    License: 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 8
@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 9
/**
 * 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 10
Source Project: cloudhopper-commons   Source File: Window.java    License: 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 11
Source Project: smallrye-mutiny   Source File: MultiSubscribeTest.java    License: 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 12
Source Project: packagedrone   Source File: ArtifactInformation.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public Manipulator ( final ArtifactInformation original )
{
    this.original = original;

    /* although this is a modifiable version, we _must not_ change the list content!
     * Since it is the base of an immutable object. But if we have access to the original
     * CopyOnWriteArraySet, the copy constructor can make use of the copy on write variant */
    this.childIds = new CopyOnWriteArraySet<> ( original.modChildIds );

    this.providedMetaData = new HashMap<> ( original.providedMetaData );
    this.extractedMetaData = new HashMap<> ( original.extractedMetaData );
    this.validationMessages = new CopyOnWriteArrayList<> ( original.modMessages );
}
 
Example 13
Source Project: dubbox   Source File: AbstractRegistryService.java    License: 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 Project: anno4j   Source File: RoleMatcher.java    License: 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 15
Source Project: tilesfx   Source File: TreeNode.java    License: Apache License 2.0 5 votes vote down vote up
public TreeNode(final T ITEM, final TreeNode<T> PARENT) {
    item      = ITEM;
    parent    = PARENT;
    depth     = -1;
    children  = FXCollections.observableArrayList();
    listeners = new CopyOnWriteArrayList<>();
    childNodeListener = c -> {
        TreeNode<T> treeRoot = getTreeRoot();
        while (c.next()) {
            if (c.wasAdded()) {
                c.getAddedSubList().forEach(addedNode -> {
                    addedNode.getNodes().forEach(node -> {
                        if (null != treeRoot) { treeRoot.fireTreeNodeEvent(CHILD_ADDED); }
                    });
                });
            } else if (c.wasRemoved()) {
                c.getRemoved().forEach(removedNode -> {
                    removedNode.getNodes().forEach(node -> {
                        if (null != treeRoot) { treeRoot.fireTreeNodeEvent(CHILD_REMOVED); }
                    });
                });
            }
        }
        if (null != treeRoot) { treeRoot.fireTreeNodeEvent(CHILDREN_CHANGED); }
    };

    init();
}
 
Example 16
Source Project: mobius   Source File: ExecutorServiceWorkRunnerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotReturnFromDisposeUntilFinishedRunning() throws Exception {
  final Semaphore blockBackground = new Semaphore(0);
  final Semaphore blockUnderTest = new Semaphore(0);
  final Semaphore blockMainThread = new Semaphore(0);

  final List<Integer> output = new CopyOnWriteArrayList<>();

  underTest.post(
      new Runnable() {
        @Override
        public void run() {
          output.add(1);
          blockBackground.release();
          blockUnderTest.acquireUninterruptibly();
          output.add(3);
          blockMainThread.release();
        }
      });

  ExecutorServiceWorkRunner backgroundWorkRunner =
      new ExecutorServiceWorkRunner(Executors.newSingleThreadExecutor());
  backgroundWorkRunner.post(
      new Runnable() {
        @Override
        public void run() {
          blockBackground.acquireUninterruptibly();
          output.add(2);
          blockUnderTest.release();
        }
      });

  blockMainThread.acquire();
  underTest.dispose();
  output.add(4);

  Thread.sleep(40); // wait a bit and make sure nothing else is added after the 4

  assertThat(output, equalTo(asList(1, 2, 3, 4)));
}
 
Example 17
Source Project: BiglyBT   Source File: ImageLoader.java    License: GNU General Public License v2.0 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 18
Source Project: sailfish-core   Source File: SFWebHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void register(IUpdateRequestListener listener, IUpdateRetriever retriever) throws Exception{
	
	List<IUpdateRequestListener> retriverLsteners = subscribers.get(retriever);
	
	if (retriverLsteners == null) {
		retriverLsteners = new CopyOnWriteArrayList<IUpdateRequestListener>();
		subscribers.put(retriever, retriverLsteners);
	}
	
	for (IUpdateRequestListener subscriber : retriverLsteners) {
		
		try {
			logger.debug("Handler {} Channel {} unregister subscriber {}", new Object[] {id, channel, subscriber});
			retriever.unregisterUpdateRequest(subscriber);
			subscriber.destroy();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		
	}
	
	retriverLsteners.clear();
		
	logger.debug("Handler {} Channel {} register subscriber {}", new Object[] {id, channel, listener});
	retriever.registerUpdateRequest(listener);		
	
	retriever.synchronizeUpdateRequest(listener);
	retriverLsteners.add(listener);
	
}
 
Example 19
Source Project: astor   Source File: EventListenerSupport.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deserialize.
 * @param objectInputStream
 * @throws IOException
 * @throws ClassNotFoundException
 */
private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
    @SuppressWarnings("unchecked")
    L[] listeners = (L[]) objectInputStream.readObject();

    this.listeners = new CopyOnWriteArrayList<L>(listeners);

    @SuppressWarnings("unchecked")
    Class<L> listenerInterface = (Class<L>) listeners.getClass().getComponentType();

    initializeTransientFields(listenerInterface, Thread.currentThread().getContextClassLoader());
}
 
Example 20
Source Project: j2objc   Source File: CopyOnWriteArrayListTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * adding at an index places it in the indicated index
 */
public void testAddIndex() {
    CopyOnWriteArrayList full = populatedArray(3);
    full.add(0, m1);
    assertEquals(4, full.size());
    assertEquals(m1, full.get(0));
    assertEquals(zero, full.get(1));

    full.add(2, m2);
    assertEquals(5, full.size());
    assertEquals(m2, full.get(2));
    assertEquals(two, full.get(4));
}
 
Example 21
Source Project: ameba   Source File: BasicEventBus.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <E extends Event> void publish(E event) {
    CopyOnWriteArrayList ls = listeners.get(event.getClass());
    if (ls != null) {
        ls.forEach(listener -> {
            try {
                ((Listener<E>) listener).onReceive(event);
            } catch (Exception e) {
                logger.error(event.getClass().getName() + " event handler has a error", e);
            }
        });
    }
}
 
Example 22
public ZeroconfDiscoveryProvider(Context context) {
    foundServices = new ConcurrentHashMap<String, ServiceDescription>(8, 0.75f, 2);

    serviceListeners = new CopyOnWriteArrayList<DiscoveryProviderListener>();
    serviceFilters = new CopyOnWriteArrayList<DiscoveryFilter>();

    try {
        srcAddress = Util.getIpAddress(context);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}
 
Example 23
Source Project: besu   Source File: PipelineBuilderTest.java    License: 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
@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 25
Source Project: EVCache   Source File: EVCacheClientPoolManager.java    License: 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 26
Source Project: FimiX8-RE   Source File: DownFwService.java    License: 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 27
Source Project: phoebus   Source File: ArrayWidgetProperty.java    License: 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 28
Source Project: JavaRushTasks   Source File: Solution.java    License: 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 29
Source Project: netcrusher-java   Source File: TcpBulkServer.java    License: 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 30
Source Project: j2objc   Source File: CopyOnWriteArrayListTest.java    License: 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());
}