Example usage for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue

List of usage examples for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue.

Prototype

public ConcurrentLinkedQueue() 

Source Link

Document

Creates a ConcurrentLinkedQueue that is initially empty.

Usage

From source file:fr.msch.wissl.server.Library.java

private Library() {
    this.songs = new ConcurrentLinkedQueue<Song>();
    this.toRead = new ConcurrentHashMap<String, File>();
    this.files = new ConcurrentLinkedQueue<File>();
    this.toInsert = new ConcurrentLinkedQueue<Song>();
    this.hashes = new HashSet<String>();
    this.artworks = new HashMap<String, Map<String, String>>();

    this.artworkFallback = new FileFilter() {
        @Override/*from  ww  w. j  ava  2  s . co m*/
        public boolean accept(File pathname) {
            return Pattern.matches(".*[.](jpeg|jpg|png|bmp|gif)$", pathname.getName().toLowerCase());
        }
    };

    Runnable timer = new Runnable() {

        @Override
        public void run() {
            while (!kill) {
                final long t1 = System.currentTimeMillis();

                final List<File> music = new ArrayList<File>();
                for (String path : Config.getMusicPath()) {
                    music.add(new File(path));
                }

                addSongCount = 0;
                skipSongCount = 0;
                failedSongCount = 0;
                fileSearchTime = 0;
                dbCheckTime = 0;
                fileReadTime = 0;
                dbInsertTime = 0;
                resizeTime = 0;
                songs.clear();
                toRead.clear();
                files.clear();
                hashes.clear();
                toInsert.clear();
                artworks.clear();

                songsTodo = 0;
                songsDone = 0;
                working = true;
                stop = false;
                percentDone = 0.0f;
                secondsLeft = -1;

                artworkRegex = Pattern.compile(Config.getArtworkRegex());
                artworkFilter = new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return (artworkRegex.matcher(pathname.getName().toLowerCase()).matches());
                    }
                };

                // walks filesystem and indexes files that look like music
                fileSearchDone = false;
                Thread fileSearch = new Thread(new Runnable() {
                    public void run() {
                        long f1 = System.currentTimeMillis();
                        for (File f : music) {
                            try {
                                listFiles(f, files);
                            } catch (IOException e) {
                                Logger.error("Failed to add directory to library: " + f.getAbsolutePath(), e);
                            } catch (InterruptedException e) {
                                return;
                            }
                        }
                        fileSearchDone = true;
                        fileSearchTime = (System.currentTimeMillis() - f1);
                    }
                });
                fileSearch.start();

                // exclude files that are already in DB
                dbCheckDone = false;
                Thread dbCheck = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !dbCheckDone) {
                            long f1 = System.currentTimeMillis();
                            while (!files.isEmpty()) {
                                File f = files.remove();
                                String hash = new String(md5.digest(f.getAbsolutePath().getBytes()));

                                boolean hasSong = false;

                                try {
                                    hasSong = DB.get().hasSong(hash);
                                } catch (SQLException e) {
                                    Logger.error("Failed to query DB for file " + f.getAbsolutePath(), e);
                                }
                                if (!hasSong) {
                                    toRead.put(hash, f);
                                } else {
                                    skipSongCount++;
                                }
                                hashes.add(hash);
                            }

                            dbCheckTime += (System.currentTimeMillis() - f1);
                            if (fileSearchDone && files.isEmpty()) {
                                dbCheckDone = true;
                                return;
                            }
                        }
                    }
                });
                dbCheck.start();

                // read file metadata
                fileReadDone = false;
                Thread fileRead = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !fileReadDone) {
                            long f1 = System.currentTimeMillis();

                            Iterator<Entry<String, File>> it = toRead.entrySet().iterator();
                            while (it.hasNext()) {
                                Entry<String, File> f = it.next();
                                it.remove();
                                try {
                                    Song s = getSong(f.getValue(), f.getKey());
                                    songs.add(s);
                                    addSongCount++;
                                } catch (IOException e) {
                                    Logger.warn("Failed to read music file " + f.getValue(), e);
                                    failedSongCount++;
                                }
                            }

                            fileReadTime += (System.currentTimeMillis() - f1);
                            if (dbCheckDone && toRead.isEmpty()) {
                                fileReadDone = true;
                                return;
                            }
                        }
                    }
                });
                fileRead.start();

                // resize images
                resizeDone = false;
                Thread resize = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !resizeDone) {
                            long f1 = System.currentTimeMillis();
                            while (!songs.isEmpty()) {
                                Song s = songs.remove();
                                String path = null;
                                Map<String, String> m = artworks.get(s.artist.name);
                                if (m != null && m.containsKey(s.album.name)) {
                                    path = m.get(s.album.name);
                                }
                                if (path != null) {
                                    if (new File(path + "_SCALED.jpg").exists()) {
                                        path = path + "_SCALED.jpg";
                                    } else {
                                        try {
                                            path = resizeArtwork(path);
                                        } catch (IOException e) {
                                            Logger.warn("Failed to resize image", e);
                                        }
                                    }
                                    s.album.artwork_path = path;
                                    s.album.artwork_id = "" + System.currentTimeMillis();
                                }
                                toInsert.add(s);
                            }
                            resizeTime += (System.currentTimeMillis() - f1);

                            if (fileReadDone && songs.isEmpty()) {
                                resizeDone = true;
                                return;
                            }
                        }
                    }
                });
                resize.start();

                // insert Songs in DB
                Thread dbInsert = new Thread(new Runnable() {
                    public void run() {
                        while (!stop) {
                            long f1 = System.currentTimeMillis();
                            while (!toInsert.isEmpty()) {
                                Song s = toInsert.remove();
                                try {
                                    DB.get().addSong(s);
                                } catch (SQLException e) {
                                    Logger.warn("Failed to insert in DB " + s.filepath, e);
                                    failedSongCount++;
                                }
                                songsDone++;
                                percentDone = songsDone / ((float) songsTodo);

                                float songsPerSec = songsDone / ((System.currentTimeMillis() - t1) / 1000f);
                                secondsLeft = (long) ((songsTodo - songsDone) / songsPerSec);
                            }
                            dbInsertTime += (System.currentTimeMillis() - f1);

                            if (resizeDone && toInsert.isEmpty()) {
                                return;
                            }
                        }
                    }
                });
                dbInsert.start();
                try {
                    dbInsert.join();
                } catch (InterruptedException e3) {
                    Logger.warn("Library indexer interrupted", e3);
                    fileSearch.interrupt();
                    dbCheck.interrupt();
                    fileRead.interrupt();
                    resize.interrupt();
                    dbInsert.interrupt();
                }

                if (Thread.interrupted()) {
                    Logger.warn("Library indexer has been interrupted");
                    continue;
                }

                // remove files from DB that were not found
                int removed = 0;
                long r1 = System.currentTimeMillis();
                try {
                    removed = DB.get().removeSongs(hashes);
                } catch (SQLException e3) {
                    Logger.error("Failed to remove songs", e3);
                }
                long dbRemoveTime = (System.currentTimeMillis() - r1);

                // update statistics
                long u1 = System.currentTimeMillis();
                try {
                    DB.get().updateSongCount();
                } catch (SQLException e1) {
                    Logger.error("Failed to update song count", e1);
                }
                long dbUpdateTime = (System.currentTimeMillis() - u1);

                try {
                    RuntimeStats.get().updateFromDB();
                } catch (SQLException e) {
                    Logger.error("Failed to update runtime statistics", e);
                }

                working = false;

                long t2 = (System.currentTimeMillis() - t1);
                Logger.info("Processed " + songsDone + " files " //
                        + "(add:" + addSongCount + "," //
                        + "skip:" + skipSongCount + "," //
                        + "fail:" + failedSongCount + "," //
                        + "rem:" + removed + ")");
                Logger.info("Indexer took " + t2 + " (" + ((float) songsDone / ((float) t2 / 1000)) + " /s) (" //
                        + "search:" + fileSearchTime + "," //
                        + "check:" + dbCheckTime + ","//
                        + "read:" + fileReadTime + "," //
                        + "resize:" + resizeTime + "," //
                        + "insert:" + dbInsertTime + "," //
                        + "remove:" + dbRemoveTime + "," //
                        + "update:" + dbUpdateTime + ")");

                int seconds = Config.getMusicRefreshRate();
                try {
                    Thread.sleep(seconds * 1000);
                } catch (InterruptedException e) {
                    Logger.warn("Library indexer interrupted", e);
                }
            }
        }

    };
    this.thread = new Thread(timer, "MusicIndexer");
}

