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.nubisa.jxcore.MainActivity.java

public void startProgress() {
    jx_instructions = Collections.synchronizedList(new ArrayList<String>());

    Runnable runnable = new Runnable() {
        @Override/*from  ww w .ja  va 2 s  .  c  om*/
        public void run() {
            jx_handler.Initialize(AppManager.currentContext.getFilesDir().getAbsolutePath());

            AppManager.currentActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JXCoreAssetsReady();
                }
            });

            while (instance_alive) {
                try {
                    int active = jx_handler.loopOnce();
                    if (jx_instructions.isEmpty())
                        Thread.sleep(active == 1 ? 0 : 5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                while (!jx_instructions.isEmpty()) {
                    String json = (String) jx_instructions.remove(0);
                    long x = jx_handler.evalEngine(json);
                    if (x != -2) {
                        String result = jx_handler.convertToString(x);
                        // unexpected return, is that an exception ?
                        Log.e("JXcore", result);
                    }
                    jx_handler.loopOnce();
                }
            }
        }
    };
    new Thread(runnable).start();
}

From source file:org.wallerlab.yoink.cube.service.CubeBuilderImpl.java

private List<Coord> getAllCoordinates(Cube cube) {
    Coord[] initialValues = new SimpleCoord[cube.getSize()];
    List<Coord> coordinates = Collections.synchronizedList(Arrays.asList(initialValues));
    IntStream.range(0, cube.getNumberOfXYZSteps()[0]).parallel().forEach(nXStep -> {
        for (int nYStep = 0; nYStep < cube.getNumberOfXYZSteps()[1]; nYStep++) {
            for (int nZStep = 0; nZStep < cube.getNumberOfXYZSteps()[2]; nZStep++) {
                // get the coordinate in cube
                int[] xyzCurrentStep = new int[] { nXStep, nYStep, nZStep };
                Coord currentCoord = coordInCubeCalculator.calculate(xyzCurrentStep, cube);
                // get the index of a grid point in cube
                int indexInCube = nXStep * cube.getNumberOfXYZSteps()[1] * cube.getNumberOfXYZSteps()[2]
                        + nYStep * cube.getNumberOfXYZSteps()[2] + nZStep;
                coordinates.set(indexInCube, currentCoord);
            }//from  w w w  .java 2  s .c  o m
        }
    });
    return coordinates;
}

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

@Test
public void queueReference() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    final List<Message<?>> receivedList1 = Collections.synchronizedList(new ArrayList<Message<?>>());
    MessageHandler handler1 = new MessageHandler() {
        public void handleMessage(Message<?> message) {
            receivedList1.add(message);/*w w  w.ja va2 s.  c om*/
            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.queue);
    factoryBean.afterPropertiesSet();
    SubscribableJmsChannel channel = (SubscribableJmsChannel) factoryBean.getObject();
    channel.afterPropertiesSet();
    channel.start();
    channel.subscribe(handler1);
    channel.subscribe(handler2);
    channel.send(new GenericMessage<String>("foo"));
    channel.send(new GenericMessage<String>("bar"));
    latch.await(TIMEOUT, TimeUnit.MILLISECONDS);
    assertEquals(1, receivedList1.size());
    assertNotNull(receivedList1.get(0));
    assertEquals("foo", receivedList1.get(0).getPayload());
    assertEquals(1, receivedList2.size());
    assertNotNull(receivedList2.get(0));
    assertEquals("bar", receivedList2.get(0).getPayload());
    channel.stop();
}

From source file:org.zaproxy.zap.extension.spider.SpiderScan.java

public SpiderScan(ExtensionSpider extension, SpiderParam spiderParams, Target target, URI spiderURI,
        User scanUser, int scanId) {
    lock = new ReentrantLock();
    this.scanId = scanId;

    numberOfURIsFound = new AtomicInteger();
    foundURIs = Collections.synchronizedSet(new HashSet<String>());
    resourcesFound = Collections.synchronizedList(new ArrayList<SpiderResource>());
    foundURIsOutOfScope = Collections.synchronizedSet(new HashSet<String>());

    state = State.NOT_STARTED;//from ww  w .j av  a  2  s .c  o m

    spiderThread = new SpiderThread(extension, spiderParams, "SpiderApi-" + scanId, this);

    spiderThread.setStartURI(spiderURI);
    spiderThread.setStartNode(target.getStartNode());
    spiderThread.setScanContext(target.getContext());
    spiderThread.setScanAsUser(scanUser);
    spiderThread.setJustScanInScope(target.isInScopeOnly());
    spiderThread.setScanChildren(target.isRecurse());
}

From source file:psiprobe.model.stats.StatsCollection.java

/**
 * New stats./*from w w  w .  ja  va  2  s .  co m*/
 *
 * @param name the name
 * @param maxElements the max elements
 * @return the list
 */
