@Deprecated public static <T> Future<T> future( final Callable<T> task ) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<T> future = executor.submit( task ); executor.shutdown(); return future; } }
public synchronized Future<Boolean> process() { if (future != null) { return future; } ExecutorService shutdownExecutor = Executors.newSingleThreadExecutor(); FutureTask<Boolean> task = new ShutdownTask(); shutdownExecutor.execute(task); shutdownExecutor.shutdown(); future = task; return future; }
@PostConstruct public synchronized void start() { if (finalizerTask != null) { return; } if (executor == null) { executor = newSingleThreadExecutor(daemonThreadsNamed("FinalizerService")); } if (executor.isShutdown()) { throw new IllegalStateException("Finalizer service has been destroyed"); } finalizerTask = executor.submit(this::processFinalizerQueue); }
ExecutorService service = Executors.newSingleThreadExecutor(); try { Runnable r = new Runnable() { @Override public void run() { // Database task } }; Future<?> f = service.submit(r); f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes } catch (final InterruptedException e) { // The thread was interrupted during sleep, wait or join } catch (final TimeoutException e) { // Took too long! } catch (final ExecutionException e) { // An exception from within the Runnable task } finally { service.shutdown(); }
@Test public void interruptTest() throws InterruptedException { ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); final ListenableFuture<Object> future = executor.submit(() -> { // try { System.out.println("Waiting"); Thread.sleep(10000); System.out.println("Complete"); return null; // } catch (Exception e) { // e.printStackTrace(); // throw e; // } }); future.addListener(() -> { System.out.println("Listener: " + future.isCancelled() + ", " + future.isDone()); try { future.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } }, MoreExecutors.directExecutor()); Thread.sleep(1000); future.cancel(true); }
@Test public void disposeRace() { ExecutorService exec = Executors.newSingleThreadExecutor(); final Scheduler s = Schedulers.from(exec); try { for (int i = 0; i < 500; i++) { final Worker w = s.createWorker(); final AtomicInteger c = new AtomicInteger(2); w.schedule(new Runnable() { @Override public void run() { c.decrementAndGet(); while (c.get() != 0) { } } }); c.decrementAndGet(); while (c.get() != 0) { } w.dispose(); } } finally { exec.shutdownNow(); } }
public static void main(String[] args) { CompletableFuture.completedFuture("hello"); CompletableFuture.runAsync(() -> System.out.println("hello")); CompletableFuture.runAsync(() -> System.out.println("hello"), Executors.newSingleThreadExecutor()); CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString()); CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString(), Executors.newSingleThreadExecutor()); } }
public static void usingSingleThreadExecutor() { System.out.println("=== SingleThreadExecutor ==="); ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); singleThreadExecutor.execute(() -> System.out.println("Print this.")); singleThreadExecutor.execute(() -> System.out.println("and this one to.")); singleThreadExecutor.shutdown(); try { singleThreadExecutor.awaitTermination(4, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("\n\n"); }
/** * Tries to pass a null Callable to the constructor that takes an executor. * This should cause an exception. */ @Test(expected=IllegalArgumentException.class) public void testInitExecutorNullCallable() throws InterruptedException { final ExecutorService exec = Executors.newSingleThreadExecutor(); try { new CallableBackgroundInitializer<Integer>(null, exec); } finally { exec.shutdown(); exec.awaitTermination(1, TimeUnit.SECONDS); } }
@Test public void closeStatusChangesToSessionNotReliable() throws Exception { BlockingSession session = new BlockingSession(); session.setId("123"); session.setOpen(true); CountDownLatch sentMessageLatch = session.getSentMessageLatch(); int sendTimeLimit = 100; int bufferSizeLimit = 1024; final ConcurrentWebSocketSessionDecorator decorator = new ConcurrentWebSocketSessionDecorator(session, sendTimeLimit, bufferSizeLimit); Executors.newSingleThreadExecutor().submit((Runnable) () -> { TextMessage message = new TextMessage("slow message"); try { decorator.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } }); assertTrue(sentMessageLatch.await(5, TimeUnit.SECONDS)); // ensure some send time elapses Thread.sleep(sendTimeLimit + 100); decorator.close(CloseStatus.PROTOCOL_ERROR); assertEquals("CloseStatus should have changed to SESSION_NOT_RELIABLE", CloseStatus.SESSION_NOT_RELIABLE, session.getCloseStatus()); }
@Test public void testExecuteFromIOWorkerFromNonVertxThread() { assertEquals("true", System.getProperty("vertx.threadChecks")); ExecutorService a = Executors.newSingleThreadExecutor(); ContextInternal ctx = ((VertxInternal) vertx).createWorkerContext(null, new WorkerPool(a, null), null, Thread.currentThread().getContextClassLoader()); AtomicBoolean called = new AtomicBoolean(); try { ctx.executeFromIO(v -> { called.set(true); }); fail(); } catch (IllegalStateException ignore) { // } assertFalse(called.get()); }
ExecutorService executor = Executors.newSingleThreadExecutor(); Runnable task = new Runnable() { public void run() { throw new RuntimeException("foo"); } }; Future<?> future = executor.submit(task); try { future.get(); } catch (ExecutionException e) { Exception rootException = e.getCause(); }
ExecutorService executor = newSingleThreadExecutor(); Future<V> waiter = executor.submit( new Callable<V>() { @Override
@Override public void run() { ExecutorService executor = Executors.newSingleThreadExecutor(); try { Future future = executor.submit(monitored::stop); future.get(terminationTimeoutMs, TimeUnit.MILLISECONDS); } catch (Exception e) { LoggerFactory.getLogger(getClass()).error("Can not stop in {}ms", terminationTimeoutMs, e); } executor.shutdownNow(); commands.endWatch(); } }
@Test public void handleErrorWithJvmFatalForwardsToUncaughtHandlerFusedCallable() { AtomicBoolean handlerCaught = new AtomicBoolean(); Scheduler scheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(r -> { Thread thread = new Thread(r); thread.setUncaughtExceptionHandler((t, ex) -> { handlerCaught.set(true); System.err.println("from uncaught handler: " + ex.toString()); }); return thread; })); final StepVerifier stepVerifier = StepVerifier.create(Mono.<String>fromCallable(() -> { throw new StackOverflowError("boom"); }).subscribeOn(scheduler)) .expectFusion() .expectErrorMessage("boom"); //the exception is still fatal, so the StepVerifier should time out. assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> stepVerifier.verify(Duration.ofMillis(100))) .withMessageStartingWith("VerifySubscriber timed out on "); //nonetheless, the uncaught exception handler should have been invoked assertThat(handlerCaught).as("uncaughtExceptionHandler used").isTrue(); }
@Test public void disposeRace() { ExecutorService exec = Executors.newSingleThreadExecutor(); final Scheduler s = Schedulers.from(exec, true); try { for (int i = 0; i < 500; i++) { final Worker w = s.createWorker(); final AtomicInteger c = new AtomicInteger(2); w.schedule(new Runnable() { @Override public void run() { c.decrementAndGet(); while (c.get() != 0) { } } }); c.decrementAndGet(); while (c.get() != 0) { } w.dispose(); } } finally { exec.shutdownNow(); } }
ExecutorService exec = Executors.newSingleThreadExecutor(); CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new MySupplier(), exec); System.out.println(f.isDone()); // False CompletableFuture<Integer> f2 = f.thenApply(new PlusOne()); System.out.println(f2.get()); // Waits until the "calculation" is done, then prints 2
public static void main(String[] args) { Callable<Integer> callable = () -> { int random = new Random().nextInt(10) * 100; System.out.println("Preparing to execute"); Thread.sleep(random); System.out.println("Executed - " + random); return random; }; FutureTask<Integer> futureTask = new FutureTask<>(callable); ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(futureTask); try { Integer value = futureTask.get(2, TimeUnit.SECONDS); System.out.println("Value is " + value); } catch (InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); } executor.shutdown(); }
@Test public void testDeliverPausedBufferWhenResumeOnOtherThread() throws Exception { ExecutorService exec = Executors.newSingleThreadExecutor(); try { testDeliverPausedBufferWhenResume(block -> exec.execute(() -> { try { Thread.sleep(10); } catch (InterruptedException e) { fail(e); Thread.currentThread().interrupt(); } block.run(); })); } finally { exec.shutdown(); } }
public static <T> Future<Void> startAsyncProcessing(AbstractCallbackNotifier<T> callbackNotifier) { ExecutorService executorService = Executors.newSingleThreadExecutor(FACTORY); Future<Void> response = executorService.submit(callbackNotifier); executorService.shutdown(); return response; } }