List of usage examples for java.util.concurrent Executors newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
From source file:com.github.lindenb.mscheduler.MScheduler.java
protected int updateJobStatus(final Task task) { final StatusChecker call = createStatusChecker(task); final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<Integer> future = executor.submit(call); int return_status = -1; try {/* w w w . j a v a2 s. co m*/ //allow 10 seconds to get status return_status = future.get(10, TimeUnit.SECONDS); return return_status; } catch (TimeoutException e) { future.cancel(true); LOG.error("Timeout for gettting job status and " + task); return -1; } catch (Exception e) { future.cancel(true); LOG.error("Failure:", e); return -1; } finally { executor.shutdown(); } }
From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java
/** * Query the server for Recipes which contains at subset of the given ingredients list. * @param ingredients The list of ingredients by which to search. * @return ReturnCode.ERROR if anything goes wrong, ReturnCode.NO_RESULTS if * the search returned no results, ReturnCode.SUCCESS if the search was successful, * in which case the results are written to the database and the observing views * are notified, ReturnCode.BUSY if the server was busy or the operation took * longer than TIME_PERIOD seconds./*from w w w .j av a 2 s .c o m*/ */ public ReturnCode searchByIngredients(ArrayList<Ingredient> ingredients) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ReturnCode> future = executor.submit(new SearchByIngredientsTask(ingredients)); ReturnCode ret = ReturnCode.ERROR; try { ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS); } catch (TimeoutException te) { logger.log(Level.SEVERE, "Search by Ingredients operation timed out."); return ReturnCode.BUSY; } catch (Exception e) { logger.log(Level.SEVERE, "Exception during Search by Ingredients operation."); return ReturnCode.ERROR; } /* Got here so the operation finished. */ executor.shutdownNow(); return ret; }
From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java
@Test public void testProduceXmlRecordsRecordElement() throws StageException, IOException, InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(//from w w w . ja va 2s . co m new ProducerRunnable(TOPIC7, SINGLE_PARTITION, producer, startLatch, DataType.XML, null, -1, null)); KafkaConfigBean conf = new KafkaConfigBean(); conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI(); conf.topic = TOPIC7; conf.consumerGroup = CONSUMER_GROUP; conf.zookeeperConnect = zkConnect; conf.maxBatchSize = 9; conf.maxWaitTime = 5000; conf.kafkaConsumerConfigs = null; conf.produceSingleRecordPerMessage = false; conf.dataFormat = DataFormat.XML; conf.dataFormatConfig.charset = "UTF-8"; conf.dataFormatConfig.removeCtrlChars = false; conf.dataFormatConfig.xmlRecordElement = "author"; conf.dataFormatConfig.xmlMaxObjectLen = 4096; SourceRunner sourceRunner = new SourceRunner.Builder(StandaloneKafkaSource.class, createSource(conf)) .addOutputLane("lane").build(); sourceRunner.runInit(); startLatch.countDown(); List<Record> records = new ArrayList<>(); StageRunner.Output output = getOutputAndRecords(sourceRunner, 9, "lane", records); shutDownExecutorService(executorService); String newOffset = output.getNewOffset(); Assert.assertNull(newOffset); // we stop at 10 because each message has an XML with 2 authors (one record each) Assert.assertEquals(10, records.size()); sourceRunner.runDestroy(); }
From source file:edu.kit.trufflehog.view.jung.visualization.FXVisualizationViewer.java
synchronized public void refreshLayout() { // logger.debug("refresh"); final FRLayout2<INode, IConnection> l = new FRLayout2<>(this.layout.getObservableGraph()); l.setMaxIterations(layout.getGraph().getEdgeCount() * (int) (this.getWidth() / canvas.getScale())); // l.setMaxIterations(700); this.layout = new ObservableLayout<>(l); //TODO make the dimension changeable from settings menu? // logger.debug(canvas.getScale() + " " + this.getWidth() + " " + this.getHeight()); layout.setSize(new Dimension((int) (this.getWidth() / (2 * canvas.getScale())), (int) (this.getHeight() / (2 * canvas.getScale())))); //layout.set// w w w .j a v a 2s . c om final Executor layouter = Executors.newSingleThreadExecutor(); layouter.execute(() -> { while (!layout.done()) { layout.step(); Platform.runLater(this::repaint); } }); }
From source file:com.uwsoft.editor.data.manager.DataManager.java
public void importExternalSpriteAnimationsIntoProject(final ArrayList<File> files, ProgressHandler progressHandler) { if (files.size() == 0) { return;/*from w w w . java 2 s .co m*/ } handler = progressHandler; ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { String newAnimName = null; String rawFileName = files.get(0).getName(); String fileExtension = FilenameUtils.getExtension(rawFileName); if (fileExtension.equals("png")) { Settings settings = new Settings(); settings.square = true; settings.flattenPaths = true; TexturePacker texturePacker = new TexturePacker(settings); FileHandle pngsDir = new FileHandle(files.get(0).getParentFile().getAbsolutePath()); for (FileHandle entry : pngsDir.list(new PngFilenameFilter())) { texturePacker.addImage(entry.file()); } String fileNameWithoutExt = FilenameUtils.removeExtension(rawFileName); String fileNameWithoutFrame = fileNameWithoutExt.replaceAll("\\d*$", ""); String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutFrame; File targetDir = new File(targetPath); if (targetDir.exists()) { try { FileUtils.deleteDirectory(targetDir); } catch (IOException e) { e.printStackTrace(); } } texturePacker.pack(targetDir, fileNameWithoutFrame); newAnimName = fileNameWithoutFrame; } else { for (File file : files) { try { ArrayList<File> imgs = getAtlasPages(file); String fileNameWithoutExt = FilenameUtils.removeExtension(file.getName()); String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutExt; File targetDir = new File(targetPath); if (targetDir.exists()) { FileUtils.deleteDirectory(targetDir); } for (File img : imgs) { FileUtils.copyFileToDirectory(img, targetDir); } FileUtils.copyFileToDirectory(file, targetDir); newAnimName = fileNameWithoutExt; } catch (IOException e) { e.printStackTrace(); } } } if (newAnimName != null) { resolutionManager.resizeSpriteAnimationForAllResolutions(newAnimName, currentProjectInfoVO); } } }); executor.execute(new Runnable() { @Override public void run() { changePercentBy(100 - currentPercent); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } handler.progressComplete(); } }); executor.shutdown(); }
From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java
@Test public void testFlush() throws Exception { final Timing timing = new Timing(); final CountDownLatch latch = new CountDownLatch(1); DistributedQueue<TestQueueItem> queue = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start();/*from ww w . j a v a2 s. co m*/ try { final AtomicBoolean firstTime = new AtomicBoolean(true); queue = new DistributedQueue<TestQueueItem>(client, null, serializer, "/test", new ThreadFactoryBuilder().build(), MoreExecutors.sameThreadExecutor(), 10, true, null, QueueBuilder.NOT_SET, true, 0) { @Override void internalCreateNode(final String path, final byte[] bytes, final BackgroundCallback callback) throws Exception { if (firstTime.compareAndSet(true, false)) { Executors.newSingleThreadExecutor().submit(new Callable<Object>() { @Override public Object call() throws Exception { latch.await(); timing.sleepABit(); client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback) .forPath(path, bytes); return null; } }); } else { super.internalCreateNode(path, bytes, callback); } } }; queue.start(); queue.put(new TestQueueItem("1")); Assert.assertFalse(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); latch.countDown(); Assert.assertTrue(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { if (latch.getCount() > 0) { latch.countDown(); } IOUtils.closeQuietly(queue); IOUtils.closeQuietly(client); } }
From source file:pl.nask.hsn2.service.urlfollower.WebClientWorker.java
private ProcessedPage getInsecurePagesChain(final ProcessedPage processedPage) throws IOException, BreakingChainException, ExecutionException, TimeoutException { final WebRequest req = insecurePagesChaingInitialization(processedPage); ExecutorService ex = Executors.newSingleThreadExecutor(); Future<Page> f = ex.submit(new Callable<Page>() { @Override//from www. ja v a 2s. co m public Page call() throws IOException { return wc.getPage(processedPage.getPage().getEnclosingWindow(), req); } }); Page p = null; try { if (!interruptProcessing) { if (taskParams.getPageTimeoutMillis() <= 0) { p = f.get(); } else { p = f.get(taskParams.getPageTimeoutMillis(), TimeUnit.MILLISECONDS); } } } catch (InterruptedException e) { LOGGER.warn("Gathering {} interrupted", req.getUrl()); Thread.currentThread().interrupt(); } catch (java.util.concurrent.TimeoutException e) { throw new TimeoutException("Timeout when gathering:" + req.getUrl(), e); } finally { if (f != null) { f.cancel(true); } closeExecutorWithJSDisabled(ex); } return insecurePagesChainPostprocessing(processedPage, p); }
From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java
@Test public void testProduceCsvRecords() throws StageException, IOException, InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(//from w w w. ja va2 s. c om new ProducerRunnable(TOPIC9, SINGLE_PARTITION, producer, startLatch, DataType.CSV, null, -1, null)); KafkaConfigBean conf = new KafkaConfigBean(); conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI(); conf.topic = TOPIC9; conf.consumerGroup = CONSUMER_GROUP; conf.zookeeperConnect = zkConnect; conf.maxBatchSize = 9; conf.maxWaitTime = 5000; conf.kafkaConsumerConfigs = null; conf.produceSingleRecordPerMessage = false; conf.dataFormat = DataFormat.DELIMITED; conf.dataFormatConfig.charset = "UTF-8"; conf.dataFormatConfig.removeCtrlChars = false; conf.dataFormatConfig.csvFileFormat = CsvMode.CSV; conf.dataFormatConfig.csvHeader = CsvHeader.NO_HEADER; conf.dataFormatConfig.csvMaxObjectLen = 4096; conf.dataFormatConfig.csvRecordType = CsvRecordType.LIST; conf.dataFormatConfig.csvSkipStartLines = 0; SourceRunner sourceRunner = new SourceRunner.Builder(StandaloneKafkaSource.class, createSource(conf)) .addOutputLane("lane").build(); sourceRunner.runInit(); startLatch.countDown(); List<Record> records = new ArrayList<>(); StageRunner.Output output = getOutputAndRecords(sourceRunner, 9, "lane", records); shutDownExecutorService(executorService); String newOffset = output.getNewOffset(); Assert.assertNull(newOffset); Assert.assertEquals(9, records.size()); sourceRunner.runDestroy(); }
From source file:io.realm.RealmTest.java
private boolean transactionMethodWrongThread(final TransactionMethod method) throws InterruptedException, ExecutionException { if (method != TransactionMethod.METHOD_BEGIN) { testRealm.beginTransaction();//from www . ja v a 2 s. c o m testRealm.createObject(Dog.class); // FIXME: Empty transactions cannot be cancelled } ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<Boolean> future = executorService.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { switch (method) { case METHOD_BEGIN: testRealm.beginTransaction(); break; case METHOD_COMMIT: testRealm.commitTransaction(); break; case METHOD_CANCEL: testRealm.cancelTransaction(); break; } return false; } catch (IllegalStateException ignored) { return true; } } }); boolean result = future.get(); if (result && method != TransactionMethod.METHOD_BEGIN) { testRealm.cancelTransaction(); } return result; }
From source file:fr.bmartel.speedtest.SpeedTestTask.java
/** * write and flush mSocket.// w w w . ja v a 2s.c om * * @param data payload to write * @return error status (-1 for error) * @throws IOException mSocket io exception */ private int writeFlushSocket(final byte[] data) throws IOException { final ExecutorService executor = Executors.newSingleThreadExecutor(); @SuppressWarnings("unchecked") final Future<Integer> future = executor.submit(new Callable() { /** * execute sequential write/flush task. * * @return status */ public Integer call() { try { mSocket.getOutputStream().write(data); mSocket.getOutputStream().flush(); } catch (IOException e) { return -1; } return 0; } }); int status; try { status = future.get(mSocketInterface.getSocketTimeout(), TimeUnit.MILLISECONDS); } catch (TimeoutException e) { future.cancel(true); status = -1; } catch (InterruptedException | ExecutionException e) { status = -1; } executor.shutdownNow(); return status; }