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:org.apache.falcon.service.BacklogMetricEmitterService.java

private void initInstances() throws FalconException {
    LOG.info("Initializing backlog instances from state store");
    Map<Entity, List<MetricInfo>> backlogInstances = backlogMetricStore.getAllInstances();
    if (backlogInstances != null && !backlogInstances.isEmpty()) {
        for (Map.Entry<Entity, List<MetricInfo>> entry : backlogInstances.entrySet()) {
            List<MetricInfo> metricsInDB = entry.getValue();
            List<MetricInfo> metricInfoList = Collections.synchronizedList(metricsInDB);
            entityBacklogs.put(entry.getKey(), metricInfoList);
            LOG.debug("Initializing backlog for entity " + entry.getKey().getName());
        }//from   w  ww  .ja  v a2  s . c om
    }
}

From source file:org.apache.flume.channel.file.TestFileChannel.java

@Test
public void testThreaded() throws IOException, InterruptedException {
    int numThreads = 10;
    final CountDownLatch producerStopLatch = new CountDownLatch(numThreads);
    final CountDownLatch consumerStopLatch = new CountDownLatch(numThreads);
    final List<Exception> errors = Collections.synchronizedList(new ArrayList<Exception>());
    final List<String> expected = Collections.synchronizedList(new ArrayList<String>());
    final List<String> actual = Collections.synchronizedList(new ArrayList<String>());
    for (int i = 0; i < numThreads; i++) {
        final int id = i;
        Thread t = new Thread() {
            @Override/*from  ww  w .  j a v a2s. c o m*/
            public void run() {
                try {
                    if (id % 2 == 0) {
                        expected.addAll(putEvents(channel, Integer.toString(id), 1, 5));
                    } else {
                        expected.addAll(putEvents(channel, Integer.toString(id), 5, 5));
                    }
                    LOG.info("Completed some puts " + expected.size());
                } catch (Exception e) {
                    LOG.error("Error doing puts", e);
                    errors.add(e);
                } finally {
                    producerStopLatch.countDown();
                }
            }
        };
        t.setDaemon(true);
        t.start();
    }
    for (int i = 0; i < numThreads; i++) {
        final int id = i;
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    while (!producerStopLatch.await(1, TimeUnit.SECONDS) || expected.size() > actual.size()) {
                        if (id % 2 == 0) {
                            actual.addAll(takeEvents(channel, 1, Integer.MAX_VALUE));
                        } else {
                            actual.addAll(takeEvents(channel, 5, Integer.MAX_VALUE));
                        }
                    }
                    if (actual.isEmpty()) {
                        LOG.error("Found nothing!");
                    } else {
                        LOG.info("Completed some takes " + actual.size());
                    }
                } catch (Exception e) {
                    LOG.error("Error doing takes", e);
                    errors.add(e);
                } finally {
                    consumerStopLatch.countDown();
                }
            }
        };
        t.setDaemon(true);
        t.start();
    }
    Assert.assertTrue("Timed out waiting for producers", producerStopLatch.await(30, TimeUnit.SECONDS));
    Assert.assertTrue("Timed out waiting for consumer", consumerStopLatch.await(30, TimeUnit.SECONDS));
    Assert.assertEquals(Collections.EMPTY_LIST, errors);
    Collections.sort(expected);
    Collections.sort(actual);
    Assert.assertEquals(expected, actual);
}

From source file:org.goko.tools.viewer.jogl.service.JoglSceneManager.java

/**
 * @return the renderers//from  w  w w.j  av a  2 s  . c  o  m
 */
protected List<ICoreJoglRenderer> getRenderers() {
    if (renderers == null) {
        renderers = Collections.synchronizedList(new ArrayList<ICoreJoglRenderer>());
    }
    return renderers;
}

From source file:org.apache.flume.channel.kafka.TestKafkaChannel.java

