Example usage for java.util Collections synchronizedList

List of usage examples for java.util Collections synchronizedList

Introduction

In this page you can find the example usage for java.util Collections synchronizedList.

Prototype

public static <T> List<T> synchronizedList(List<T> list) 

Source Link

Document

Returns a synchronized (thread-safe) list backed by the specified list.

Usage

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

@Before
@SuppressWarnings("unchecked")
public void setup() {
    responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() {
        @Override/*from   w  ww. j ava  2 s  .co  m*/
        public ResponseEvent newInstance() {
            return new ResponseEvent();
        }
    }, 1024, Executors.newCachedThreadPool());

    firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>());
    latch = new CountDownLatch(1);
    responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() {
        @Override
        public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
            firedEvents.add(event.getMessage());
            latch.countDown();
        }
    });
    responseRingBuffer = responseBuffer.start();

    CoreEnvironment environment = mock(CoreEnvironment.class);
    when(environment.scheduler()).thenReturn(Schedulers.computation());
    when(environment.maxRequestLifetime()).thenReturn(10000L); // 10 seconds
    when(environment.autoreleaseAfter()).thenReturn(2000L);
    endpoint = mock(AbstractEndpoint.class);
    when(endpoint.environment()).thenReturn(environment);
    when(environment.userAgent()).thenReturn("Couchbase Client Mock");

    queue = new ArrayDeque<ViewRequest>();
    handler = new ViewHandler(endpoint, responseRingBuffer, queue, false);
    channel = new EmbeddedChannel(handler);
}

From source file:org.piwik.sdk.TestDispatcher.java

@Test
public void testForceDispatch() throws Exception {
    final Tracker tracker = createTracker();
    tracker.setDispatchInterval(-1);/* w w w .j a v  a2 s . c o  m*/

    final int threadCount = 10;
    final int queryCount = 10;
    final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>());
    launchTestThreads(tracker, threadCount, queryCount, createdEvents);
    Thread.sleep(500);
    assertEquals(threadCount * queryCount, createdEvents.size());
    assertEquals(0, tracker.getDispatcher().getDryRunOutput().size());
    assertTrue(tracker.dispatch());

    checkForMIAs(threadCount * queryCount, createdEvents, tracker.getDispatcher().getDryRunOutput());
}

From source file:io.udvi.amqp.mq.transport.session.CAMQPSessionManager.java

