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.gemini.provision.security.openstack.SecurityProviderOpenStackImpl.java

/**
 *
 * @param tenant/*from w w w  . j a va 2  s. c  om*/
 * @param env
 * @return
 *
 * List all the security groups.
 */
@Override
public List<GeminiSecurityGroup> listAllSecurityGroups(GeminiTenant tenant, GeminiEnvironment env) {
    List<GeminiSecurityGroup> listSecGrps = 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();
    if (os == null) {
        Logger.error("Failed to authenticate Tenant: {}",
                ToStringBuilder.reflectionToString(tenant, ToStringStyle.MULTI_LINE_STYLE));
        return null;
    }

    //get the list from OpenStack
    List<? extends SecurityGroup> osSecGrps = os.networking().securitygroup().list();
    osSecGrps.stream().forEach(osSecGrp -> {
        //see if this security group already exists in the environment
        GeminiSecurityGroup tmpSecGrp = null;
        GeminiSecurityGroup newGemSecGrp = null;
        try {
            tmpSecGrp = env.getSecurityGroups().stream().filter(s -> s.getName().equals(osSecGrp.getName()))
                    .findFirst().get();
            tmpSecGrp.setProvisioned(true);
            tmpSecGrp.setCloudID(osSecGrp.getId());
        } catch (NoSuchElementException | NullPointerException ex) {
            //The OpenStack security group hasn't been mapped to an object on the Gemini side, so create it and add to the environment
            newGemSecGrp = new GeminiSecurityGroup();
            newGemSecGrp.setCloudID(osSecGrp.getId());
            newGemSecGrp.setProvisioned(true);
            newGemSecGrp.setName(osSecGrp.getName());
            newGemSecGrp.setDescription(osSecGrp.getDescription());
            env.addSecurityGroup(newGemSecGrp);
        }

        //check to see if this group's rules are mapped on the Gemini side
        List<? extends SecurityGroupRule> osSecGrpRules = osSecGrp.getRules();
        final GeminiSecurityGroup gemSecGrp = tmpSecGrp == null ? newGemSecGrp : tmpSecGrp;
        osSecGrpRules.stream().filter(osSecGrpRule -> osSecGrpRule != null).forEach(osSecGrpRule -> {
            GeminiSecurityGroupRule gemSecGrpRule = null;
            try {
                gemSecGrpRule = gemSecGrp.getSecurityRules().stream()
                        .filter(sr -> sr.getCloudID().equals(osSecGrpRule.getId())).findFirst().get();
            } catch (NoSuchElementException | NullPointerException 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.setDirection(
                    GeminiSecurityGroupRuleDirection.valueOf(osSecGrpRule.getDirection().toUpperCase()));
            gemSecGrpRule.setRemoteGroupId(osSecGrpRule.getRemoteGroupId());
            gemSecGrpRule.setRemoteIpPrefix(osSecGrpRule.getRemoteIpPrefix());
            gemSecGrpRule.setIpAddressType(IPAddressType.valueOf(osSecGrpRule.getEtherType()));
            //gemSecGrpRule.setCidr(osSecGrpRule.getRange().getCidr());
            gemSecGrpRule.setParent(gemSecGrp);
            gemSecGrp.addSecurityRule(gemSecGrpRule);
        });
        listSecGrps.add(gemSecGrp);
    });

    Logger.debug("Successfully retrieved all security groups Tenant: {} Env: {}", tenant.getName(),
            env.getName());
    return listSecGrps;
}

From source file:libepg.ts.fileseeker.TsFileSeeker.java

/**
 * ???????/*  w  ww .j  a  va 2  s.  c  o  m*/
 *
 * @return ??????
 */
public synchronized List<File> seek() {
    List<File> list = Collections.synchronizedList(new ArrayList<File>());
    Collection<File> files = FileUtils.listFiles(this.SourceDir, this.TS_SUFFIX, this.dirf);
    list.addAll(files);
    return Collections.unmodifiableList(list);
}

From source file:org.springframework.batch.repeat.support.TaskExecutorRepeatTemplateBulkAsynchronousTests.java

@Before
public void setUp() {

    template = new TaskExecutorRepeatTemplate();
    TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    threadPool.setMaxPoolSize(300);/*ww  w .  ja va  2s  .  c o  m*/
    threadPool.setCorePoolSize(10);
    threadPool.setQueueCapacity(0);
    threadPool.afterPropertiesSet();
    taskExecutor = threadPool;
    template.setTaskExecutor(taskExecutor);
    template.setThrottleLimit(throttleLimit);

    items = Collections.synchronizedList(new ArrayList<String>());

    callback = new RepeatCallback() {

        private volatile AtomicInteger count = new AtomicInteger(0);

        @Override
        public RepeatStatus doInIteration(RepeatContext context) throws Exception {
            int position = count.incrementAndGet();
            String item = position <= total ? "" + position : null;
            items.add("" + item);
            if (item != null) {
                beBusy();
            }
            /*
             * In a multi-threaded task, one of the callbacks can call
             * FINISHED early, while other threads are still working, and
             * would do more work if the callback was called again. (This
             * happens for instance if there is a failure and you want to
             * retry the work.)
             */
            RepeatStatus result = RepeatStatus.continueIf(position != early && item != null);
            if (position == error) {
                throw new RuntimeException("Planned");
            }
            if (!result.isContinuable()) {
                logger.debug("Returning " + result + " for count=" + position);
            }
            return result;
        }
    };

}

From source file:org.kurento.test.metatest.BrowserCreationTest.java

private void createParallelBrowsers(int numBrowsers) throws InterruptedException {
    long startTime = System.currentTimeMillis();

    final List<Browser> browsers = Collections.synchronizedList(new ArrayList<Browser>());

    ExecutorService executor = Executors.newFixedThreadPool(numBrowsers);

    try {//from   w ww . ja  va  2 s.co m

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (int i = 0; i < numBrowsers; i++) {

            final int numBrowser = i;

            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {

                        Browser browser = new Browser.Builder().scope(BrowserScope.DOCKER).build();

                        browsers.add(browser);

                        browser.setId("browser" + numBrowser);

                        browser.init();

                        latch.countDown();

                    } catch (Throwable t) {
                        latch.abort("Exception setting up test. A browser could not be initialised", t);
                    }
                }
            });
        }

        latch.await();

        long creationTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers started in {} millis", numBrowsers, creationTime);

        log.debug("----------------------------------------------------------------");

    } finally {

        log.debug("***************************************************************");

        startTime = System.currentTimeMillis();

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (final Browser browser : browsers) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    browser.close();
                    latch.countDown();
                }
            });
        }

        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.HOURS);

        latch.await();

        long destructionTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers stopped in {} millis", numBrowsers, destructionTime);

        log.debug("----------------------------------------------------------------");
    }
}

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