private List<Event> pullEvents(final KafkaChannel channel, ExecutorCompletionService<Void> submitterSvc,
        final int total, final boolean testRollbacks, final boolean retryAfterRollback) {
    final List<Event> eventsPulled = Collections.synchronizedList(new ArrayList<Event>(50));
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicInteger rolledBackCount = new AtomicInteger(0);
    final AtomicBoolean startedGettingEvents = new AtomicBoolean(false);
    final AtomicBoolean rolledBack = new AtomicBoolean(false);
    for (int k = 0; k < 5; k++) {
        final int index = k;
        submitterSvc.submit(new Callable<Void>() {
            @Override//w w  w . j  a va  2  s  . c  om
            public Void call() throws Exception {
                Transaction tx = null;
                final List<Event> eventsLocal = Lists.newLinkedList();
                int takenByThisThread = 0;
                channel.registerThread();
                Thread.sleep(1000);
                barrier.await();
                while (counter.get() < (total - rolledBackCount.get())) {
                    if (tx == null) {
                        tx = channel.getTransaction();
                        tx.begin();
                    }
                    try {
                        Event e = channel.take();
                        if (e != null) {
                            startedGettingEvents.set(true);
                            eventsLocal.add(e);
                        } else {
                            if (testRollbacks && index == 4 && (!rolledBack.get())
                                    && startedGettingEvents.get()) {
                                tx.rollback();
                                tx.close();
                                tx = null;
                                rolledBack.set(true);
                                final int eventsLocalSize = eventsLocal.size();
                                eventsLocal.clear();
                                if (!retryAfterRollback) {
                                    rolledBackCount.set(eventsLocalSize);
                                    return null;
                                }
                            } else {
                                tx.commit();
                                tx.close();
                                tx = null;
                                eventsPulled.addAll(eventsLocal);
                                counter.getAndAdd(eventsLocal.size());
                                eventsLocal.clear();
                            }
                        }
                    } catch (Exception ex) {
                        eventsLocal.clear();
                        if (tx != null) {
                            tx.rollback();
                            tx.close();
                        }
                        tx = null;
                        ex.printStackTrace();
                    }
                }
                // Close txn.
                return null;
            }
        });
    }
    return eventsPulled;
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

protected SyncLanClientQueryResult findSyncLanClient(SyncFile syncFile) throws Exception {

    SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncFile.getSyncAccountId());

    List<String> syncLanClientUuids = SyncLanEndpointService
            .findSyncLanClientUuids(syncAccount.getLanServerUuid(), syncFile.getRepositoryId());

    if (syncLanClientUuids.isEmpty()) {
        return null;
    }// w w w  .ja v  a  2  s. c  o  m

    final List<Callable<SyncLanClientQueryResult>> syncLanClientQueryResultCallables = Collections
            .synchronizedList(new ArrayList<Callable<SyncLanClientQueryResult>>(syncLanClientUuids.size()));

    for (String syncLanClientUuid : syncLanClientUuids) {
        SyncLanClient syncLanClient = SyncLanClientService.fetchSyncLanClient(syncLanClientUuid);

        syncLanClientQueryResultCallables.add(createSyncLanClientQueryResultCallable(syncLanClient, syncFile));
    }

    int queryPoolSize = Math.min(syncLanClientUuids.size(), PropsValues.SYNC_LAN_SESSION_QUERY_POOL_MAX_SIZE);

    List<Future<SyncLanClientQueryResult>> pendingSyncLanClientQueryResults = new ArrayList<>(queryPoolSize);

    ExecutorCompletionService<SyncLanClientQueryResult> executorCompletionService = new ExecutorCompletionService<>(
            getExecutorService());

    for (int i = 0; i < queryPoolSize; i++) {
        Callable<SyncLanClientQueryResult> callable = new Callable<SyncLanClientQueryResult>() {

            @Override
            public synchronized SyncLanClientQueryResult call() throws Exception {

                if (syncLanClientQueryResultCallables.isEmpty()) {
                    return null;
                }

                Callable<SyncLanClientQueryResult> syncLanClientQueryResultCallable = syncLanClientQueryResultCallables
                        .remove(0);

                try {
                    return syncLanClientQueryResultCallable.call();
                } catch (Exception e) {
                    return call();
                }
            }

        };

        pendingSyncLanClientQueryResults.add(executorCompletionService.submit(callable));
    }

    List<Future<SyncLanClientQueryResult>> completedSyncLanClientQueryResult = new ArrayList<>(queryPoolSize);

    long timeout = PropsValues.SYNC_LAN_SESSION_QUERY_TOTAL_TIMEOUT;

    long endTime = System.currentTimeMillis() + timeout;

    for (int i = 0; i < queryPoolSize; i++) {
        Future<SyncLanClientQueryResult> future = executorCompletionService.poll(timeout,
                TimeUnit.MILLISECONDS);

        if (future == null) {
            for (Future<SyncLanClientQueryResult> pendingSyncLanClientQueryResult : pendingSyncLanClientQueryResults) {

                if (!pendingSyncLanClientQueryResult.isDone()) {
                    pendingSyncLanClientQueryResult.cancel(true);
                }
            }

            break;
        }

        completedSyncLanClientQueryResult.add(future);

        timeout = endTime - System.currentTimeMillis();
    }

    SyncLanClientQueryResult candidateSyncLanClientQueryResult = null;
    int candidateDownloadRatePerConnection = 0;

    for (Future<SyncLanClientQueryResult> completedFuture : completedSyncLanClientQueryResult) {

        SyncLanClientQueryResult syncLanClientQueryResult = null;

        try {
            syncLanClientQueryResult = completedFuture.get();
        } catch (Exception e) {
            continue;
        }

        if (syncLanClientQueryResult == null) {
            continue;
        }

        if (syncLanClientQueryResult.getConnectionsCount() >= syncLanClientQueryResult.getMaxConnections()) {

            if (candidateSyncLanClientQueryResult == null) {
                candidateSyncLanClientQueryResult = syncLanClientQueryResult;
            }

            continue;
        }

        if (syncLanClientQueryResult.getConnectionsCount() == 0) {
            return syncLanClientQueryResult;
        }

        int downloadRatePerConnection = syncLanClientQueryResult.getDownloadRate()
                / (syncLanClientQueryResult.getConnectionsCount() + 1);

        if (downloadRatePerConnection >= candidateDownloadRatePerConnection) {

            candidateDownloadRatePerConnection = downloadRatePerConnection;
            candidateSyncLanClientQueryResult = syncLanClientQueryResult;
        }
    }

    return candidateSyncLanClientQueryResult;
}