From source file:org.glassfish.jersey.examples.sseitemstore.ItemStoreResourceTest.java

/**
 * Test the item addition, addition event broadcasting and item retrieval from {@link ItemStoreResource}.
 *
 * @throws Exception in case of a test failure.
 *//*from w  w  w .  jav a  2 s.c  om*/
@Test
public void testItemsStore() throws Exception {
    final List<String> items = Collections.unmodifiableList(Arrays.asList("foo", "bar", "baz"));
    final WebTarget itemsTarget = target("items");
    final CountDownLatch latch = new CountDownLatch(items.size() * MAX_LISTENERS * 2); // countdown on all events
    final List<Queue<Integer>> indexQueues = new ArrayList<Queue<Integer>>(MAX_LISTENERS);
    final EventSource[] sources = new EventSource[MAX_LISTENERS];
    final AtomicInteger sizeEventsCount = new AtomicInteger(0);

    for (int i = 0; i < MAX_LISTENERS; i++) {
        final int id = i;
        final EventSource es = EventSource.target(itemsTarget.path("events")).named("SOURCE " + id).build();
        sources[id] = es;

        final Queue<Integer> indexes = new ConcurrentLinkedQueue<Integer>();
        indexQueues.add(indexes);

        es.register(new EventListener() {
            @SuppressWarnings("MagicNumber")
            @Override
            public void onEvent(InboundEvent inboundEvent) {
                try {
                    if (inboundEvent.getName() == null) {
                        final String data = inboundEvent.readData();
                        LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId()
                                + " data=" + data);
                        indexes.add(items.indexOf(data));
                    } else if ("size".equals(inboundEvent.getName())) {
                        sizeEventsCount.incrementAndGet();
                    }
                } catch (Exception ex) {
                    LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
                    indexes.add(-999);
                } finally {
                    latch.countDown();
                }
            }
        });
    }

    try {
        open(sources);

        for (String item : items) {
            postItem(itemsTarget, item);
        }

        assertTrue("Waiting to receive all events has timed out.",
                latch.await(
                        (1000 + MAX_LISTENERS * EventSource.RECONNECT_DEFAULT) * getAsyncTimeoutMultiplier(),
                        TimeUnit.MILLISECONDS));

        // need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection
        sendCommand(itemsTarget, "disconnect");
    } finally {
        close(sources);
    }

    String postedItems = itemsTarget.request().get(String.class);
    for (String item : items) {
        assertTrue("Item '" + item + "' not stored on server.", postedItems.contains(item));
    }

    int queueId = 0;
    for (Queue<Integer> indexes : indexQueues) {
        for (int i = 0; i < items.size(); i++) {
            assertTrue("Event for '" + items.get(i) + "' not received in queue " + queueId,
                    indexes.contains(i));
        }
        assertEquals("Not received the expected number of events in queue " + queueId, items.size(),
                indexes.size());
        queueId++;
    }

    assertEquals("Number of received 'size' events does not match.", items.size() * MAX_LISTENERS,
            sizeEventsCount.get());
}

