List of usage examples for java.util.concurrent ExecutorService shutdown
void shutdown();
From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedReentrantLockTest.java
@Test protected void test_try_lock() { ExecutorService exeucotr = Executors.newCachedThreadPool(); final int count = 50; final CountDownLatch latch = new CountDownLatch(count); final DistributedReentrantLock lock = new DistributedReentrantLock(dir); for (int i = 0; i < count; i++) { exeucotr.submit(new Runnable() { public void run() { try { while (lock.tryLock() == false) { Thread.sleep(100 + RandomUtils.nextInt(100)); }//from w w w. j ava 2 s .c o m System.out.println("id: " + lock.getId() + " is leader: " + lock.isOwner()); } catch (InterruptedException e) { want.fail(); } catch (KeeperException e) { want.fail(); } finally { latch.countDown(); try { lock.unlock(); } catch (KeeperException e) { want.fail(); } } } }); } try { latch.await(); } catch (InterruptedException e) { want.fail(); } exeucotr.shutdown(); }
From source file:es.us.lsi.restest.engine.UnirestTest.java
private void makeParallelRequests() throws InterruptedException { ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); final AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < 200; i++) { newFixedThreadPool.execute(new Runnable() { public void run() { try { Unirest.get("http://httpbin.org/get").queryString("index", counter.incrementAndGet()) .asJson();//from ww w. ja v a2 s .co m } catch (UnirestException e) { throw new RuntimeException(e); } } }); } newFixedThreadPool.shutdown(); newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); }
From source file:com.opengamma.engine.cache.BerkeleyDBValueIdentifierMapTest.java
@Test(timeOut = 30000) public void interruptThread() throws Throwable { final ExecutorService threads = Executors.newSingleThreadExecutor(); try {/* w ww .j a v a2 s . com*/ final Thread main = Thread.currentThread(); final Runnable interrupter = new Runnable() { @Override public void run() { try { Thread.sleep(1000); main.interrupt(); } catch (InterruptedException e) { throw new OpenGammaRuntimeException("Interrupted", e); } } }; threads.submit(interrupter); int count = 0; do { try { getPerformanceTest(); } catch (OpenGammaRuntimeException e) { assertEquals("Interrupted", e.getMessage()); count++; if (count <= 5) { threads.submit(interrupter); } else { break; } } } while (true); } finally { threads.shutdown(); Thread.interrupted(); threads.awaitTermination(5, TimeUnit.SECONDS); } }
From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedLockTest.java
@Test protected void test_lock() { ExecutorService exeucotr = Executors.newCachedThreadPool(); final int count = 50; final CountDownLatch latch = new CountDownLatch(count); final DistributedLock[] nodes = new DistributedLock[count]; for (int i = 0; i < count; i++) { final DistributedLock node = new DistributedLock(dir); nodes[i] = node;//ww w . ja v a 2 s .c o m exeucotr.submit(new Runnable() { public void run() { try { node.lock(); Thread.sleep(100 + RandomUtils.nextInt(100)); System.out.println("id: " + node.getId() + " is leader: " + node.isOwner()); } catch (InterruptedException e) { want.fail(); } catch (KeeperException e) { want.fail(); } finally { latch.countDown(); try { node.unlock(); } catch (KeeperException e) { want.fail(); } } } }); } try { latch.await(); } catch (InterruptedException e) { want.fail(); } exeucotr.shutdown(); }
From source file:eu.edisonproject.training.wsd.Wikidata.java
private Map<CharSequence, List<CharSequence>> getCategories(Set<Term> terms) throws MalformedURLException, InterruptedException, ExecutionException { Map<CharSequence, List<CharSequence>> cats = new HashMap<>(); if (terms.size() > 0) { int maxT = 2; BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(maxT); ExecutorService pool = new ThreadPoolExecutor(maxT, maxT, 500L, TimeUnit.MICROSECONDS, workQueue); // ExecutorService pool = new ThreadPoolExecutor(maxT, maxT, // 5000L, TimeUnit.MILLISECONDS, // new ArrayBlockingQueue<>(maxT, true), new ThreadPoolExecutor.CallerRunsPolicy()); Set<Future<Map<CharSequence, List<CharSequence>>>> set1 = new HashSet<>(); String prop = "P910"; for (Term t : terms) { URL url = new URL( PAGE + "?action=wbgetclaims&format=json&props=&property=" + prop + "&entity=" + t.getUid()); Logger.getLogger(Wikidata.class.getName()).log(Level.FINE, url.toString()); WikiRequestor req = new WikiRequestor(url, t.getUid().toString(), 1); Future<Map<CharSequence, List<CharSequence>>> future = pool.submit(req); set1.add(future);// ww w .java2 s .co m } pool.shutdown(); Map<CharSequence, List<CharSequence>> map = new HashMap<>(); for (Future<Map<CharSequence, List<CharSequence>>> future : set1) { while (!future.isDone()) { // Logger.getLogger(Wikipedia.class.getName()).log(Level.INFO, "Task is not completed yet...."); Thread.currentThread().sleep(10); } Map<CharSequence, List<CharSequence>> c = future.get(); if (c != null) { map.putAll(c); } } workQueue = new ArrayBlockingQueue(maxT); pool = new ThreadPoolExecutor(maxT, maxT, 500L, TimeUnit.MICROSECONDS, workQueue); // pool = new ThreadPoolExecutor(maxT, maxT, // 5000L, TimeUnit.MILLISECONDS, // new ArrayBlockingQueue<>(maxT, true), new ThreadPoolExecutor.CallerRunsPolicy()); Set<Future<Map<CharSequence, List<CharSequence>>>> set2 = new HashSet<>(); for (Term t : terms) { List<CharSequence> catIDs = map.get(t.getUid()); for (CharSequence catID : catIDs) { URL url = new URL( PAGE + "?action=wbgetentities&format=json&props=labels&languages=en&ids=" + catID); Logger.getLogger(Wikidata.class.getName()).log(Level.FINE, url.toString()); WikiRequestor req = new WikiRequestor(url, t.getUid().toString(), 2); Future<Map<CharSequence, List<CharSequence>>> future = pool.submit(req); set2.add(future); } } pool.shutdown(); for (Future<Map<CharSequence, List<CharSequence>>> future : set2) { while (!future.isDone()) { // Logger.getLogger(Wikipedia.class.getName()).log(Level.INFO, "Task is not completed yet...."); Thread.currentThread().sleep(10); } Map<CharSequence, List<CharSequence>> c = future.get(); if (c != null) { cats.putAll(c); } } } return cats; }
From source file:ir.ac.iust.nlp.postagger.POSTaggerForm.java
private void btnStartTaggingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartTaggingActionPerformed wordModel.clear();//from w w w.ja v a2 s . c o m predModel.clear(); goldModel.clear(); txtTagLog.setText(""); btnStartTagging.setEnabled(false); tabTag.setSelectedIndex(0); tabTag.setEnabledAt(1, false); File modelFrom = new File(txtModelPath.getText()); File modelTo = new File(System.getProperty("user.dir") + File.separator + modelFrom.getName()); if (!modelFrom.equals(modelTo)) { modelTo.mkdirs(); copyDirectory(modelFrom, modelTo); } PrintStream out = new PrintStream(new OutputStream() { private StringBuffer buffer = new StringBuffer(); @Override public void write(int b) throws IOException { this.buffer.append((char) b); txtTagLog.setText(buffer.toString()); txtTagLog.setCaretPosition(txtTagLog.getDocument().getLength() - 1); } }); RunnableTagging.out = out; String gold = null; if (chkGoldFile.isSelected() == true) { gold = txtGoldFile.getText(); } // Run in a new thread Runnable job = new RunnableTagging(this, modelFrom.getName(), txtInputFile.getText(), txtOutputPath.getText() + "tagged_output.lbl", gold); ExecutorService threadPool = Executors.newFixedThreadPool(1); threadPool.execute(job); threadPool.shutdown(); }
From source file:ir.ac.iust.nlp.postagger.POSTaggerForm.java
private void btnStartTrainingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartTrainingActionPerformed try {//from w ww . java2s .c om txtTrainLog.setText(""); btnStartTraining.setEnabled(false); PrintStream out = new PrintStream(new OutputStream() { private StringBuffer buffer = new StringBuffer(); @Override public void write(int b) throws IOException { this.buffer.append((char) b); txtTrainLog.setText(buffer.toString()); txtTrainLog.setCaretPosition(txtTrainLog.getDocument().getLength() - 1); } }); RunnableTrain.out = out; File trainFrom = new File(txtTrainFile.getText()); File trainTo = new File(System.getProperty("user.dir") + File.separator + trainFrom.getName()); if (!trainFrom.equals(trainTo)) FileUtils.copyFile(trainFrom, trainTo); File modelTo = new File(txtTrainModelPath.getText()); File modelFrom = new File(System.getProperty("user.dir") + File.separator + modelTo.getName()); modelFrom.mkdirs(); // Run in a new thread Runnable job = new RunnableTrain(this, modelTo.getName(), trainFrom.getName(), Integer.parseInt(spMaxIters.getValue().toString())); ExecutorService threadPool = Executors.newFixedThreadPool(1); threadPool.execute(job); threadPool.shutdown(); } catch (IOException | NumberFormatException ex) { } }
From source file:org.jtheque.modules.impl.ModuleLoader.java
/** * Load all the modules from the given files in parallel (using one thread per processor). * * @param files The files to load the modules from. * * @return A Collection containing all the loaded modules. *//*from w w w .ja v a2s .c om*/ @SuppressWarnings({ "ForLoopReplaceableByForEach" }) private Collection<Module> loadInParallel(File[] files) { ExecutorService loadersPool = Executors.newFixedThreadPool(2 * ThreadUtils.processors()); CompletionService<Module> completionService = new ExecutorCompletionService<Module>(loadersPool); for (File file : files) { completionService.submit(new ModuleLoaderTask(file)); } List<Module> modules = CollectionUtils.newList(files.length); try { for (int i = 0; i < files.length; i++) { modules.add(completionService.take().get()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } loadersPool.shutdown(); return modules; }
From source file:ch.jamiete.hilda.plugins.PluginManager.java
public void disablePlugins() { ExecutorService executor = Executors.newSingleThreadExecutor(); synchronized (this.plugins) { final Iterator<HildaPlugin> iterator = this.plugins.iterator(); while (iterator.hasNext()) { final HildaPlugin entry = iterator.next(); Future<?> future = executor.submit(() -> { try { entry.onDisable();// w ww. j a va2s.c om } catch (final Exception e) { Hilda.getLogger().log(Level.WARNING, "Encountered an exception while disabling plugin " + entry.getPluginData().getName(), e); } }); try { future.get(30, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { Hilda.getLogger().log(Level.WARNING, "Plugin " + entry.getPluginData().getName() + " took too long disabling; ceased executing its code", e); } } } executor.shutdown(); try { executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { Hilda.getLogger().log(Level.WARNING, "Encountered an exception during the plugin disable grace period", e); } }
From source file:broadwick.Broadwick.java
/** * Run the Broadwick framework./* ww w.j a va 2s .c o m*/ */ @SuppressWarnings("squid:S1147") public void run() { if (project != null) { final StopWatch sw = new StopWatch(); sw.start(); // initialise the data, by reading the data files and/or the database. log.info("Running broadwick {}", BroadwickVersion.getVersionAndTimeStamp()); try (DataReader dr = new DataReader(project.getData())) { final Map<String, Model> registeredModels = registerModels(project, dr.getLookup()); log.info("Running broadwick for the following models {}", registeredModels.keySet()); // Run the models, each on a separate thread. // TODO in a single-threaded grid environment we cannot do this - need to think again here.... final int poolSize = registeredModels.size(); if (poolSize > 0) { final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("BroadwickModels-%d").setDaemon(true).build(); final ExecutorService es = Executors.newFixedThreadPool(poolSize, threadFactory); //final StopWatch sw = new StopWatch(); for (final Entry<String, Model> entry : registeredModels.entrySet()) { es.submit(new Runnable() { @Override public void run() { final String modelName = entry.getKey(); final Model model = entry.getValue(); try { log.info("Running {} [{}]", modelName, model.getClass().getCanonicalName()); model.init(); model.run(); model.finalise(); } catch (Exception ex) { log.error("Error running model {}. see stack trace from details.", modelName); log.error("{}", Throwables.getStackTraceAsString(ex)); } } }); } es.shutdown(); while (!es.isTerminated()) { es.awaitTermination(10, TimeUnit.SECONDS); } //sw.stop(); //log.trace("Finished {} simulations in {}.", maxSimulations, sw); } } catch (Exception ex) { log.error("{}", ex.getLocalizedMessage()); log.error("{}", Throwables.getStackTraceAsString(ex)); log.error("Something went wrong. See previous messages for details."); } log.info("Simulation complete. {}", sw.toString()); // In rare circumstances, where exceptions are caught and the simulation has completed but // there are still tasks being submitted to the executor, we need to force the progam to quit. Runtime.getRuntime().exit(0); } }