From source file:org.codice.ddf.ui.searchui.query.controller.SearchController.java

/**
 * Execute all of the queries contained within the SearchRequest
 *
 * @param request// w w  w  .  j  ava2 s. c o  m
 *            - SearchRequest containing a query for 1 or more sources
 * @param session
 *            - Cometd ServerSession
 */
public void executeQuery(final SearchRequest request, final ServerSession session, final Subject subject) {

    final SearchController controller = this;

    if (!cacheDisabled) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                // check if there are any currently cached results
                // search cache for all sources
                QueryResponse response = executeQuery(null, request, subject, new HashMap<>(CACHE_PROPERTIES));

                try {
                    Search search = addQueryResponseToSearch(request, response);
                    pushResults(request.getId(), controller.transform(search, request), session);
                } catch (InterruptedException e) {
                    LOGGER.error("Failed adding cached search results.", e);
                } catch (CatalogTransformerException e) {
                    LOGGER.error("Failed to transform cached search results.", e);
                }
            }
        });

        for (final String sourceId : request.getSourceIds()) {
            LOGGER.debug("Executing async query on: {}", sourceId);
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    // update index from federated sources
                    QueryResponse indexResponse = executeQuery(sourceId, request, subject,
                            new HashMap<>(INDEX_PROPERTIES));

                    // query updated cache
                    QueryResponse cachedResponse = executeQuery(null, request, subject,
                            new HashMap<>(CACHE_PROPERTIES));

                    try {
                        Search search = addQueryResponseToSearch(request, cachedResponse);
                        search.updateStatus(sourceId, indexResponse);
                        pushResults(request.getId(), controller.transform(search, request), session);
                        if (search.isFinished()) {
                            searchMap.remove(request.getId());
                        }
                    } catch (InterruptedException e) {
                        LOGGER.error("Failed adding federated search results.", e);
                    } catch (CatalogTransformerException e) {
                        LOGGER.error("Failed to transform federated search results.", e);
                    }
                }
            });
        }
    } else {
        final Comparator<Result> sortComparator = getResultComparator(request.getQuery());
        final int maxResults = request.getQuery().getPageSize() > 0 ? request.getQuery().getPageSize()
                : Integer.MAX_VALUE;
        final List<Result> results = Collections.synchronizedList(new ArrayList<Result>());

        for (final String sourceId : request.getSourceIds()) {
            LOGGER.debug("Executing async query without cache on: {}", sourceId);
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    QueryResponse sourceResponse = executeQuery(sourceId, request, subject,
                            new HashMap<String, Serializable>());

                    results.addAll(sourceResponse.getResults());

                    List<Result> sortedResults = Ordering.from(sortComparator).immutableSortedCopy(results);

                    sourceResponse.getResults().clear();
                    sourceResponse.getResults()
                            .addAll(sortedResults.size() > maxResults ? sortedResults.subList(0, maxResults)
                                    : sortedResults);

                    try {
                        Search search = addQueryResponseToSearch(request, sourceResponse);
                        search.updateStatus(sourceId, sourceResponse);
                        pushResults(request.getId(), controller.transform(search, request), session);
                        if (search.isFinished()) {
                            searchMap.remove(request.getId());
                        }
                    } catch (InterruptedException e) {
                        LOGGER.error("Failed adding federated search results.", e);
                    } catch (CatalogTransformerException e) {
                        LOGGER.error("Failed to transform federated search results.", e);
                    }
                }
            });
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.WebClientWaitForBackgroundJobsTest.java

