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.smartitengineering.cms.spi.impl.content.VelocityGeneratorTest.java

@Test
public void testContinuousVelocityRepGeneration() throws IOException {
    TypeRepresentationGenerator generator = new VelocityRepresentationGenerator();
    final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class);
    WorkspaceAPIImpl impl = new WorkspaceAPIImpl() {

        @Override//  w  ww. jav a 2  s  . c om
        public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) {
            return template;
        }
    };
    impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.VELOCITY, generator));
    final RepresentationProvider provider = new RepresentationProviderImpl();
    final WorkspaceAPI api = impl;
    registerBeanFactory(api);
    final Content content = mockery.mock(Content.class);
    final Field field = mockery.mock(Field.class);
    final FieldValue value = mockery.mock(FieldValue.class);
    final Map<String, Field> fieldMap = mockery.mock(Map.class);
    final ContentType type = mockery.mock(ContentType.class);
    final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap");
    final RepresentationDef def = mockery.mock(RepresentationDef.class);
    final int threadCount = new Random().nextInt(100);
    logger.info("Number of parallel threads " + threadCount);
    mockery.checking(new Expectations() {

        {
            exactly(threadCount).of(template).getTemplateType();
            will(returnValue(TemplateType.VELOCITY));
            exactly(threadCount).of(template).getTemplate();
            final byte[] toByteArray = IOUtils.toByteArray(
                    getClass().getClassLoader().getResourceAsStream("scripts/velocity/test-template.vm"));
            will(returnValue(toByteArray));
            exactly(threadCount).of(template).getName();
            will(returnValue(REP_NAME));
            for (int i = 0; i < threadCount; ++i) {
                exactly(1).of(value).getValue();
                will(returnValue(String.valueOf(Integer.MAX_VALUE)));
            }
            exactly(threadCount).of(field).getValue();
            will(returnValue(value));
            exactly(threadCount).of(fieldMap).get(with(Expectations.<String>anything()));
            will(returnValue(field));
            exactly(threadCount).of(content).getFields();
            will(returnValue(fieldMap));
            exactly(threadCount).of(content).getContentDefinition();
            will(returnValue(type));
            final ContentId contentId = mockery.mock(ContentId.class);
            exactly(2 * threadCount).of(content).getContentId();
            will(returnValue(contentId));
            final WorkspaceId wId = mockery.mock(WorkspaceId.class);
            exactly(threadCount).of(contentId).getWorkspaceId();
            will(returnValue(wId));
            exactly(2 * threadCount).of(type).getRepresentationDefs();
            will(returnValue(reps));
            exactly(2 * threadCount).of(reps).get(with(REP_NAME));
            will(returnValue(def));
            exactly(threadCount).of(def).getParameters();
            will(returnValue(Collections.emptyMap()));
            exactly(threadCount).of(def).getMIMEType();
            will(returnValue(GroovyGeneratorTest.MIME_TYPE));
            final ResourceUri rUri = mockery.mock(ResourceUri.class);
            exactly(threadCount).of(def).getResourceUri();
            will(returnValue(rUri));
            exactly(threadCount).of(rUri).getValue();
            will(returnValue("iUri"));
        }
    });
    final Set<String> set = Collections.synchronizedSet(new LinkedHashSet<String>(threadCount));
    final List<String> list = Collections.synchronizedList(new ArrayList<String>(threadCount));
    final AtomicInteger integer = new AtomicInteger(0);
    Threads group = new Threads();
    for (int i = 0; i < threadCount; ++i) {
        group.addThread(new Thread(new Runnable() {

            public void run() {
                Representation representation = provider.getRepresentation(REP_NAME, type, content);
                Assert.assertNotNull(representation);
                Assert.assertEquals(REP_NAME, representation.getName());
                final String rep = StringUtils.newStringUtf8(representation.getRepresentation());
                list.add(rep);
                set.add(rep);
                Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType());
                integer.addAndGet(1);
            }
        }));
    }
    group.start();
    try {
        group.join();
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
    logger.info("Generated reps list: " + list);
    logger.info("Generated reps set: " + set);
    Assert.assertEquals(threadCount, integer.get());
    Assert.assertEquals(threadCount, list.size());
    Assert.assertEquals(1, set.size());
}

From source file:org.pentaho.reporting.engine.classic.core.testsupport.gold.GoldTestBase.java

