Example usage for java.util.concurrent ThreadPoolExecutor execute

List of usage examples for java.util.concurrent ThreadPoolExecutor execute

Introduction

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

Prototype

public void execute(Runnable command) 

Source Link

Document

Executes the given task sometime in the future.

Usage

From source file:la2launcher.MainFrame.java

private void processValidation(boolean full) {
    final long initTime = new Date().getTime();
    final String patcherUrl = "http://" + updateHost + "/hf/updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    tpe.execute(new Runnable() {
        @Override//from  www  .ja  va 2 s  . c  o m
        public void run() {
            jTextArea2.setText("");
            try {
                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  system");
                }
                File patcher = File.createTempFile("la2", "la2");
                patcher.deleteOnExit();
                File patcherExt = File.createTempFile("la2", "la2");
                patcherExt.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(patcher);
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(patcherUrl);
                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                HttpEntity entity1 = response1.getEntity();
                copyStream(entity1.getContent(), fos, null);
                response1.close();
                fos.close();
                jTextArea2.setText(jTextArea2.getText()
                        + "\r\n??  ? ?: " + patcherUrl);

                fixBzip2File(patcher);
                jTextArea2.setText(jTextArea2.getText() + "\r\n ?");

                BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(patcher));
                OutputStream pout = new FileOutputStream(patcherExt);
                copyStream(bz, pout, new CopyListener() {
                    @Override
                    public void transfered(int n) {
                        bytesRecieved += n;
                        bytesRecievedTotal += n;
                    }
                });
                pout.close();
                bz.close();
                jTextArea2.setText(jTextArea2.getText() + "\r\n? ?");

                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText()
                            + "\r\n     system");
                }

                DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
                model.setRowCount(0);

                int filesCount = scanSumFilesCount(patcherExt, full);
                jProgressBar1.setMinimum(0);
                jProgressBar1.setMaximum(filesCount);
                jProgressBar1.setValue(0);
                jLabel4.setText("0/" + filesCount);
                scanSumFile(patcherExt, new SumHandler() {

                    private ReentrantLock lock = new ReentrantLock();

                    @Override
                    public void handle(MDNamePair pair) {
                        try {
                            jProgressBar1.setIndeterminate(false);
                            //lock.unlock();
                            tpe.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        lock.lock();
                                        //printMsg(pair.filename);
                                        String crc = digest(new File(gamePath + pair.filename));
                                        //printMsg("    : " + pair.crc);
                                        //printMsg("   ? ? : " + crc);
                                        if (!pair.crc.equals(crc)) {
                                            DefaultTableModel dtm = (DefaultTableModel) jTable2.getModel();
                                            dtm.addRow(new Object[] { pair.filename, false });
                                        }
                                        jProgressBar1.setValue(jProgressBar1.getValue() + 1);
                                        jLabel4.setText(jProgressBar1.getValue() + "/" + filesCount);
                                        lock.unlock();
                                    } catch (NoSuchAlgorithmException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (IOException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } finally {
                                        //if (lock.isLocked()) lock.unlock();
                                    }
                                }
                            });
                        } finally {
                            //if (lock.isLocked()) lock.unlock();
                        }
                    }
                }, full);
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}