From source file:org.apache.http.impl.nio.client.AbstractHttpAsyncClient.java

protected AbstractHttpAsyncClient(final ClientAsyncConnectionManager connmgr) {
    super();/*  w  w  w  .  j av a  2 s  . c o m*/
    this.connmgr = connmgr;
    this.queue = new ConcurrentLinkedQueue<HttpAsyncRequestExecutionHandler<?>>();
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void writeAsync(String filename, int size, int loop, int batch, int storageClass, int locationClass)
        throws Exception {
    System.out.println("writeAsync, filename " + filename + ", size " + size + ", loop " + loop + ", batch "
            + batch + ", storageClass " + storageClass + ", locationClass " + locationClass);

    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    for (int i = 0; i < batch; i++) {
        CrailBuffer buf = null;/*www  . ja  v  a  2s  . c o  m*/
        if (size == CrailConstants.BUFFER_SIZE) {
            buf = fs.allocateBuffer();
        } else if (size < CrailConstants.BUFFER_SIZE) {
            CrailBuffer _buf = fs.allocateBuffer();
            _buf.clear().limit(size);
            buf = _buf.slice();
        } else {
            buf = OffHeapBuffer.wrap(ByteBuffer.allocateDirect(size));
        }
        bufferQueue.add(buf);
    }

    //warmup
    warmUp(filename, warmup, bufferQueue);

    //benchmark
    System.out.println("starting benchmark...");
    LinkedBlockingQueue<Future<CrailResult>> futureQueue = new LinkedBlockingQueue<Future<CrailResult>>();
    HashMap<Integer, CrailBuffer> futureMap = new HashMap<Integer, CrailBuffer>();
    fs.getStatistics().reset();
    long _loop = (long) loop;
    long _bufsize = (long) CrailConstants.BUFFER_SIZE;
    long _capacity = _loop * _bufsize;
    double sumbytes = 0;
    double ops = 0;
    CrailFile file = fs.create(filename, CrailNodeType.DATAFILE, CrailStorageClass.get(storageClass),
            CrailLocationClass.get(locationClass)).get().asFile();
    CrailOutputStream directStream = file.getDirectOutputStream(_capacity);
    long start = System.currentTimeMillis();
    for (int i = 0; i < batch - 1 && ops < loop; i++) {
        CrailBuffer buf = bufferQueue.poll();
        buf.clear();
        Future<CrailResult> future = directStream.write(buf);
        futureQueue.add(future);
        futureMap.put(future.hashCode(), buf);
        ops = ops + 1.0;
    }
    while (ops < loop) {
        CrailBuffer buf = bufferQueue.poll();
        buf.clear();
        Future<CrailResult> future = directStream.write(buf);
        futureQueue.add(future);
        futureMap.put(future.hashCode(), buf);

        future = futureQueue.poll();
        future.get();
        buf = futureMap.get(future.hashCode());
        bufferQueue.add(buf);

        sumbytes = sumbytes + buf.capacity();
        ops = ops + 1.0;
    }
    while (!futureQueue.isEmpty()) {
        Future<CrailResult> future = futureQueue.poll();
        future.get();
        CrailBuffer buf = futureMap.get(future.hashCode());
        sumbytes = sumbytes + buf.capacity();
        ops = ops + 1.0;
    }
    long end = System.currentTimeMillis();
    double executionTime = ((double) (end - start)) / 1000.0;
    double throughput = 0.0;
    double latency = 0.0;
    double sumbits = sumbytes * 8.0;
    if (executionTime > 0) {
        throughput = sumbits / executionTime / 1000.0 / 1000.0;
        latency = 1000000.0 * executionTime / ops;
    }
    directStream.close();

    System.out.println("execution time " + executionTime);
    System.out.println("ops " + ops);
    System.out.println("sumbytes " + sumbytes);
    System.out.println("throughput " + throughput);
    System.out.println("latency " + latency);

    fs.getStatistics().print("close");
}

From source file:org.eclipse.kura.deployment.agent.impl.DeploymentAgent.java

protected void activate(ComponentContext componentContext) {

    this.m_deployedPackages = new Properties();

    this.m_dpaConfPath = System.getProperty(DPA_CONF_PATH_PROPNAME);
    if (this.m_dpaConfPath == null || this.m_dpaConfPath.isEmpty()) {
        throw new ComponentException("The value of '" + DPA_CONF_PATH_PROPNAME + "' is not defined");
    }/*from  ww w .  j  a v  a 2s. c  o  m*/

    final Properties kuraProperties = this.m_systemService.getProperties();

    this.m_packagesPath = kuraProperties.getProperty(PACKAGES_PATH_PROPNAME);
    if (this.m_packagesPath == null || this.m_packagesPath.isEmpty()) {
        throw new ComponentException("The value of '" + PACKAGES_PATH_PROPNAME + "' is not defined");
    }
    if (kuraProperties.getProperty(PACKAGES_PATH_PROPNAME) != null
            && kuraProperties.getProperty(PACKAGES_PATH_PROPNAME).trim().equals("kura/packages")) {
        kuraProperties.setProperty(PACKAGES_PATH_PROPNAME, "/opt/eclipse/kura/kura/packages");
        this.m_packagesPath = kuraProperties.getProperty(PACKAGES_PATH_PROPNAME);
        s_logger.warn("Overridding invalid kura.packages location");
    }

    String sConnTimeout = kuraProperties.getProperty(CONN_TIMEOUT_PROPNAME);
    if (sConnTimeout != null) {
        this.m_connTimeout = Integer.valueOf(sConnTimeout);
    }

    String sReadTimeout = kuraProperties.getProperty(READ_TIMEOUT_PROPNAME);
    if (sReadTimeout != null) {
        this.m_readTimeout = Integer.valueOf(sReadTimeout);
    }

    File dpaConfFile = new File(this.m_dpaConfPath);
    if (dpaConfFile.getParentFile() != null && !dpaConfFile.getParentFile().exists()) {
        dpaConfFile.getParentFile().mkdirs();
    }
    if (!dpaConfFile.exists()) {
        try {
            dpaConfFile.createNewFile();
        } catch (IOException e) {
            throw new ComponentException("Cannot create empty DPA configuration file", e);
        }
    }

    File packagesDir = new File(this.m_packagesPath);
    if (!packagesDir.exists()) {
        if (!packagesDir.mkdirs()) {
            throw new ComponentException("Cannot create packages directory");
        }
    }

    this.m_instPackageUrls = new ConcurrentLinkedQueue<String>();
    this.m_uninstPackageNames = new ConcurrentLinkedQueue<String>();

    this.m_installerExecutor = Executors.newSingleThreadExecutor();

    this.m_uninstallerExecutor = Executors.newSingleThreadExecutor();

    s_installerTask = this.m_installerExecutor.submit(new Runnable() {

        @Override
        public void run() {
            Thread.currentThread().setName("DeploymentAgent");
            installer();
        }
    });

    s_uninstallerTask = this.m_uninstallerExecutor.submit(new Runnable() {

        @Override
        public void run() {
            Thread.currentThread().setName("DeploymentAgent:Uninstall");
            uninstaller();
        }
    });

    installPackagesFromConfFile();
}

From source file:metlos.executors.batch.BatchExecutorTest.java

public void testChangesInTaskCollectionPickedUpInRepetitions() throws Exception {
    final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<Runnable>();
    final AtomicInteger reportedNofTasks = new AtomicInteger();
    final CountDownLatch waitForTask2 = new CountDownLatch(2);
    final CountDownLatch waitForTask3 = new CountDownLatch(2);

    Runnable task1 = new Runnable() {
        @Override//from w  ww. j  a v  a 2  s  . c o m
        public void run() {
        }
    };

    Runnable task2 = new Runnable() {
        @Override
        public void run() {
            if (tasks.size() == 2) {
                reportedNofTasks.set(2);
                waitForTask2.countDown();
            }
        }
    };

    Runnable task3 = new Runnable() {
        @Override
        public void run() {
            if (tasks.size() == 3) {
                reportedNofTasks.set(3);
                waitForTask3.countDown();
            }
        }
    };

    BatchExecutor ex = getExecutor(10);

    tasks.add(task1);
    tasks.add(task2);

    ex.submitWithPreferedDurationAndFixedDelay(tasks, 0, 0, 0, TimeUnit.MILLISECONDS);

    //k, now the tasks should be running and there should be just 2 of them...
    //so we should be getting the value of "2" reported by the reportedNofTasks

    waitForTask2.countDown();
    waitForTask2.await();

    int currentReportedTasks = reportedNofTasks.get();

    assert currentReportedTasks == 2 : "We should be getting 2 tasks reported but are getting "
            + currentReportedTasks + " instead.";

    //k, now let's try updating the tasks collection... this should get picked up by the
    //repeated executions 
    tasks.add(task3);

    //now the reported nof tasks should change to 3. let's wait on it first to make sure the executor has had time to 
    //register the change.        
    waitForTask3.countDown();
    waitForTask3.await();

    currentReportedTasks = reportedNofTasks.get();

    assert currentReportedTasks == 3 : "We should be getting 3 tasks reported but are getting "
            + currentReportedTasks + " instead.";

    ex.shutdown();
}

From source file:org.apache.http.impl.nio.client.AbstractHttpAsyncClient.java

protected AbstractHttpAsyncClient(final IOReactorConfig config) throws IOReactorException {
    super();//from   ww  w  . j a  va2 s.  c o m
    final DefaultConnectingIOReactor defaultioreactor = new DefaultConnectingIOReactor(config);
    defaultioreactor.setExceptionHandler(new InternalIOReactorExceptionHandler(this.log));
    this.connmgr = new PoolingClientAsyncConnectionManager(defaultioreactor);
    this.queue = new ConcurrentLinkedQueue<HttpAsyncRequestExecutionHandler<?>>();
}

From source file:org.deeplearning4j.arbiter.optimize.generator.GridSearchCandidateGenerator.java

@Override
protected void initialize() {
    super.initialize();

    List<ParameterSpace> leaves = LeafUtils.getUniqueObjects(parameterSpace.collectLeaves());
    int nParams = leaves.size();

    //Work out for each parameter: is it continuous or discrete?
    // for grid search: discrete values are grid-searchable as-is
    // continuous values: discretize using 'discretizationCount' bins
    // integer values: use min(max-min+1, discretizationCount) values. i.e., discretize if necessary
    numValuesPerParam = new int[nParams];
    long searchSize = 1;
    for (int i = 0; i < nParams; i++) {
        ParameterSpace ps = leaves.get(i);
        if (ps instanceof DiscreteParameterSpace) {
            DiscreteParameterSpace dps = (DiscreteParameterSpace) ps;
            numValuesPerParam[i] = dps.numValues();
        } else if (ps instanceof IntegerParameterSpace) {
            IntegerParameterSpace ips = (IntegerParameterSpace) ps;
            int min = ips.getMin();
            int max = ips.getMax();
            //Discretize, as some integer ranges are much too large to search (i.e., num. neural network units, between 100 and 1000)
            numValuesPerParam[i] = Math.min(max - min + 1, discretizationCount);
        } else {//from  w ww .  j a v  a 2s .  co  m
            numValuesPerParam[i] = discretizationCount;
        }
        searchSize *= numValuesPerParam[i];
    }

    if (searchSize >= Integer.MAX_VALUE)
        throw new IllegalStateException(
                "Invalid search: cannot process search with " + searchSize + " candidates > Integer.MAX_VALUE"); //TODO find a more reasonable upper bound?

    order = new ConcurrentLinkedQueue<>();

    totalNumCandidates = (int) searchSize;
    switch (mode) {
    case Sequential:
        for (int i = 0; i < totalNumCandidates; i++) {
            order.add(i);
        }
        break;
    case RandomOrder:
        List<Integer> tempList = new ArrayList<>(totalNumCandidates);
        for (int i = 0; i < totalNumCandidates; i++) {
            tempList.add(i);
        }

        Collections.shuffle(tempList, new RandomAdaptor(rng));
        order.addAll(tempList);
        break;
    default:
        throw new RuntimeException();
    }

}

From source file:jef.database.DbUtils.java

/**
 * ?//from w ww  .j  a v a2s .c  o  m
 * 
 * @param tasks
 * @throws SQLException
 */
public static void parallelExecute(List<DbTask> tasks) throws SQLException {
    CountDownLatch latch = new CountDownLatch(tasks.size());
    Queue<SQLException> exceptions = new ConcurrentLinkedQueue<SQLException>();
    Queue<Throwable> throwables = new ConcurrentLinkedQueue<Throwable>();
    for (DbTask task : tasks) {
        task.prepare(latch, exceptions, throwables);
        DbUtils.es.execute(task);
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new SQLException(e);
    }
    if (!exceptions.isEmpty()) {
        throw DbUtils.wrapExceptions(exceptions);
    }
    if (!throwables.isEmpty()) {
        throw DbUtils.toRuntimeException(throwables.peek());
    }
}

From source file:de.hybris.platform.test.ThreadPoolTest.java

/**
 * CORE-66PLA-10816 Potential chance to fetch a PoolableThread with pending transaction from previous run
 * /*from www.j  a va  2s.c o  m*/
 * together with setting logger level for a log4j.logger.de.hybris.platform.util.threadpool=DEBUG prints out
 * information who/where started the stale transaction
 */
@Test
public void testTransactionCleanUp() throws Exception {
    final Queue<Transaction> recordedTransactions = new ConcurrentLinkedQueue<Transaction>();

    final boolean flagBefore = Config.getBoolean("transaction.monitor.begin", false);
    Config.setParameter("transaction.monitor.begin", "true");
    ThreadPool pool = null;

    try {
        // create own pool since we don't want to mess up the system
        pool = new ThreadPool(Registry.getCurrentTenantNoFallback().getTenantID(), MAX_THREADS);

        final GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = MAX_THREADS;
        config.maxIdle = 1;
        config.maxWait = -1;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.timeBetweenEvictionRunsMillis = 30 * 1000; // keep idle threads for at most 30 sec
        pool.setConfig(config);

        final int maxSize = pool.getMaxActive();
        final int activeBefore = pool.getNumActive();
        final List<NoClosingTransactionProcess> started = new ArrayList<NoClosingTransactionProcess>(maxSize);
        for (int i = activeBefore; i < maxSize; i++) {
            final PoolableThread poolableThread = pool.borrowThread();
            final NoClosingTransactionProcess noClosingTransactionProcess = new NoClosingTransactionProcess();
            started.add(noClosingTransactionProcess);
            poolableThread.execute(noClosingTransactionProcess);
        }
        Thread.sleep(1000);

        transacationStartingBarrier.await(); //await for all transacations to start

        //record all started  transactions
        for (final NoClosingTransactionProcess singleStarted : started) {
            recordedTransactions.add(singleStarted.getStartedTransaction());
        }

        finishedStaleTransactionLatch.await(180, TimeUnit.SECONDS);
        Thread.sleep(1000);//give them 1 second to finish

        final List<HasNoCurrentRunningTransactionProcess> ranAfter = new ArrayList<HasNoCurrentRunningTransactionProcess>(
                maxSize);
        Transaction recordedTransaction = recordedTransactions.poll();
        do {
            final PoolableThread poolableThread = pool.borrowThread();
            final HasNoCurrentRunningTransactionProcess hasNoCurrentRunningTransactionProcess = new HasNoCurrentRunningTransactionProcess(
                    recordedTransaction);
            ranAfter.add(hasNoCurrentRunningTransactionProcess);
            poolableThread.execute(hasNoCurrentRunningTransactionProcess);
            recordedTransaction = recordedTransactions.poll();
        } while (recordedTransaction != null);
        //still can borrow
        Assert.assertNotNull(pool.borrowThread());
        Thread.sleep(1000);

        //verify if really Thread had a non started transaction on the enter
        for (final HasNoCurrentRunningTransactionProcess singleRanAfter : ranAfter) {
            if (singleRanAfter.getException() != null) {
                singleRanAfter.getException().printException();
                Assert.fail("Some of the thread(s) captured not finshied transaction in the pool ");
            }
        }
    } finally {
        if (pool != null) {
            try {
                pool.close();
            } catch (final Exception e) {
                // can't help it
            }
        }
        Config.setParameter("transaction.monitor.begin", BooleanUtils.toStringTrueFalse(flagBefore));

    }
}