/**
 * @throws Exception if the test fails/* w w w.j a v a 2 s . c o  m*/
 */
@Test
public void dontWaitWhenUnnecessary() throws Exception {
    final String content = "<html>\n" + "<head>\n" + "  <title>test</title>\n" + "  <script>\n"
            + "    var threadID;\n" + "    function test() {\n"
            + "      threadID = setTimeout(doAlert, 10000);\n" + "    }\n" + "    function doAlert() {\n"
            + "      alert('blah');\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(1, jobManager.getJobCount());

    startTimedTest();
    assertEquals(1, page.getWebClient().waitForBackgroundJavaScriptStartingBefore(7000));
    assertMaxTestRunTime(100);
    assertEquals(1, jobManager.getJobCount());
    assertEquals(Collections.EMPTY_LIST, collectedAlerts);
}

From source file:org.alfresco.bm.tools.BMTestRunner.java

/**
 * @param maxTestTime               the maximum time before we stop the test and fail
 *//*from   w w  w . ja v a2  s .c  o m*/
public BMTestRunner(long maxTestTime) {
    this.maxTestTime = maxTestTime;
    this.listeners = Collections.synchronizedList(new ArrayList<BMTestRunnerListener>(1));
}

From source file:org.lightjason.agentspeak.action.buildin.math.statistic.CRandomSample.java