protected void runAllGoldReportsInParallel(int threads) throws Exception {
    initializeTestEnvironment();//from  w w w  .java  2 s  .c o  m

    final List<Throwable> errors = Collections.synchronizedList(new ArrayList<Throwable>());

    final ExecutorService threadPool = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(), new TestThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    List<ExecuteReportRunner> reports = new ArrayList<ExecuteReportRunner>();
    reports.addAll(collectReports("reports", ReportProcessingMode.legacy, errors));
    reports.addAll(collectReports("reports", ReportProcessingMode.migration, errors));
    reports.addAll(collectReports("reports", ReportProcessingMode.current, errors));
    reports.addAll(collectReports("reports-4.0", ReportProcessingMode.migration, errors));
    reports.addAll(collectReports("reports-4.0", ReportProcessingMode.current, errors));

    for (ExecuteReportRunner report : reports) {
        threadPool.submit(report);
    }

    threadPool.shutdown();
    while (threadPool.isTerminated() == false) {
        threadPool.awaitTermination(5, TimeUnit.MINUTES);
    }
    if (errors.isEmpty() == false) {
        Log log = LogFactory.getLog(GoldTestBase.class);
        for (Throwable throwable : errors) {
            log.error("Failed", throwable);
        }
        Assert.fail();
    }
}

From source file:org.pentaho.di.trans.Trans.java

/**
 * Instantiates a new transformation.// w  w  w . j a  v  a 2 s.  c  om
 */
public Trans() {
    finished = new AtomicBoolean(false);
    paused = new AtomicBoolean(false);
    stopped = new AtomicBoolean(false);

    transListeners = Collections.synchronizedList(new ArrayList<TransListener>());
    transStoppedListeners = Collections.synchronizedList(new ArrayList<TransStoppedListener>());
    delegationListeners = new ArrayList<DelegationListener>();

    // Get a valid transactionId in case we run database transactional.
    transactionId = calculateTransactionId();
    threadName = transactionId; // / backward compatibility but deprecated!

    errors = new AtomicInteger(0);

    stepPerformanceSnapshotSeqNr = new AtomicInteger(0);
    lastWrittenStepPerformanceSequenceNr = 0;

    activeSubtransformations = new HashMap<String, Trans>();
    activeSubjobs = new HashMap<String, Job>();

    resultRows = new ArrayList<RowMetaAndData>();
    resultFiles = new ArrayList<ResultFile>();
    counters = new Hashtable<String, Counter>();

    extensionDataMap = new HashMap<String, Object>();
}

From source file:org.hexlogic.CooptoPluginFactory.java

private void rebuildCache() {
    log.debug("Rebuilding full cache...");
    log.debug("Current cachesize: " + nodes.size() + ".");
    /* Do not just simply clear the cache because e.g. find() requests executed while the new cache is being build 
     * would result in cache misses and trigger a cache rebuild, causing multiple inventory-objects to be created.
     * /* w ww.  j a v a  2  s.co m*/
     * Instead, build the new cache into a newNode array, and replace it in a synchronized way
     */
    ArrayList<DockerNode> newNodes = new ArrayList<DockerNode>();

    // Load node data from EndpointConfiguration
    for (IEndpointConfiguration config : service.getNodes()) {
        if (config != null) {
            // create scripting objects, reload child objects & add to cache
            newNodes.add(this.makeDockerNode(config));
        }
    }

    // replace old list - must be in synchronized block
    synchronized (nodes) {
        nodes = Collections.synchronizedList(newNodes);
    }
    log.debug("New cachesize: " + nodes.size() + ".");
    log.debug("Finished full cache rebuild.");
}

From source file:com.smartitengineering.cms.spi.impl.content.PythonGeneratorTest.java