public synchronized List<XYDataItem> newStats(String name, int maxElements) {
    List<XYDataItem> stats = Collections.synchronizedList(new ArrayList<XYDataItem>(maxElements));
    statsData.put(name, stats);
    return stats;
}

From source file:org.apache.hadoop.hdfs.nfs.mount.RpcProgramMountd.java

public RpcProgramMountd(Configuration config) throws IOException {
    // Note that RPC cache is not enabled
    super("mountd", "localhost", config.getInt("nfs3.mountd.port", PORT), PROGRAM, VERSION_1, VERSION_3);
    exports = new ArrayList<String>();
    exports.add(config.get(Nfs3Constant.EXPORT_POINT, Nfs3Constant.EXPORT_POINT_DEFAULT));
    this.hostsMatcher = NfsExports.getInstance(config);
    this.mounts = Collections.synchronizedList(new ArrayList<MountEntry>());
    UserGroupInformation.setConfiguration(config);
    SecurityUtil.login(config, DFS_NFS_KEYTAB_FILE_KEY, DFS_NFS_USER_NAME_KEY);
    this.dfsClient = new DFSClient(NameNode.getAddress(config), config);
}

From source file:com.samknows.measurement.schedule.datacollection.LocationDataCollector.java

@Override
public void start(TestContext tc) {
    super.start(tc);
    locations = Collections.synchronizedList(new ArrayList<Location>());
    manager = (LocationManager) tc.getSystemService(Context.LOCATION_SERVICE);

    locationType = AppSettings.getInstance().getLocationServiceType();
    //if the provider in the settings is gps but the service is not enable fail over to network provider
    if (locationType == LocationType.gps && !manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locationType = LocationType.network;
    }//from  ww w .  j  a  va  2s . c  o  m

    if (locationType != LocationType.gps && locationType != LocationType.network) {
        throw new RuntimeException("unknown location type: " + locationType);
    }

    String provider = locationType == LocationType.gps ? LocationManager.GPS_PROVIDER
            : LocationManager.NETWORK_PROVIDER;

    if (getLastKnown) {
        lastKnown = manager.getLastKnownLocation(provider);
        if (lastKnown != null) {
            data.add(new LocationData(true, lastKnown, locationType));
            lastKnownLocation = locationToDCSString("LASTKNOWNLOCATION", lastKnown);
        }
    }
    gotLastLocation = false;
    manager.requestLocationUpdates(provider, 0, 0, LocationDataCollector.this, Looper.getMainLooper());
    Logger.d(this, "start collecting location data from: " + provider);

    try {
        Logger.d(this, "sleeping: " + time);
        Thread.sleep(time);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    //stop listening for location updates if we are on network. That is done because network location uses network and breaks NetworkCondition
    if (locationType == LocationType.network) {
        manager.removeUpdates(this);
    }
}

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.ComponentBuilder.java

/**
 * Builds a List of ServiceInfo components for each Service defined in a WSDL Document
 *
 * @param wsdlURI A URI that points to a WSDL XML Definition. Can be a filename or URL.
 *
 * @return A List of SoapComponent objects populated for each service defined
 *         in a WSDL document. A null is returned if the document can't be read.
 *//*from   w  w  w .ja  v  a2 s.c om*/
public List buildComponents(String wsdlURI) throws Exception {
    // The list of components that will be returned
    List serviceList = Collections.synchronizedList(new ArrayList());
    // Create the WSDL Reader object
    WSDLReader reader = wsdlFactory.newWSDLReader();
    // Read the WSDL and get the top-level Definition object
    Definition def = reader.readWSDL(null, wsdlURI);
    // Create a castor schema from the types element defined in WSDL
    // This method will return null if there are types defined in the WSDL
    wsdlTypes = createSchemaFromTypes(def);
    // Get the services defined in the document
    Map services = def.getServices();
    if (services != null) {
        // Create a component for each service defined
        Iterator svcIter = services.values().iterator();

        for (int i = 0; svcIter.hasNext(); i++) {
            // Create a new ServiceInfo component for each service found
            ServiceInfo serviceInfo = new ServiceInfo();

            // Populate the new component from the WSDL Definition read
            populateComponent(serviceInfo, (Service) svcIter.next());

            // Add the new component to the List to be returned
            serviceList.add(serviceInfo);
        }
    }
    // return the List of services we created
    return serviceList;
}

From source file:org.alfresco.wcm.client.SectionFactoryTest.java

public void testConcurrentGetSections() {
    final WebSite site = getWebSite();
    final Map<String, List<String>> expectedSections = new TreeMap<String, List<String>>();

    if (SectionFactoryCmisImpl.class.isAssignableFrom(sectionFactory.getClass())) {
        ((SectionFactoryCmisImpl) sectionFactory).setSectionsRefreshAfter(20);
    } else if (SectionFactoryWebscriptImpl.class.isAssignableFrom(sectionFactory.getClass())) {
        ((SectionFactoryWebscriptImpl) sectionFactory).setSectionsRefreshAfter(20);
    }/*w ww . j  a v a  2  s  . c om*/
    expectedSections.put("", Arrays.asList(new String[] { "blog", "contact", "news", "publications" }));
    expectedSections.put("/news", Arrays.asList(new String[] { "companies", "global", "markets" }));
    expectedSections.put("/blog", Arrays.asList(new String[] {}));
    expectedSections.put("/contact", Arrays.asList(new String[] {}));
    expectedSections.put("/publications", Arrays.asList(new String[] { "research-reports", "white-papers" }));
    expectedSections.put("/news/companies", Arrays.asList(new String[] {}));
    expectedSections.put("/news/global", Arrays.asList(new String[] {}));
    expectedSections.put("/news/markets", Arrays.asList(new String[] {}));
    expectedSections.put("/publications/research-reports", Arrays.asList(new String[] {}));
    expectedSections.put("/publications/white-papers", Arrays.asList(new String[] {}));

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

    Runnable treeWalker = new Runnable() {
        @Override
        public void run() {
            try {
                //Run each thread for 5 mins
                long timeToStop = System.currentTimeMillis() + 300000L;
                while (timeToStop > System.currentTimeMillis()) {
                    Section section = site.getRootSection();
                    checkSection("", section);
                }
            } catch (AssertionFailedError e) {
                errorThreads.add(Thread.currentThread());
                throw e;
            } finally {
                threads.remove(Thread.currentThread());
            }
        }

        private void checkSection(String path, Section section) {
            List<Section> children = section.getSections();
            List<String> childNames = new ArrayList<String>(children.size());
            for (Section child : children) {
                childNames.add(child.getName());
            }
            List<String> expectedChildren = expectedSections.get(path);
            assertNotNull(path, expectedChildren);
            assertEquals(path, expectedChildren.size(), childNames.size());
            childNames.removeAll(expectedChildren);
            assertEquals(path, 0, childNames.size());
            for (Section child : children) {
                checkSection(path + "/" + child.getName(), child);
            }
        }
    };

    for (int i = 0; i < 30; ++i) {
        Thread thread = new Thread(treeWalker);
        threads.add(thread);
        thread.start();
    }

    System.out.print("Working");
    while (!threads.isEmpty()) {
        if (!errorThreads.isEmpty()) {
            fail("At least one thread has failed");
        }
        System.out.print(".");
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
        }
    }
    System.out.println();
    System.out.println("Finished");
}

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