/**
 * creates the sample structure/*  w w  w  .j ava  2s . c om*/
 *
 * @param p_distribution distribution object
 * @param p_size size of the returned values
 * @param p_parallel parallel flag
 * @return term with data
 */
private static ITerm samples(final AbstractRealDistribution p_distribution, final int p_size,
        final boolean p_parallel) {
    if (p_size < 2)
        return CRawTerm.from(p_distribution.sample());

    final List<Double> l_list = Arrays.stream(p_distribution.sample(p_size)).boxed()
            .collect(Collectors.toList());
    return CRawTerm.from(p_parallel ? Collections.synchronizedList(l_list) : l_list);

}

From source file:com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJobManagerTest.java

/**
 * @throws Exception if the test fails//from w  w w . j av a2 s .  com
 */
@Test
public void setClearTimeoutUsesManager() throws Exception {
    final String content = "<html>\n" + "<head>\n" + "  <title>test</title>\n" + "  <script>\n"
            + "    var threadID;\n" + "    function test() {\n"
            + "      threadID = setTimeout(doAlert, 10000);\n" + "    }\n" + "    function doAlert() {\n"
            + "      alert('blah');\n" + "    }\n" + "  </script>\n" + "</head>\n" + "<body onload='test()'>\n"
            + "<a onclick='clearTimeout(threadID);' id='clickme'/>\n" + "</body>\n" + "</html>";

    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    startTimedTest();
    final HtmlPage page = loadPage(content, collectedAlerts);
    final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager();
    assertNotNull(jobManager);
    assertEquals(1, jobManager.getJobCount());
    final HtmlAnchor a = page.getHtmlElementById("clickme");
    a.click();
    jobManager.waitForJobs(7000);
    assertEquals(0, jobManager.getJobCount());
    assertEquals(Collections.EMPTY_LIST, collectedAlerts);
    assertMaxTestRunTime(10000);
}

From source file:se.bitcraze.crazyfliecontrol.bootloader.FirmwareDownloader.java

public FirmwareDownloader(Context context) {
    this.mContext = context;
    this.mDownloadListeners = Collections.synchronizedList(new LinkedList<FirmwareDownloadListener>());
    this.mBootloaderDir = new File(mContext.getExternalFilesDir(null), BootloaderActivity.BOOTLOADER_DIR);
}

From source file:com.buaa.cfs.mount.RpcProgramMountd.java

public RpcProgramMountd(NfsConfiguration config, DatagramSocket registrationSocket, boolean allowInsecurePorts)
        throws IOException {
    // Note that RPC cache is not enabled
    super("mountd", "localhost",
            config.getInt(NfsConfigKeys.DFS_NFS_MOUNTD_PORT_KEY, NfsConfigKeys.DFS_NFS_MOUNTD_PORT_DEFAULT),
            PROGRAM, VERSION_1, VERSION_3, registrationSocket, allowInsecurePorts);
    exports = new ArrayList<String>();
    exports.add(config.get(NfsConfigKeys.DFS_NFS_EXPORT_POINT_KEY, NfsConfigKeys.DFS_NFS_EXPORT_POINT_DEFAULT));
    this.hostsMatcher = NfsExports.getInstance(config);
    this.mounts = Collections.synchronizedList(new ArrayList<MountEntry>());
    UserGroupInformation.setConfiguration(config);
    SecurityUtil.login(config, NfsConfigKeys.DFS_NFS_KEYTAB_FILE_KEY,
            NfsConfigKeys.DFS_NFS_KERBEROS_PRINCIPAL_KEY);
    this.dfsClient = null;
    //        this.dfsClient = new DFSClient(NameNode.getAddress(config), config);
}