protected static void sessionCreated(CAMQPConnectionKey amqpRemoteConnectionKey, int sessionChannelId,
        CAMQPSession session) {/*from www  .  j a v  a  2  s  .c om*/
    List<CAMQPSession> sessions = _sessionManager.mappedSessions.get(amqpRemoteConnectionKey);
    List<CAMQPSession> sessionsPrevValue = null;
    if (sessions == null) {
        sessions = Collections.synchronizedList(new ArrayList<CAMQPSession>());
        sessionsPrevValue = _sessionManager.mappedSessions.putIfAbsent(amqpRemoteConnectionKey, sessions);
    }
    if (sessionsPrevValue == null) {
        sessions.add(session);
    } else {
        sessionsPrevValue.add(session);
    }
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

private NicosClient() {
    // private constructor -> Singleton
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
    callbackHandlers = Collections.synchronizedList(new CopyOnWriteArrayList<NicosCallbackHandler>());
    socket = null;// w w w .  j av a  2  s .  c  o  m
    eventSocket = null;
    connected = false;
    disconnecting = false;
    last_reqno = null;
    viewonly = true;
    user_level = -1;
    MessageDigest md5 = getMD5();
    if (md5 != null) {
        client_id = getMD5().digest(getUniqueID().getBytes());
    }

    // Add debug printer for signals.
    // callbackHandlers.add(new SignalDebugPrinter());
    Unpickler.registerConstructor("nicos.utils", "readonlylist", new ReadOnlyListConstructor());
    Unpickler.registerConstructor("nicos.utils", "readonlydict", new ReadOnlyDictConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "ConfigurationError",
            new ConfigurationErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "CommunicationError",
            new CommunicationErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "NicosError", new NicosErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "InvalidValueError", new InvalidValueErrorConstructor());
    Unpickler.registerConstructor("__builtin__", "str", new strErrorConstructor());
}

From source file:com.chessix.vas.web.AccountController.java

@RequestMapping(value = "/{clasId}/range/from/{start}/count/{count}", method = RequestMethod.POST)
public DeferredResult<Object> createAccounts(@PathVariable final String clasId,
        @PathVariable final String start, @PathVariable final String count) {
    log.info("createAccounts({},{},{})", clasId, start, count);
    final ActorRef clas = clasService.getClas(clasId);
    final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
    final int countValue = Integer.parseInt(count);

    if (countValue > MAX_ACCOUNTS_IN_BATCH) {
        deferredResult//from   ww  w  . j a v a 2  s .  com
                .setErrorResult(String.format("count %s is to large (> %d)", count, MAX_ACCOUNTS_IN_BATCH));
        return deferredResult;
    }

    if (clas != null) {
        final List<AccountCreated> results = Collections.synchronizedList(new LinkedList<AccountCreated>());
        final AtomicInteger resultsCounter = new AtomicInteger(0);

        for (int i = Integer.parseInt(start); i < Integer.parseInt(start) + countValue; i++) {
            final String accountId = Integer.toString(i);
            log.debug("createAccounts() : create {}", accountId);
            final Future<Object> future = Patterns.ask(clas,
                    new CreateAccount.RequestBuilder(clasId).accountId(accountId).build(),
                    timeout * countValue);
            future.onSuccess(new OnSuccess<Object>() {
                @Override
                public void onSuccess(final Object result) {
                    log.info("createAccount({}) : result: {}", clasId, result);
                    final CreateAccount.Response response = (CreateAccount.Response) result;
                    results.add(new AccountCreated(clasId, response.getAccountId(), true,
                            String.format("Account %s created", accountId)));

                    // check if all values are received
                    if (resultsCounter.incrementAndGet() >= countValue) {
                        deferredResult.setResult(results);
                    }

                }
            }, system.dispatcher());
            future.onFailure(new OnFailure() {
                @Override
                public void onFailure(final Throwable arg) throws Throwable {
                    log.error("onFailure", arg);
                    deferredResult
                            .setErrorResult(new AccountCreated(clasId, null, false, arg.getLocalizedMessage()));
                }
            }, system.dispatcher());
        }
    } else {
        deferredResult.setErrorResult(new AccountCreated(clasId, null, false, "CLAS does not exist"));
    }
    return deferredResult;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.DataImporter.java

protected synchronized EnumMap<ReportColumns, Object> trackActivity(String item, String action, Integer count) {
    if (reportRows == null) {
        reportRows = Collections.synchronizedList(new ArrayList<>());
    }/*from  w  w w. ja v  a 2  s . com*/
    EnumMap<ReportColumns, Object> reportRow = new EnumMap<>(ReportColumns.class);
    reportRow.put(ReportColumns.item, item);
    reportRow.put(ReportColumns.action, action);
    reportRow.put(ReportColumns.count, count);
    reportRows.add(reportRow);
    return reportRow;
}

From source file:annis.gui.resultview.ResultViewPanel.java

public ResultViewPanel(SearchUI ui, PluginSystem ps, InstanceConfig instanceConfig,
        PagedResultQuery initialQuery) {
    this.sui = ui;
    this.tokenAnnoVisible = new TreeMap<>();
    this.ps = ps;
    this.controller = ui.getQueryController();
    this.selectedSegmentationLayer = ui.getQueryState().getBaseText().getValue();
    this.initialQuery = initialQuery;

    cacheResolver = Collections/* www. j  a  va  2  s .c o  m*/
            .synchronizedMap(new HashMap<HashSet<SingleResolverRequest>, List<ResolverEntry>>());

    resultPanelList = Collections.synchronizedList(new LinkedList<SingleResultPanel>());

    resultLayout = new CssLayout();
    resultLayout.addStyleName("result-view-css");
    Panel resultPanel = new Panel(resultLayout);
    resultPanel.setSizeFull();
    resultPanel.addStyleName(ChameleonTheme.PANEL_BORDERLESS);
    resultPanel.addStyleName("result-view-panel");

    this.instanceConfig = instanceConfig;

    setSizeFull();
    setMargin(false);

    MenuBar mbResult = new MenuBar();
    mbResult.setWidth("100%");
    mbResult.addStyleName("menu-hover");
    addComponent(mbResult);

    miSegmentation = mbResult.addItem("Base text", null);
    miTokAnnos = mbResult.addItem("Token Annotations", null);

    addComponent(resultPanel);

    setExpandRatio(mbResult, 0.0f);
    setExpandRatio(resultPanel, 1.0f);

    paging = new PagingComponent();

    addComponent(paging, 1);

    setComponentAlignment(paging, Alignment.TOP_CENTER);
    setExpandRatio(paging, 0.0f);
}

From source file:org.rifidi.edge.core.sensors.sessions.AbstractSensorSession.java

/**
 * Constructor//from w ww .  j  a va2  s .co m
 * 
 * @param sensor
 * @param ID
 *            ID of this SensorSession
 * @param destination
 *            The JMS Queue to add Tag Data to
 * @param template
 *            The Template used to send Tag data to the internal queue
 * @param commandConfigurations
 *            Provided by spring
 */
public AbstractSensorSession(AbstractSensor<?> sensor, String ID,
        Set<AbstractCommandConfiguration<?>> commandConfigurations) {
    super(ID, sensor);
    this.commandConfigurations = commandConfigurations;
    status = SessionStatus.CREATED;
    this.queuedCommands = new ConcurrentLinkedQueue<CommandExecutor>();
    this.runningCommands = Collections.synchronizedList(new LinkedList<CommandExecutor>());
}

From source file:esg.node.core.AbstractDataNodeComponent.java

public AbstractDataNodeComponent(String name) {
    this.myName = name;
    this.esgListeners = Collections.synchronizedList(new ArrayList<ESGListener>());
    this.esgQueueListenersMap = Collections.synchronizedMap(new HashMap<String, ESGQueueListener>());
    this.eventQueue = new ESGQueue(this);
}

From source file:org.springframework.integration.jms.SubscribableJmsChannelTests.java

@Test
public void topicReference() throws Exception {
    final CountDownLatch latch = new CountDownLatch(4);
    final List<Message<?>> receivedList1 = Collections.synchronizedList(new ArrayList<Message<?>>());
    MessageHandler handler1 = new MessageHandler() {
        public void handleMessage(Message<?> message) {
            receivedList1.add(message);/* w  w  w . j  av  a2  s  .  c  o  m*/
            latch.countDown();
        }
    };
    final List<Message<?>> receivedList2 = Collections.synchronizedList(new ArrayList<Message<?>>());
    MessageHandler handler2 = new MessageHandler() {
        public void handleMessage(Message<?> message) {
            receivedList2.add(message);
            latch.countDown();
        }
    };
    JmsChannelFactoryBean factoryBean = new JmsChannelFactoryBean(true);
    factoryBean.setConnectionFactory(this.connectionFactory);
    factoryBean.setDestination(this.topic);
    factoryBean.afterPropertiesSet();
    SubscribableJmsChannel channel = (SubscribableJmsChannel) factoryBean.getObject();
    channel.afterPropertiesSet();
    channel.subscribe(handler1);
    channel.subscribe(handler2);
    channel.start();
    if (!waitUntilRegisteredWithDestination(channel, 10000)) {
        fail("Listener failed to subscribe to topic");
    }
    channel.send(new GenericMessage<String>("foo"));
    channel.send(new GenericMessage<String>("bar"));
    latch.await(TIMEOUT, TimeUnit.MILLISECONDS);
    assertEquals(2, receivedList1.size());
    assertEquals("foo", receivedList1.get(0).getPayload());
    assertEquals("bar", receivedList1.get(1).getPayload());
    assertEquals(2, receivedList2.size());
    assertEquals("foo", receivedList2.get(0).getPayload());
    assertEquals("bar", receivedList2.get(1).getPayload());
    channel.stop();
}