@Test
public void testWholeFileRecordsForFile() throws Exception {
    Path sourcePath = Paths.get(testDir + "/source.txt");
    Files.write(sourcePath, "Sample Text 1".getBytes());
    Files.setAttribute(sourcePath, "posix:permissions",
            ImmutableSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
                    PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ));

    SpoolDirSource source = createSource();
    PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane")
            .setOnRecordError(OnRecordError.TO_ERROR).build();

    final List<Record> records = Collections.synchronizedList(new ArrayList<>(10));
    AtomicInteger batchCount = new AtomicInteger(0);

    runner.runInit();/*from   w  ww. j  av a 2 s  .  c  o m*/
    try {
        runner.runProduce(new HashMap<>(), 10, output2 -> {
            synchronized (records) {
                records.addAll(output2.getRecords().get("lane"));
            }
            batchCount.incrementAndGet();
            runner.setStop();
        });

        runner.waitOnProduce();

        Assert.assertNotNull(records);
        Assert.assertEquals(1, records.size());
        Record record = records.get(0);

        Assert.assertTrue(record.has(FileRefUtil.FILE_INFO_FIELD_PATH));
        Assert.assertTrue(record.has(FileRefUtil.FILE_REF_FIELD_PATH));

        Assert.assertEquals(Field.Type.FILE_REF, record.get(FileRefUtil.FILE_REF_FIELD_PATH).getType());
        Assert.assertEquals(Field.Type.MAP, record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getType());

        Map<String, Object> metadata = Files.readAttributes(sourcePath, "posix:*");
        Assert.assertTrue(record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getValueAsMap().keySet()
                .containsAll(metadata.keySet()));

        //Check permissions
        Assert.assertTrue(record.has(FileRefUtil.FILE_INFO_FIELD_PATH + "/" + SpoolDirRunnable.PERMISSIONS));
        Assert.assertEquals("rwxr-----", record
                .get(FileRefUtil.FILE_INFO_FIELD_PATH + "/" + SpoolDirRunnable.PERMISSIONS).getValueAsString());

        Assert.assertEquals(Field.Type.FILE_REF, record.get(FileRefUtil.FILE_REF_FIELD_PATH).getType());
        Assert.assertEquals(Field.Type.MAP, record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getType());

    } finally {
        runner.runDestroy();
    }
}