@Test
public void testMultiPythonRepGeneration() throws IOException {
    TypeRepresentationGenerator generator = new PythonRepresentationGenerator();
    final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class);
    WorkspaceAPIImpl impl = new WorkspaceAPIImpl() {

        @Override//w  w w.ja  va2 s. com
        public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) {
            return template;
        }
    };
    impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.PYTHON, generator));
    final RepresentationProvider provider = new RepresentationProviderImpl();
    final WorkspaceAPI api = impl;
    registerBeanFactory(api);
    final Content content = mockery.mock(Content.class);
    final Field field = mockery.mock(Field.class);
    final FieldValue value = mockery.mock(FieldValue.class);
    final Map<String, Field> fieldMap = mockery.mock(Map.class);
    final ContentType type = mockery.mock(ContentType.class);
    final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap");
    final RepresentationDef def = mockery.mock(RepresentationDef.class);
    final int threadCount = new Random().nextInt(50) + 50;
    logger.info("Number of parallel threads " + threadCount);
    final Set<Integer> expecteds = new LinkedHashSet<Integer>();
    mockery.checking(new Expectations() {

        {
            exactly(threadCount).of(template).getTemplateType();
            will(returnValue(TemplateType.PYTHON));
            exactly(threadCount).of(template).getTemplate();
            final byte[] toByteArray = IOUtils.toByteArray(getClass().getClassLoader()
                    .getResourceAsStream("scripts/python/test-multi-rep-gen-script.py"));
            will(returnValue(toByteArray));
            exactly(threadCount).of(template).getName();
            will(returnValue(REP_NAME));

            for (int i = 0; i < threadCount; ++i) {
                exactly(1).of(value).getValue();
                will(returnValue(String.valueOf(i)));
                expecteds.add(i);
            }
            exactly(threadCount).of(field).getValue();
            will(returnValue(value));
            exactly(threadCount).of(fieldMap).get(with(Expectations.<String>anything()));
            will(returnValue(field));
            exactly(threadCount).of(content).getFields();
            will(returnValue(fieldMap));
            exactly(threadCount).of(content).getContentDefinition();
            will(returnValue(type));
            final ContentId contentId = mockery.mock(ContentId.class);
            exactly(2 * threadCount).of(content).getContentId();
            will(returnValue(contentId));
            final WorkspaceId wId = mockery.mock(WorkspaceId.class);
            exactly(threadCount).of(contentId).getWorkspaceId();
            will(returnValue(wId));
            exactly(2 * threadCount).of(type).getRepresentationDefs();
            will(returnValue(reps));
            exactly(2 * threadCount).of(reps).get(with(REP_NAME));
            will(returnValue(def));
            exactly(threadCount).of(def).getParameters();
            will(returnValue(Collections.emptyMap()));
            exactly(threadCount).of(def).getMIMEType();
            will(returnValue(GroovyGeneratorTest.MIME_TYPE));
            final ResourceUri rUri = mockery.mock(ResourceUri.class);
            exactly(threadCount).of(def).getResourceUri();
            will(returnValue(rUri));
            exactly(threadCount).of(rUri).getValue();
            will(returnValue("iUri"));
        }
    });
    final Set<String> set = Collections.synchronizedSet(new LinkedHashSet<String>(threadCount));
    final List<String> list = Collections.synchronizedList(new ArrayList<String>(threadCount));
    final AtomicInteger integer = new AtomicInteger(0);
    Threads group = new Threads();
    for (int i = 0; i < threadCount; ++i) {
        group.addThread(new Thread(new Runnable() {

            public void run() {
                Representation representation = provider.getRepresentation(REP_NAME, type, content);
                Assert.assertNotNull(representation);
                Assert.assertEquals(REP_NAME, representation.getName());
                final String rep = StringUtils.newStringUtf8(representation.getRepresentation());
                list.add(rep);
                set.add(rep);
                Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType());
                integer.addAndGet(1);
            }
        }));
    }
    long start = System.currentTimeMillis();
    group.start();
    try {
        group.join();
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
    long end = System.currentTimeMillis();
    logger.info("For generating " + threadCount + " simple representation it took " + (end - start) + "ms");
    logger.info("Generated reps list: " + list);
    logger.info("Generated reps set: " + set);
    Assert.assertEquals(threadCount, expecteds.size());
    Assert.assertEquals(threadCount, integer.get());
    Assert.assertEquals(threadCount, list.size());
    Assert.assertEquals(threadCount, set.size());
}

From source file:de.javakaffee.kryoserializers.KryoTest.java

@DataProvider
public Object[][] synchronizedCollections() {
    final HashMap<String, String> m = new HashMap<String, String>();
    m.put("foo", "bar");
    return new Object[][] {
            { Collections.synchronizedList(new ArrayList<String>(Arrays.asList("foo", "bar"))) },
            { Collections.synchronizedSet(new HashSet<String>(Arrays.asList("foo", "bar"))) },
            { Collections.synchronizedMap(m) }, };
}

From source file:net.sourceforge.fenixedu.domain.accounting.report.events.EventReportQueueJob.java