From source file:la2launcher.MainFrame.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    final long initTime = new Date().getTime();
    ReentrantLock lock = new ReentrantLock();
    final String patcherUrl = "http://" + updateHost + "/hf//updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    filesProcessed = 0;/*from   ww w.  j av  a  2s.  com*/
    tpe.execute(new Runnable() {
        @Override
        public void run() {
            jTextArea2.setText("");
            DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
            jProgressBar1.setMinimum(0);
            jProgressBar1.setMaximum(model.getRowCount());
            jProgressBar1.setValue(0);
            jLabel4.setText("0/" + model.getRowCount());
            for (int i = 0; i < model.getRowCount(); i++) {
                boolean checked = (Boolean) model.getValueAt(i, 1);
                String fileName = (String) model.getValueAt(i, 0);
                if (checked) {
                    tpe.execute(new Runnable() {
                        @Override
                        public void run() {

                            final String fileUrl = "http://" + updateHost + "/hf/" + fileName.replace("\\", "/")
                                    + ".la2";
                            try {
                                printMsg("  " + fileUrl);
                                File file = new File(gamePath + fileName + ".rar");
                                File fileExt = new File(gamePath + fileName);

                                file.getParentFile().mkdirs();
                                FileOutputStream fos = new FileOutputStream(file);
                                CloseableHttpClient httpclient = HttpClients.createDefault();
                                HttpGet httpGet = new HttpGet(fileUrl);
                                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                                HttpEntity entity1 = response1.getEntity();
                                copyStream(entity1.getContent(), fos, new CopyListener() {
                                    @Override
                                    public void transfered(int n) {
                                        bytesRecieved += n;
                                        bytesRecievedTotal += n;
                                    }
                                });
                                response1.close();
                                fos.close();

                                printMsg("?? : " + fileName);

                                lock.lock();
                                //fixBzip2File(file);
                                //printMsg(" ?");

                                extractArchive(file.getAbsolutePath());

                                //BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(file));
                                //OutputStream pout = new FileOutputStream(fileExt);
                                //copyStream(archStream, pout, null);
                                //pout.close();
                                //archStream.close();
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n? : " + fileName);
                                printMsg("? : " + fileName);
                                //file.delete();

                                //                                    File tgt = new File(gamePath + fileName);
                                //                                    if (tgt.exists()) {
                                //                                        tgt.delete();
                                //                                    }
                                //tgt.getParentFile().mkdirs();
                                //Files.move(fileExt.toPath(), new File(gamePath + fileName).toPath());
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n ??: " + fileName);
                                printMsg(" ??: " + fileName);
                                jProgressBar1.setIndeterminate(false);
                                jLabel4.setText((++filesProcessed) + "/" + model.getRowCount());
                                jProgressBar1.setValue((int) filesProcessed);
                                lock.unlock();
                            } catch (IOException ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (Exception ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    });
                }
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton9.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton9.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}

From source file:knowledgeMiner.preprocessing.KnowledgeMinerPreprocessor.java

/**
 * Loops through all Wikipedia/Ontology indices.
 * //from   w  w  w  .j ava2 s  .  com
 * @param taskType
 *            The type of task to process.
 * @param heuristics
 *            The heuristics to process with.
 * @param reverseOrder
 */
private void precomputeAll(PrecomputationTaskType taskType, Collection<? extends WeightedHeuristic> heuristics,
        boolean reverseOrder) {
    boolean loopOntology = taskType == PrecomputationTaskType.CYC_TO_WIKI;

    // Set up the iterator
    OntologySocket ontology = (loopOntology) ? ResourceAccess.requestOntologySocket() : null;
    WMISocket wmi = (loopOntology) ? null : ResourceAccess.requestWMISocket();

    // Set up an executor and add all concepts to the execution queue.
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors
            .newFixedThreadPool(Math.max(1, KnowledgeMiner.getNumThreads()));
    int id = (reverseOrder) ? 35000000 : 0;

    while (true) {
        try {
            // Get next thing
            int nextID = 0;
            if (loopOntology) {
                if (reverseOrder)
                    nextID = ontology.getPrevNode(id);
                else
                    nextID = ontology.getNextNode(id);
            } else {
                if (reverseOrder)
                    nextID = wmi.getPrevArticle(id);
                else
                    nextID = wmi.getNextArticle(id);
            }
            if (nextID < 0)
                break;

            id = nextID;
            if (loopOntology) {
                // If the concept is not a predicate or ephemeral, process
                // it.
                String constant = ontology.findConceptByID(id);
                if (constant != null
                        && ontology.getProperty(id, true, DirectedAcyclicGraph.EPHEMERAL_MARK) == null
                        && !ontology.evaluate(null, CommonConcepts.ISA.getID(), constant,
                                CommonConcepts.PREDICATE.getID())) {
                    PrecomputationTask preTask = new PrecomputationTask(
                            new ConceptModule(new OntologyConcept(constant, id)), heuristics, taskType, this);
                    executor.execute(preTask);
                }
            } else {
                String type = wmi.getPageType(nextID);
                // If it's an article or disambiguation, process it.
                if (type.equals(WMISocket.TYPE_ARTICLE) || type.equals(WMISocket.TYPE_DISAMBIGUATION)) {
                    PrecomputationTask preTask = new PrecomputationTask(new ConceptModule(id), heuristics,
                            taskType, this);
                    executor.execute(preTask);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Wait for completion
    executor.shutdown();
    try {
        if (executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS))
            return;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.err.println("Error precomputing tasks.");
}

From source file:com.emc.esu.test.EsuApiTest.java

@Test
public void testIssue9() throws Exception {
    int threadCount = 10;

    final int objectSize = 10 * 1000 * 1000; // size is not a power of 2.
    final MetadataList list = new MetadataList();
    list.addMetadata(new Metadata("test-data", null, true));
    final EsuApi api = esu;
    final List<Identifier> cleanupList = cleanup;
    ThreadPoolExecutor executor = new ThreadPoolExecutor(threadCount, threadCount, 0, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    try {//ww  w  .j av  a2 s  . c o m
        for (int i = 0; i < threadCount; i++) {
            executor.execute(new Thread() {
                public void run() {
                    ObjectId oid = api.createObjectFromStream(null, list, new RandomInputStream(objectSize),
                            objectSize, null);
                    cleanupList.add(oid);
                }
            });
        }
        while (true) {
            Thread.sleep(1000);
            if (executor.getActiveCount() < 1)
                break;
        }
    } finally {
        executor.shutdown();
    }
}

From source file:net.pms.dlna.DLNAResource.java

/**
 * First thing it does it searches for an item matching the given objectID.
 * If children is false, then it returns the found object as the only object in the list.
 * TODO: (botijo) This function does a lot more than this!
 * @param objectId ID to search for./*from   www.ja  v a 2 s  .c  o m*/
 * @param returnChildren State if you want all the children in the returned list.
 * @param start
 * @param count
 * @param renderer Renderer for which to do the actions.
 * @return List of DLNAResource items.
 * @throws IOException
 */
public synchronized List<DLNAResource> getDLNAResources(String objectId, boolean returnChildren, int start,
        int count, RendererConfiguration renderer) throws IOException {
    ArrayList<DLNAResource> resources = new ArrayList<DLNAResource>();
    DLNAResource dlna = search(objectId, count, renderer);

    if (dlna != null) {
        String systemName = dlna.getSystemName();
        dlna.setDefaultRenderer(renderer);

        if (!returnChildren) {
            resources.add(dlna);
            dlna.refreshChildrenIfNeeded();
        } else {
            dlna.discoverWithRenderer(renderer, count, true);

            if (count == 0) {
                count = dlna.getChildren().size();
            }

            if (count > 0) {
                ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(count);

                int nParallelThreads = 3;
                if (dlna instanceof DVDISOFile) {
                    nParallelThreads = 1; // Some DVD drives die wih 3 parallel threads
                }

                ThreadPoolExecutor tpe = new ThreadPoolExecutor(Math.min(count, nParallelThreads), count, 20,
                        TimeUnit.SECONDS, queue);

                for (int i = start; i < start + count; i++) {
                    if (i < dlna.getChildren().size()) {
                        final DLNAResource child = dlna.getChildren().get(i);

                        if (child != null) {
                            tpe.execute(child);
                            resources.add(child);
                        } else {
                            logger.warn("null child at index {} in {}", i, systemName);
                        }
                    }
                }

                try {
                    tpe.shutdown();
                    tpe.awaitTermination(20, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    logger.error("error while shutting down thread pool executor for " + systemName, e);
                }

                logger.trace("End of analysis for {}", systemName);
            }
        }
    }

    return resources;
}

From source file:com.emc.atmos.api.test.AtmosApiClientTest.java

@Test
public void testIssue9() throws Exception {
    int threadCount = 10;

    final int objectSize = 10 * 1000 * 1000; // not a power of 2
    final AtmosApi atmosApi = api;
    final List<ObjectIdentifier> cleanupList = new ArrayList<ObjectIdentifier>();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(threadCount, threadCount, 0, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    try {// w  w w .j  a  v  a  2s  .  co m
        for (int i = 0; i < threadCount; i++) {
            executor.execute(new Thread() {
                public void run() {
                    CreateObjectRequest request = new CreateObjectRequest();
                    request.content(new RandomInputStream(objectSize)).contentLength(objectSize)
                            .userMetadata(new Metadata("test-data", null, true));
                    ObjectId oid = atmosApi.createObject(request).getObjectId();
                    cleanupList.add(oid);
                }
            });
        }
        while (true) {
            Thread.sleep(1000);
            if (executor.getActiveCount() < 1)
                break;
        }
    } finally {
        executor.shutdown();
        cleanup.addAll(cleanupList);
        if (cleanupList.size() < threadCount)
            Assert.fail("At least one thread failed");
    }
}

From source file:com.emc.atmos.api.test.AtmosApiClientTest.java

@Test
public void testMultiThreadedBufferedWriter() throws Exception {
    int threadCount = 20;
    ThreadPoolExecutor executor = new ThreadPoolExecutor(threadCount, threadCount, 5000, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());

    // test with String
    List<Throwable> errorList = Collections.synchronizedList(new ArrayList<Throwable>());
    for (int i = 0; i < threadCount; i++) {
        executor.execute(
                new ObjectTestThread<String>("Test thread " + i, "text/plain", String.class, errorList));
    }/*from   w ww  .j ava  2  s .c o m*/
    do {
        Thread.sleep(500);
    } while (executor.getActiveCount() > 0);
    if (!errorList.isEmpty()) {
        for (Throwable t : errorList)
            t.printStackTrace();
        Assert.fail("At least one thread failed");
    }

    // test with JAXB bean
    try {
        for (int i = 0; i < threadCount; i++) {
            executor.execute(new ObjectTestThread<AccessTokenPolicy>(
                    createTestTokenPolicy("Test thread " + i, "x.x.x." + i), "text/xml",
                    AccessTokenPolicy.class, errorList));
        }
        do {
            Thread.sleep(500);
        } while (executor.getActiveCount() > 0);
    } finally {
        executor.shutdown();
    }
    if (!errorList.isEmpty()) {
        for (Throwable t : errorList)
            t.printStackTrace();
        Assert.fail("At least one thread failed");
    }
}

From source file:org.opendedup.sdfs.filestore.cloud.BatchAwsS3ChunkStore.java

@Override
public void run() {
    while (!closed) {
        try {//from   w w  w.  ja  va  2s . c om
            Thread.sleep(60000);
            try {
                ObjectMetadata omd = s3Service.getObjectMetadata(name, binm);
                Map<String, String> md = omd.getUserMetadata();
                ObjectMetadata nmd = new ObjectMetadata();
                nmd.setUserMetadata(md);
                md.put("currentsize", Long.toString(HashBlobArchive.currentLength.get()));
                md.put("currentcompressedsize", Long.toString(HashBlobArchive.compressedLength.get()));
                md.put("currentsize", Long.toString(HashBlobArchive.currentLength.get()));
                md.put("currentcompressedsize", Long.toString(HashBlobArchive.compressedLength.get()));
                md.put("lastupdate", Long.toString(System.currentTimeMillis()));
                md.put("hostname", InetAddress.getLocalHost().getHostName());
                md.put("port", Integer.toString(Main.sdfsCliPort));
                byte[] sz = Long.toString(System.currentTimeMillis()).getBytes();
                String st = BaseEncoding.base64().encode(ServiceUtils.computeMD5Hash(sz));
                md.put("md5sum", st);
                nmd.setContentMD5(st);
                nmd.setContentLength(sz.length);
                nmd.setUserMetadata(md);
                s3Service.putObject(this.name, binm, new ByteArrayInputStream(sz), nmd);
            } catch (Exception e) {
                try {
                    ObjectMetadata omd = s3Service.getObjectMetadata(name, binm);
                    Map<String, String> md = omd.getUserMetadata();
                    ObjectMetadata nmd = new ObjectMetadata();
                    nmd.setUserMetadata(md);
                    md.put("currentsize", Long.toString(HashBlobArchive.currentLength.get()));
                    md.put("currentcompressedsize", Long.toString(HashBlobArchive.compressedLength.get()));
                    md.put("currentsize", Long.toString(HashBlobArchive.currentLength.get()));
                    md.put("currentcompressedsize", Long.toString(HashBlobArchive.compressedLength.get()));
                    md.put("lastupdate", Long.toString(System.currentTimeMillis()));
                    md.put("hostname", InetAddress.getLocalHost().getHostName());
                    md.put("port", Integer.toString(Main.sdfsCliPort));
                    byte[] sz = Long.toString(System.currentTimeMillis()).getBytes();
                    String st = BaseEncoding.base64().encode(ServiceUtils.computeMD5Hash(sz));
                    md.put("md5sum", st);
                    nmd.setContentMD5(st);
                    nmd.setContentLength(sz.length);
                    nmd.setUserMetadata(md);

                    this.updateObject(binm, nmd);
                } catch (Exception e1) {
                    SDFSLogger.getLog().error("unable to update metadata for " + binm, e);
                }
            }

            if (this.deletes.size() > 0) {
                SDFSLogger.getLog().info("running garbage collection");
                RejectedExecutionHandler executionHandler = new BlockPolicy();
                BlockingQueue<Runnable> worksQueue = new SynchronousQueue<Runnable>();
                ThreadPoolExecutor executor = new ThreadPoolExecutor(1, Main.dseIOThreads, 10, TimeUnit.SECONDS,
                        worksQueue, executionHandler);
                this.delLock.lock();
                HashMap<Long, Integer> odel = null;
                try {
                    odel = this.deletes;
                    this.deletes = new HashMap<Long, Integer>();
                    // SDFSLogger.getLog().info("delete hash table size of "
                    // + odel.size());
                } finally {
                    this.delLock.unlock();
                }
                Set<Long> iter = odel.keySet();
                for (Long k : iter) {
                    DeleteObject obj = new DeleteObject();
                    obj.k = k;
                    obj.odel = odel;
                    obj.st = this;
                    executor.execute(obj);
                }
                executor.shutdown();
                while (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    SDFSLogger.getLog().debug("Awaiting deletion task completion of threads.");
                }
                SDFSLogger.getLog().info("done running garbage collection");
            }
        } catch (InterruptedException e) {
            break;
        } catch (Exception e) {
            SDFSLogger.getLog().error("error in delete thread", e);
        }
    }

}

From source file:net.tjado.jcdbe.jcdbe.java

public static void main(String[] args) throws Exception {
    // print banner
    System.out.println("------------------------------------------");
    System.out.println("| Java Central DataBase Engine v0.4 beta |");
    System.out.println("------------------------------------------");

    // path to the ini configuration
    String configPath = workingDir + "/config/jcdbe.ini";

    // If the first CLI argument doesn't begin with "-" it must be a config file.
    // We need to do this, to have the possibility to specify other ini config files
    // The ini config file is necessary for the input/output classes, which again specify the
    // required CLI arguments
    if (args.length != 0 && !args[0].startsWith("-")) {
        configPath = args[0];//from w  w  w. ja v  a  2 s.  c  om
        // remove first argument from CLI arguments array, so it won't be validated by CLI argument
        // parser
        args = Arrays.copyOfRange(args, 1, args.length);
    }

    // initialize the ini configuration to get required parameters
    Ini config = initConfig(configPath);

    // initialize Logger
    log.init(log4jPropertyFile);

    // setting jdbc property file
    DatabaseOracle.setPropertyFile(jdbcPropertyeFile);

    // declare the input/output classes
    Input input = (Input) Class.forName(inputClass).getDeclaredMethod("getInstance").invoke(null,
            (Object[]) null);
    Output output = (Output) Class.forName(outputClass).getDeclaredMethod("getInstance").invoke(null,
            (Object[]) null);

    // declare options and parser for the CLI arguments
    Options options = new Options();
    CommandLineParser parser = new PosixParser();

    // add "help" CLI argument
    options.addOption("h", "help", false, "print this usage information");

    // add further CLI arguments by the input/output classes
    input.setCLI(options);
    output.setCLI(options);

    CommandLine cli = null;
    try {
        // parse the CLI arguments
        cli = parser.parse(options, args);

        if (cli.hasOption("help") || cli.getOptions().length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar jcdbe.jar [options]", options);

            System.exit(1);
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar jcdbe.jar [options]", options);

        System.exit(1);
    }

    // output engine config after initializing of Logger
    log.debug("[CONFIG] Working Directory: " + workingDir);
    log.debug("[CONFIG] Input class:  " + inputClass);
    log.debug("[CONFIG] Output class: " + outputClass);
    log.debug("[CONFIG] JDBC URL prefix: " + jdbcPrefix);
    log.debug("[CONFIG] Java Library Path: " + System.getProperty("java.library.path"));
    log.debug("[CONFIG] Oracle SDU size: " + sduSize);
    log.debug("[CONFIG] Max. threads: " + threadMax);
    log.debug("[CONFIG] Max. running threads: " + threadRun);
    log.debug("[CONFIG] Thread idle timeout: " + threadTTL);
    log.debug("[CONFIG] Advanced Debugging: " + advDebugging);

    // validate Input arguments
    input.validateParameters(cli, config);
    // validate Output arguments
    output.validateParameters(cli, config);

    // start benchmark time
    measureTimeStart();

    log.info("[INPUT] Initialization");
    // run input init and check if it was successfull....
    if (!input.init()) {
        log.fatal("Error during input init...");
        System.exit(2);
    }
    log.info("[OUTPUT] Initialization");
    // run output init and check if it was successfull....
    if (!output.init()) {
        log.fatal("[OUTPUT] Error during output init...");
        System.exit(3);
    }

    // init thread pool
    workQueue = new ArrayBlockingQueue<Runnable>(99999);
    ThreadPoolExecutor threads = new ThreadPoolExecutor(threadRun, threadMax, threadTTL, TimeUnit.SECONDS,
            workQueue);

    // get DatabaseList object which will manage all database infos (url, username, pw, status...)
    DatabaseList dbList = input.getDatabaseList();

    if (dbList.size() == 0) {
        log.info("[QUEUE] database list is empty... nothing do to.");
        System.exit(1);
    }

    // get all SQL queries to execute
    // Integer = Query ID
    // String = SQL Text
    Map<Integer, String> queries = input.getQueries();

    log.info("[QUEUE] Starting Threads");

    // loop thru dbList to create & execute/queue all threads
    for (Integer id : dbList) {
        try {
            // create new runnable instance
            DatabaseThreadSlave slaveThread = new DatabaseThreadSlave(id, dbList, queries, output, jdbcPrefix,
                    sduSize);
            // insert runnable instance into dbList
            dbList.setThread(id, slaveThread);

            // add runnable instance into thread pool queue
            threads.execute(slaveThread);
        } catch (Exception e) {
            advDebug(e);
            log.warn("Exception in thread-starter loop (DBID: " + id + "): " + e.getMessage());
        }
    }

    //
    // waiting for all threads to complete
    //
    // the timeout handling will be done completely over JDBC
    // see docs for more information
    //

    while (!dbList.isFinished() || threads.getActiveCount() > 0) {
        Thread.sleep(500);
    }

    log.info("[QUEUE] Shutting down all threads");
    threads.shutdown();

    Thread.sleep(2000);

    log.info("[INPUT] close input...");
    input.close();

    log.info("[OUTPUT] close output...");
    output.close();

    // end time-benchmark and output
    measureTimeEnd();

    // rc=0
    System.exit(0);
}

From source file:org.apache.activemq.JmsConnectionStartStopTest.java

public void testConcurrentSessionCreateWithStart() throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
    final Vector<Throwable> exceptions = new Vector<Throwable>();
    final Random rand = new Random();
    Runnable createSessionTask = new Runnable() {
        @Override/*from  www .  ja  v a 2s.  c om*/
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
                stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            } catch (Exception e) {
                exceptions.add(e);
            }
        }
    };

    Runnable startStopTask = new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
                stoppedConnection.start();
                stoppedConnection.stop();
            } catch (Exception e) {
                exceptions.add(e);
            }
        }
    };

    for (int i = 0; i < 1000; i++) {
        executor.execute(createSessionTask);
        executor.execute(startStopTask);
    }

    executor.shutdown();
    assertTrue("executor terminated", executor.awaitTermination(30, TimeUnit.SECONDS));
    assertTrue("no exceptions: " + exceptions, exceptions.isEmpty());
}