/**
 * When waitForBackgroundJavaScriptStartingBefore is called and a new job is scheduled after the one that
 * is first found as the last one within the delay (a job starts a new one or simply a setInterval),
 * a few retries should be done to see if new jobs exists.
 * @throws Exception if the test fails/*  w  ww  .  j ava  2s.  co m*/
 */
@Test
@Tries(3)
public void waitWithsubWindows() throws Exception {
    final String html = "<html>\n" + "<head>\n" + "  <title>test</title>\n" + "</head>\n" + "<body>\n"
            + "<iframe src='nested.html'></iframe>\n" + "</body>\n" + "</html>";
    final String nested = "<html>\n" + "<head>\n" + "  <title>nested</title>\n" + "  <script>\n"
            + "    function test() {\n" + "      setTimeout(doWork1, 200);\n" + "    }\n"
            + "    function doWork1() {\n" + "      alert('work1');\n" + "    }\n" + "  </script>\n"
            + "</head>\n" + "<body onload='test()'>\n" + "</body>\n" + "</html>";

    final WebClient client = getWebClient();
    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, html);
    webConnection.setDefaultResponse(nested);

    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);

    final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager();
    assertNotNull(jobManager);
    assertEquals(0, jobManager.getJobCount());

    startTimedTest();
    assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(20_000));
    assertMaxTestRunTime(300);
    assertEquals(0, jobManager.getJobCount());

    final String[] expectedAlerts = { "work1" };
    assertEquals(expectedAlerts, collectedAlerts);
}

From source file:org.alfresco.dropbox.service.polling.DropboxPollerImpl.java

private List<NodeRef> getDocuments(final NodeRef nodeRef) {
    List<NodeRef> documents = Collections.synchronizedList(new ArrayList<NodeRef>());

    ResultSet resultSet = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<ResultSet>() {

        public ResultSet doWork() throws Exception {
            ResultSet resultSet = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,
                    SearchService.LANGUAGE_CMIS_ALFRESCO,
                    CMIS_DROPBOX_DOCUMENTS_QUERY + " WHERE IN_TREE(D, '" + nodeRef + "')");

            return resultSet;
        }//  w w  w.  j a v  a 2  s  . c  om

    }, AuthenticationUtil.getAdminUserName());

    try {
        // TODO Hopefully one day this will go away --Open Bug??
        if (resultSet.length() > 0) {
            if (!resultSet.getNodeRef(0).equals(MISSING_NODE)) {
                documents = resultSet.getNodeRefs();
                log.debug("Documents synced to Dropbox: " + documents);
            }
        }
    } finally {
        resultSet.close();
    }

    return documents;
}

From source file:com.gemini.provision.security.openstack.SecurityProviderOpenStackImpl.java

