List of usage examples for java.util.concurrent Executors newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
From source file:org.elasticsearch.client.sniff.SnifferTests.java
/** * Test multiple sniffing rounds by mocking the {@link Scheduler} as well as the {@link HostsSniffer}. * Simulates the ordinary behaviour of {@link Sniffer} when sniffing on failure is not enabled. * The {@link CountingHostsSniffer} doesn't make any network connection but may throw exception or return no hosts, which makes * it possible to verify that errors are properly handled and don't affect subsequent runs and their scheduling. * The {@link Scheduler} implementation submits rather than scheduling tasks, meaning that it doesn't respect the requested sniff * delays while allowing to assert that the requested delays for each requested run and the following one are the expected values. *///from w w w.j av a 2 s . c om public void testOrdinarySniffRounds() throws Exception { final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE); long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE); RestClient restClient = mock(RestClient.class); CountingHostsSniffer hostsSniffer = new CountingHostsSniffer(); final int iters = randomIntBetween(30, 100); final Set<Future<?>> futures = new CopyOnWriteArraySet<>(); final CountDownLatch completionLatch = new CountDownLatch(1); final AtomicInteger runs = new AtomicInteger(iters); final ExecutorService executor = Executors.newSingleThreadExecutor(); final AtomicReference<Future<?>> lastFuture = new AtomicReference<>(); final AtomicReference<Sniffer.Task> lastTask = new AtomicReference<>(); Scheduler scheduler = new Scheduler() { @Override public Future<?> schedule(Sniffer.Task task, long delayMillis) { assertEquals(sniffInterval, task.nextTaskDelay); int numberOfRuns = runs.getAndDecrement(); if (numberOfRuns == iters) { //the first call is to schedule the first sniff round from the Sniffer constructor, with delay O assertEquals(0L, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); } else { //all of the subsequent times "schedule" is called with delay set to the configured sniff interval assertEquals(sniffInterval, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); if (numberOfRuns == 0) { completionLatch.countDown(); return null; } } //we submit rather than scheduling to make the test quick and not depend on time Future<?> future = executor.submit(task); futures.add(future); if (numberOfRuns == 1) { lastFuture.set(future); lastTask.set(task); } return future; } @Override public void shutdown() { //the executor is closed externally, shutdown is tested separately } }; try { new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); assertTrue("timeout waiting for sniffing rounds to be completed", completionLatch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(iters, futures.size()); //the last future is the only one that may not be completed yet, as the count down happens //while scheduling the next round which is still part of the execution of the runnable itself. assertTrue(lastTask.get().hasStarted()); lastFuture.get().get(); for (Future<?> future : futures) { assertTrue(future.isDone()); future.get(); } } finally { executor.shutdown(); assertTrue(executor.awaitTermination(1000, TimeUnit.MILLISECONDS)); } int totalRuns = hostsSniffer.runs.get(); assertEquals(iters, totalRuns); int setHostsRuns = totalRuns - hostsSniffer.failures.get() - hostsSniffer.emptyList.get(); verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg()); verifyNoMoreInteractions(restClient); }
From source file:fi.hsl.parkandride.back.LockDaoTest.java
private <T> Future<T> runTxInOtherThread(TransactionCallback<T> transactionCallback) { return Executors.newSingleThreadExecutor().submit(() -> { TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); txTemplate.setTimeout(1);//from w w w.ja va 2s . c o m return txTemplate.execute(transactionCallback); }); }
From source file:fi.hip.sicx.webdav.WebdavClient.java
@Override public boolean connect() { // Check parameters if (this.address == null) { return false; }/*from www . j ava 2 s. co m*/ if (this.port <= 0) { return false; } myExecutor = Executors.newSingleThreadExecutor(); // Lets set timeout to 5 minutes this.host = new Host(this.address, null, this.port, this.username, this.password, null, 300000, null, null); // Lets check if the connection works try { List<? extends Resource> lr = this.host.children(); if (lr == null) { return false; } } catch (Exception e) { return false; } refreshUploadPath(null); // Check success if (this.host != null) { return true; } else { return false; } }
From source file:com.echopf.ECHODataObject.java
/** * Does Push data to the remote server in a background thread. * /*from www.j av a 2 s. c o m*/ * @param sync if set TRUE, then the main (UI) thread is waited for complete the pushing in a background thread. * (a synchronous communication) * @param callback invoked after the pushing is completed * @throws ECHOException */ protected void doPush(final boolean sync, final PushCallback<S> callback) throws ECHOException { final JSONObject obj = buildRequestContents(); if (this.multipart == null) throw new IllegalStateException("`buildRequestContents()` had not been completed."); final boolean fMultipart = this.multipart; // Get ready a background thread final Handler handler = new Handler(); ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Object> communictor = new Callable<Object>() { @Override public Object call() throws ECHOException { JSONObject data = null; ECHOException exception = null; try { synchronized (lock) { if (refid == null) { // post if (fMultipart == false) { data = ECHOQuery.postRequest(getRequestURLPath(), obj); } else { data = ECHOQuery.multipartPostRequest(getRequestURLPath(), obj); } } else { // put if (fMultipart == false) { data = ECHOQuery.putRequest(getRequestURLPath(), obj); } else { data = ECHOQuery.multipartPutRequest(getRequestURLPath(), obj); } } refid = data.optString("refid"); copyData(data); } } catch (ECHOException e) { exception = e; } catch (Exception e) { exception = new ECHOException(e); } if (sync == false) { // Execute a callback method in the main (UI) thread. if (callback != null) { final ECHOException fException = exception; handler.post(new Runnable() { @Override @SuppressWarnings("unchecked") public void run() { callback.done((S) ECHODataObject.this, fException); } }); } } else { if (exception != null) throw exception; } return null; } }; Future<Object> future = executor.submit(communictor); if (sync) { try { future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore/reset } catch (ExecutionException e) { Throwable e2 = e.getCause(); if (e2 instanceof ECHOException) { throw (ECHOException) e2; } throw new RuntimeException(e2); } } }
From source file:com.ifountain.compass.CompositeDirectoryWrapperProvider.java
protected ExecutorService doCreateExecutorService() { return Executors.newSingleThreadExecutor(); }
From source file:hivemall.mix.server.MixServerTest.java
@Test public void test2ClientsZeroOneDenseModel() throws InterruptedException { final int port = NetUtils.getAvailablePort(); CommandLine cl = CommandLineUtils.parseOptions( new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions()); MixServer server = new MixServer(cl); ExecutorService serverExec = Executors.newSingleThreadExecutor(); serverExec.submit(server);// w ww . j a va 2 s . c om waitForState(server, ServerState.RUNNING); final ExecutorService clientsExec = Executors.newCachedThreadPool(); for (int i = 0; i < 2; i++) { clientsExec.submit(new Runnable() { @Override public void run() { try { invokeClient01("test2ClientsZeroOne", port, true, false); } catch (InterruptedException e) { Assert.fail(e.getMessage()); } } }); } clientsExec.awaitTermination(30, TimeUnit.SECONDS); clientsExec.shutdown(); serverExec.shutdown(); }
From source file:com.ikanow.aleph2.management_db.services.DataBucketCrudService.java
/** Work around for Guice circular development issues *//*from w w w .j a va2 s.c om*/ protected void initialize() { _underlying_data_bucket_db.set(_underlying_management_db.get().getDataBucketStore()); _underlying_data_bucket_status_db.set(_underlying_management_db.get().getDataBucketStatusStore()); _bucket_action_retry_store .set(_underlying_management_db.get().getRetryStore(BucketActionRetryMessage.class)); _bucket_deletion_queue .set(_underlying_management_db.get().getBucketDeletionQueue(BucketDeletionMessage.class)); // Handle some simple optimization of the data bucket CRUD repo: Executors.newSingleThreadExecutor().submit(() -> { _underlying_data_bucket_db.get().optimizeQuery( Arrays.asList(BeanTemplateUtils.from(DataBucketBean.class).field(DataBucketBean::full_name))); }); }
From source file:com.meltmedia.cadmium.core.git.GitService.java
/** * Initializes war configuration directory for a Cadmium war. * @param uri The remote Git repository ssh URI. * @param branch The remote branch to checkout. * @param root The shared root./*from w w w . ja va 2 s .c om*/ * @param warName The name of the war file. * @param historyManager The history manager to log the initialization event. * @return A GitService object the points to the freshly cloned Git repository. * @throws RefNotFoundException * @throws Exception */ public static GitService initializeConfigDirectory(String uri, String branch, String root, String warName, HistoryManager historyManager, ConfigManager configManager) throws Exception { initializeBaseDirectoryStructure(root, warName); String warDir = FileSystemManager.getChildDirectoryIfExists(root, warName); Properties configProperties = configManager.getDefaultProperties(); GitLocation gitLocation = new GitLocation(uri, branch, configProperties.getProperty("config.git.ref.sha")); GitService cloned = initializeRepo(gitLocation, warDir, "git-config-checkout"); try { String renderedContentDir = initializeSnapshotDirectory(warDir, configProperties, "com.meltmedia.cadmium.config.lastUpdated", "git-config-checkout", "config"); boolean hasExisting = configProperties.containsKey("com.meltmedia.cadmium.config.lastUpdated") && renderedContentDir != null && renderedContentDir .equals(configProperties.getProperty("com.meltmedia.cadmium.config.lastUpdated")); if (renderedContentDir != null) { configProperties.setProperty("com.meltmedia.cadmium.config.lastUpdated", renderedContentDir); } configProperties.setProperty("config.branch", cloned.getBranchName()); configProperties.setProperty("config.git.ref.sha", cloned.getCurrentRevision()); configProperties.setProperty("config.repo", cloned.getRemoteRepository()); configManager.persistDefaultProperties(); ExecutorService pool = null; if (historyManager == null) { pool = Executors.newSingleThreadExecutor(); historyManager = new HistoryManager(warDir, pool); } try { if (historyManager != null && !hasExisting) { historyManager.logEvent(EntryType.CONFIG, // NOTE: We should integrate the git pointer into this class. new GitLocation(cloned.getRemoteRepository(), cloned.getBranchName(), cloned.getCurrentRevision()), "AUTO", renderedContentDir, "", "Initial config pull.", true, true); } } finally { if (pool != null) { pool.shutdownNow(); } } return cloned; } catch (Throwable e) { cloned.close(); throw new Exception(e); } }
From source file:com.adobe.people.jedelson.aemslack.impl.Notifier.java
@Activate private void activate(ComponentContext ctx) { queue = Executors.newSingleThreadExecutor(); httpClient = new HttpClient(); Dictionary<?, ?> props = ctx.getProperties(); url = PropertiesUtil.toString(props.get(PROP_URL), null); if (url == null) { throw new IllegalArgumentException("URL is not defined"); }//w w w .ja v a 2s . c o m usernameMappings = PropertiesUtil.toMap(props.get(PROP_MAPPING), new String[0]); BundleContext bundleContext = ctx.getBundleContext(); Hashtable<String, Object> serviceProps = new Hashtable<String, Object>(); serviceProps.put(EventConstants.EVENT_TOPIC, CommentingEvent.EVENT_TOPIC_BASE + "/" + CommentingEvent.Type.COMMENTED.name().toLowerCase()); commentListenerRegistration = bundleContext.registerService(EventHandler.class.getName(), new CommentListener(), serviceProps); serviceProps.put(EventConstants.EVENT_TOPIC, TaskEvent.TOPIC); taskListenerRegistration = bundleContext.registerService(EventHandler.class.getName(), new TaskListener(), serviceProps); }
From source file:org.apache.commons.vfs2.util.NHttpServer.java
public boolean run(final int port, final File docRoot, final long waitMillis) throws IOReactorException, InterruptedException { Executors.newSingleThreadExecutor().execute(new Runnable() { @Override/*from w ww .j av a2 s . c o m*/ public void run() { try { NHttpServer.this.runBlock(port, docRoot); } catch (final IOReactorException e) { throw new IllegalStateException(e); } catch (final UnrecoverableKeyException e) { throw new IllegalStateException(e); } catch (final KeyStoreException e) { throw new IllegalStateException(e); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (final CertificateException e) { throw new IllegalStateException(e); } catch (final IOException e) { throw new IllegalStateException(e); } catch (final KeyManagementException e) { throw new IllegalStateException(e); } } }); return this.waitForServerStartup(port, waitMillis); }