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:at.ac.tuwien.dsg.quelle.elasticityQuantification.engines.CloudServiceUnitAnalysisEngine.java

public List<AnalysisResult> analyzeElasticity(CloudProvider cloudProvider) {

    final List<AnalysisResult> analysisResults = Collections.synchronizedList(new ArrayList<AnalysisResult>());
    List<Thread> threads = new ArrayList<Thread>();

    for (final CloudOfferedService unit : cloudProvider.getCloudOfferedServices()) {
        if (!unit.getCategory().equals("IaaS")) {
            continue;
        }/*from   w  w  w.  ja  v  a 2s.  c  om*/
        Thread t = new Thread() {
            @Override
            public void run() {
                analysisResults.add(analyzeElasticity(unit));
            }
        };
        threads.add(t);
        t.start();
    }

    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(CloudServiceUnitAnalysisEngine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return analysisResults;
}

From source file:edu.cmu.lti.oaqa.bioasq.concept.retrieval.GoPubMedSeparateConceptRetrievalExecutor.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    AbstractQuery aquery = TypeUtil.getAbstractQueries(jcas).stream().findFirst().get();
    Collection<QueryConcept> qconcepts = TypeUtil.getQueryConcepts(aquery);
    List<ConceptSearchResult> concepts = Collections.synchronizedList(new ArrayList<>());
    ExecutorService es = Executors.newCachedThreadPool();
    for (QueryConcept qconcept : qconcepts) {
        String queryString = bopQueryStringConstructor.formatQueryConcept(qconcept)
                .replaceAll("[^A-Za-z0-9_\\-\"]+", " ");
        LOG.info("Query string: {}", queryString);
        for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
            es.execute(() -> {//from   w w w  . j  a  v  a2  s . co  m
                try {
                    concepts.addAll(
                            BioASQUtil.searchOntology(service, jcas, queryString, pages, hits, ontology));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(timeout, TimeUnit.MINUTES)) {
            LOG.warn("Timeout occurs for one or some concept retrieval services.");
        }
    } catch (InterruptedException e) {
        throw new AnalysisEngineProcessException(e);
    }
    Map<String, List<ConceptSearchResult>> onto2concepts = concepts.stream()
            .collect(groupingBy(ConceptSearchResult::getSearchId));
    for (Map.Entry<String, List<ConceptSearchResult>> entry : onto2concepts.entrySet()) {
        List<ConceptSearchResult> results = entry.getValue();
        LOG.info("Retrieved {} concepts from {}", results.size(), entry.getKey());
        if (LOG.isDebugEnabled()) {
            results.stream().limit(10).forEach(c -> LOG.debug(" - {}", TypeUtil.toString(c)));
        }
    }
    TypeUtil.rankedSearchResultsByScore(concepts, limit).forEach(ConceptSearchResult::addToIndexes);
}

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

/**
 * test create empty synchronized list//from ww w .j  a  v  a 2 s .  co m
 */
@Test
public final void createemptysynchronize() {
    final List<ITerm> l_return = new ArrayList<>();

    new CCreate().execute(true, IContext.EMPTYPLAN, Collections.emptyList(), l_return);

    Assert.assertEquals(l_return.size(), 1);
    Assert.assertTrue(l_return.get(0).raw() instanceof List<?>);
    Assert.assertTrue(l_return.get(0).<List<?>>raw().isEmpty());
    Assert.assertEquals(l_return.get(0).raw().getClass(),
            Collections.synchronizedList(Collections.emptyList()).getClass());
}

From source file:org.wallerlab.yoink.regionizer.partitioner.CubePartitioner.java

private List<GridPoint> getGridPointsWillBeCalculated(Map<Region.Name, Region> regions, Cube cube,
        Region.Name cubeRegionName) {
    List<GridPoint> gridPoints = Collections.synchronizedList(new ArrayList<GridPoint>());
    List<Coord> coordinates = cube.getCoordinates();
    checkEveryGridPoint(regions, cubeRegionName, gridPoints, coordinates);
    return gridPoints;
}

From source file:org.squidy.manager.data.AbstractData.java

/**
 * Adds a cloned data object to the original data object.
 * //from  w  w w.  ja v a  2  s .  c om
 * @param clone The cloned data object.
 */
protected void addClone(T clone) {
    if (clones == null)
        clones = Collections.synchronizedList(new ArrayList<T>());

    clones.add(clone);
}

From source file:org.dspace.rdf.storage.RDFStorageImpl.java

@Override
public List<String> getAllStoredGraphs() {
    String queryString = "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }";
    QueryExecution qexec;/*from www  .j a  va2s . c om*/
    if (configurationService.hasProperty(RDFUtil.STORAGE_SPARQL_LOGIN_KEY)
            && configurationService.hasProperty(RDFUtil.STORAGE_SPARQL_PASSWORD_KEY)) {
        HttpAuthenticator httpAuthenticator = new SimpleAuthenticator(
                configurationService.getProperty(RDFUtil.STORAGE_SPARQL_LOGIN_KEY),
                configurationService.getProperty(RDFUtil.STORAGE_GRAPHSTORE_PASSWORD_KEY).toCharArray());
        qexec = QueryExecutionFactory.sparqlService(getSparqlEndpoint(), queryString, httpAuthenticator);
    } else {
        qexec = QueryExecutionFactory.sparqlService(getSparqlEndpoint(), queryString);
    }

    ResultSet rs = qexec.execSelect();
    List<String> graphs = Collections.synchronizedList(new ArrayList<String>());
    while (rs.hasNext()) {
        QuerySolution solution = rs.next();
        if (solution.contains("g")) {
            graphs.add(solution.get("g").asResource().getURI());
        }
    }
    qexec.close();
    return graphs;
}

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

/**
 * @throws Exception if the test fails//from w  w w  .  j  a v a 2s  .c om
 */
@Test
@Tries(3)
public void dontWaitWhenUnnecessary_jobRemovesOtherJob() throws Exception {
    final String content = "<html>\n" + "<head>\n" + "  <title>test</title>\n" + "  <script>\n"
            + "    var longTimeoutID;\n" + "    function test() {\n"
            + "      longTimeoutID = setTimeout(doAlert('late'), 10000);\n"
            + "      setTimeout(clearLongTimeout, 100);\n" + "      setTimeout(doAlert('hello'), 300);\n"
            + "    }\n" + "    function clearLongTimeout() {\n" + "      alert('clearLongTimeout');\n"
            + "      clearTimeout(longTimeoutID);\n" + "    }\n" + "    function doAlert(_text) {\n"
            + "      return function doAlert() {\n" + "        alert(_text);\n" + "      }\n" + "    }\n"
            + "  </script>\n" + "</head>\n" + "<body onload='test()'>\n" + "</body>\n" + "</html>";

    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    final HtmlPage page = loadPage(content, collectedAlerts);
    final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager();
    assertNotNull(jobManager);
    assertEquals(3, jobManager.getJobCount());

    startTimedTest();
    assertEquals(0, page.getWebClient().waitForBackgroundJavaScriptStartingBefore(20_000));
    assertMaxTestRunTime(400);
    assertEquals(0, jobManager.getJobCount());

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

From source file:org.commonreality.sensors.base.BaseSensor.java

public BaseSensor(CommonReality cr) {
    super(cr);//  w  ww . j  a v a 2  s  .c  o m
    _toBeAdded = Collections.synchronizedMap(new HashMap<IIdentifier, Collection<ISimulationObject>>());
    _toBeRemoved = Collections.synchronizedMap(new HashMap<IIdentifier, Collection<IIdentifier>>());
    _toBeChanged = Collections.synchronizedMap(new HashMap<IIdentifier, Collection<IObjectDelta>>());
    _delayedCommands = Collections.synchronizedList(new ArrayList<IMessage>());
    _committer = new Committer();
    _service = Executors.newSingleThreadExecutor();
    _perceptManager = createPerceptManager();
}

From source file:org.flite.mock.amazonaws.sqs.AmazonSQSMock.java

public CreateQueueResult createQueue(final CreateQueueRequest request)
        throws AmazonServiceException, AmazonClientException {
    if (request == null) {
        throw new AmazonClientException("Null CreateQueueRequest");
    }/*from  w  ww  .  j  a v a 2  s . co m*/
    final String queueName = request.getQueueName();
    if (StringUtils.isBlank(queueName) || queueName.length() > 80) {
        throw new AmazonServiceException("Invalid queue name: " + queueName);
    }
    final String queueUrl = QUEUE_URL_PREFIX + queueName;
    checkURLForException(queueUrl);
    // Per documentation, throws QueueNameExistsException, but in my testing, they actually
    // just quietly return the CreateQueueResult
    // (Also note: we are ignoring the documented exception: QueueDeletedRecentlyException)
    if (!allQueues.containsKey(queueUrl)) {
        allQueues.put(queueUrl, Collections.synchronizedList(new ArrayList<Message>()));
        retrievedMessages.put(queueUrl, new ConcurrentHashMap<String, Message>());
    }
    return new CreateQueueResult().withQueueUrl(queueUrl);
}

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

@Test
public void testMultiThreadDispatch() throws Exception {
    final Tracker tracker = createTracker();
    tracker.setDispatchInterval(20);/*ww  w  . j  av a 2s.com*/

    final int threadCount = 20;
    final int queryCount = 100;
    final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>());
    launchTestThreads(tracker, threadCount, queryCount, createdEvents);

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