@Override
public List<GeminiSecurityGroupRule> listSecurityGroupRules(GeminiTenant tenant, GeminiEnvironment env,
        GeminiSecurityGroup securityGroup) {
    List<GeminiSecurityGroupRule> listSecGrpRules = Collections.synchronizedList(new ArrayList());

    //authenticate the session with the OpenStack installation
    OSClient os = OSFactory.builder().endpoint(env.getEndPoint())
            .credentials(env.getAdminUserName(), env.getAdminPassword()).tenantName(tenant.getName())
            .authenticate();//from www.  j a  v a  2s.c om
    if (os == null) {
        Logger.error("Failed to authenticate Tenant: {}",
                ToStringBuilder.reflectionToString(tenant, ToStringStyle.MULTI_LINE_STYLE));
        return null;
    }

    List<? extends SecurityGroupRule> osSecGrpRules = null;
    try {
        osSecGrpRules = os.networking().securityrule().list();
    } catch (NullPointerException | ClientResponseException ex) {
        Logger.error("Failed to get rules for tenant: {} env: {} and security Group {}", tenant.getName(),
                env.getName(), securityGroup.getName());
        return null;
    }

    osSecGrpRules.stream().filter(osSecGrpRule -> osSecGrpRule != null).forEach(osSecGrpRule -> {
        //find the rule in the security group object and add it to list
        GeminiSecurityGroupRule gemSecGrpRule = null;
        try {
            gemSecGrpRule = securityGroup.getSecurityRules().stream()
                    .filter(sr -> sr.getCloudID().equals(osSecGrpRule.getId())) //check cloud id too to ensure the mapping on Gemini is complete
                    .findFirst().get();
        } catch (NoSuchElementException ex) {
            //not an error or even log worthy ... just signifies that the rule
            //on Gemini Side needs to be created
        }
        if (gemSecGrpRule == null) {
            //the rule has not been mapped on the Gemini side, so create it
            gemSecGrpRule = new GeminiSecurityGroupRule();
            gemSecGrpRule.setCloudID(osSecGrpRule.getId());
            gemSecGrpRule.setProvisioned(true);
            gemSecGrpRule.setPortRangeMin(osSecGrpRule.getPortRangeMin());
            gemSecGrpRule.setPortRangeMax(osSecGrpRule.getPortRangeMax());
            gemSecGrpRule.setProtocol(Protocol.fromString(osSecGrpRule.getProtocol()));
            //                gemSecGrpRule.setCidr(osSecGrpRule.getRange().getCidr());
            gemSecGrpRule.setDirection(
                    GeminiSecurityGroupRuleDirection.valueOf(osSecGrpRule.getDirection().toUpperCase()));
            gemSecGrpRule.setRemoteGroupId(osSecGrpRule.getRemoteGroupId());
            gemSecGrpRule.setRemoteIpPrefix(osSecGrpRule.getRemoteIpPrefix());
            gemSecGrpRule.setIpAddressType(IPAddressType.valueOf(osSecGrpRule.getEtherType()));
            gemSecGrpRule.setParent(securityGroup);
            securityGroup.addSecurityRule(gemSecGrpRule);
        }
        listSecGrpRules.add(gemSecGrpRule);
    });

    Logger.debug("Successfully retrieved security groups rules Tenant: {} Env: {} security group {}",
            tenant.getName(), env.getName(), securityGroup.getName());
    return listSecGrpRules;
}

From source file:org.lightjason.agentspeak.action.builtin.TestCActionCollectionList.java

/**
 * test range/*from  w  w  w.j a  va 2 s.c o  m*/
 */
@Test
public final void range() {
    final List<ITerm> l_return = new ArrayList<>();

    new CRange().execute(false, IContext.EMPTYPLAN,
            Stream.of(0, 5, 7, 9).map(CRawTerm::from).collect(Collectors.toList()), l_return);

    new CRange().execute(true, null, Stream.of(1, 7).map(CRawTerm::from).collect(Collectors.toList()),
            l_return);

    Assert.assertEquals(l_return.size(), 3);

    Assert.assertArrayEquals(l_return.get(0).<List<?>>raw().toArray(), IntStream.range(0, 5).boxed().toArray());
    Assert.assertArrayEquals(l_return.get(1).<List<?>>raw().toArray(), IntStream.range(7, 9).boxed().toArray());

    Assert.assertArrayEquals(l_return.get(2).<List<?>>raw().toArray(), IntStream.range(1, 7).boxed().toArray());
    Assert.assertEquals(l_return.get(2).<List<?>>raw().getClass(),
            Collections.synchronizedList(Collections.emptyList()).getClass());
}