private SheetData<ExemptionBean> allExemptions(final StringBuilder errors) {
    List<String> allEventsExternalIds = getAllEventsExternalIds();
    logger.info(String.format("%s events (exemptions) to process", allEventsExternalIds.size()));

    Integer blockRead = 0;//www  . j  a  v  a2 s.c om

    final List<ExemptionBean> result = Collections.synchronizedList(new ArrayList<ExemptionBean>());

    while (blockRead < allEventsExternalIds.size()) {
        Integer inc = BLOCK;

        if (blockRead + inc >= allEventsExternalIds.size()) {
            inc = allEventsExternalIds.size() - blockRead;
        }

        final List<String> block = allEventsExternalIds.subList(blockRead, blockRead + inc);
        blockRead += inc;

        Thread thread = new Thread() {

            @Override
            @Atomic(mode = TxMode.READ)
            public void run() {
                for (String oid : block) {
                    Event event = FenixFramework.getDomainObject(oid);
                    try {
                        if (!isAccountingEventForReport(event)) {
                            continue;
                        }
                        result.addAll(writeExemptionInformation(event));
                    } catch (Throwable e) {
                        errors.append(getErrorLine(event, e));
                    }
                }
            }
        };

        thread.start();

        try {
            thread.join();
        } catch (InterruptedException e) {
        }

        logger.info(String.format("Read %s events", blockRead));
    }

    return new SheetData<ExemptionBean>(result) {

        @Override
        protected void makeLine(ExemptionBean bean) {
            addCell("Identificador", bean.eventExternalId);
            addCell("Tipo da Iseno", bean.exemptionTypeDescription);
            addCell("Valor da Iseno", bean.exemptionValue);
            addCell("Percentagem da Iseno", bean.percentage);
            addCell("Motivo da Iseno", bean.justification);
        }
    };
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestSpoolDirSource.java

@Test
public void testRecoverableDataParserError() throws Exception {
    File f = new File("target", UUID.randomUUID().toString());
    f.mkdir();/*  w ww.j a v a2 s. co m*/

    SpoolDirConfigBean conf = new SpoolDirConfigBean();
    conf.dataFormat = DataFormat.DELIMITED;
    conf.spoolDir = f.getAbsolutePath();
    conf.batchSize = 10;
    conf.overrunLimit = 100;
    conf.poolingTimeoutSecs = 1;
    conf.filePattern = "file-[0-9].log";
    conf.pathMatcherMode = PathMatcherMode.GLOB;
    conf.maxSpoolFiles = 10;
    conf.initialFileToProcess = "file-0.log";
    conf.dataFormatConfig.compression = Compression.NONE;
    conf.dataFormatConfig.filePatternInArchive = "*";
    conf.dataFormatConfig.csvHeader = CsvHeader.WITH_HEADER;
    conf.errorArchiveDir = null;
    conf.postProcessing = PostProcessingOptions.NONE;
    conf.retentionTimeMins = 10;
    conf.allowLateDirectory = false;
    conf.dataFormatConfig.textMaxLineLen = 10;
    conf.dataFormatConfig.onParseError = OnParseError.ERROR;
    conf.dataFormatConfig.maxStackTraceLines = 0;

    FileOutputStream outputStream = new FileOutputStream(new File(conf.spoolDir, "file-0.log"));
    IOUtils.writeLines(ImmutableList.of("A,B", "a,b,c", "a,b"), "\n", outputStream);
    outputStream.close();

    SpoolDirSource source = new SpoolDirSource(conf);
    PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source)
            .setOnRecordError(OnRecordError.TO_ERROR).addOutputLane("lane").build();
    final List<Record> records = Collections.synchronizedList(new ArrayList<>(10));

    runner.runInit();
    try {
        runner.runProduce(new HashMap<>(), 10, output -> {
            synchronized (records) {
                records.addAll(output.getRecords().get("lane"));
            }
            runner.setStop();
        });

        runner.waitOnProduce();

        // Verify proper record
        Assert.assertNotNull(records);
        Assert.assertEquals(1, records.size());

        // And error record
        List<Record> errorRecords = runner.getErrorRecords();
        Assert.assertEquals(1, errorRecords.size());

    } finally {
        runner.runDestroy();
    }
}

From source file:org.alfresco.repo.transaction.RetryingTransactionHelperTest.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void testTimeLimit() {
    final RetryingTransactionHelper txnHelper = new RetryingTransactionHelper();
    txnHelper.setTransactionService(transactionService);
    txnHelper.setMaxExecutionMs(3000);/*  w ww .  ja v  a  2 s . com*/
    final List<Throwable> caughtExceptions = Collections.synchronizedList(new LinkedList<Throwable>());

    // Try submitting a request after a timeout
    runThreads(txnHelper, caughtExceptions, new Pair(0, 1000), new Pair(0, 5000), new Pair(4000, 1000));
    assertEquals("Expected 1 exception", 1, caughtExceptions.size());
    assertTrue("Excpected TooBusyException", caughtExceptions.get(0) instanceof TooBusyException);

    // Stay within timeout limits
    caughtExceptions.clear();
    runThreads(txnHelper, caughtExceptions, new Pair(0, 1000), new Pair(0, 2000), new Pair(0, 1000),
            new Pair(1000, 1000), new Pair(1000, 2000), new Pair(2000, 1000));
    if (caughtExceptions.size() > 0) {
        throw new RuntimeException("Unexpected exception", caughtExceptions.get(0));
    }
}

From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java

/**
 * Get a list of fields annotated with {@link LdapAttribute} of the implementing mapped class and it's super
 * classes./*from  ww  w  . j a  v a2 s  .c  o  m*/
 *
 * @return list of annotated fields
 */
protected synchronized List<Field> getAnnotatedFields() {
    if (annotatedFields == null) {
        annotatedFields = Collections.synchronizedList(new ArrayList<Field>());
        Class<?> superC = clazz;
        while (superC != null) {
            Field[] fields = superC.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(LdapAttribute.class)) {
                    annotatedFields.add(field);
                }
            }
            superC = superC.getSuperclass();
        }
    }
    return annotatedFields;
}