Tabnine Logo
Executors.newSingleThreadExecutor
Code IndexAdd Tabnine to your IDE (free)

How to use
newSingleThreadExecutor
method
in
java.util.concurrent.Executors

Best Java code snippets using java.util.concurrent.Executors.newSingleThreadExecutor (Showing top 20 results out of 14,769)

Refine searchRefine arrow

  • ExecutorService.submit
  • Future.get
  • ExecutorService.shutdown
  • Test.<init>
  • PrintStream.println
origin: neo4j/neo4j

  @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;
  }
}
origin: skylot/jadx

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;
}
origin: prestodb/presto

@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);
}
origin: stackoverflow.com

 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();
}
origin: ethereum/ethereumj

  @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);
  }

origin: ReactiveX/RxJava

@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();
  }
}
origin: shekhargulati/java8-the-missing-tutorial

  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());
  }
}
origin: LeonardoZ/java-concurrency-patterns

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");
}
origin: org.apache.commons/commons-lang3

/**
 * 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);
  }
}
origin: spring-projects/spring-framework

@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());
}
origin: eclipse-vertx/vert.x

@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());
}
origin: stackoverflow.com

 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();
}
origin: google/guava

ExecutorService executor = newSingleThreadExecutor();
Future<V> waiter =
  executor.submit(
    new Callable<V>() {
     @Override
origin: SonarSource/sonarqube

 @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();
 }
}
origin: reactor/reactor-core

@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();
}
origin: ReactiveX/RxJava

@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();
  }
}
origin: stackoverflow.com

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
origin: LeonardoZ/java-concurrency-patterns

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();
}
origin: eclipse-vertx/vert.x

@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();
 }
}
origin: docker-java/docker-java

  public static <T> Future<Void> startAsyncProcessing(AbstractCallbackNotifier<T> callbackNotifier) {

    ExecutorService executorService = Executors.newSingleThreadExecutor(FACTORY);
    Future<Void> response = executorService.submit(callbackNotifier);
    executorService.shutdown();
    return response;
  }
}
java.util.concurrentExecutorsnewSingleThreadExecutor

Javadoc

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

Popular methods of Executors

  • newFixedThreadPool
    Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue,
  • newCachedThreadPool
    Creates a thread pool that creates new threads as needed, but will reuse previously constructed thre
  • newSingleThreadScheduledExecutor
    Creates a single-threaded executor that can schedule commands to run after a given delay, or to exec
  • newScheduledThreadPool
    Creates a thread pool that can schedule commands to run after a given delay, or to execute periodica
  • defaultThreadFactory
    Returns a default thread factory used to create new threads. This factory creates all new threads us
  • callable
    Returns a Callable object that, when called, runs the given privileged exception action and returns
  • unconfigurableScheduledExecutorService
    Returns an object that delegates all defined ScheduledExecutorService methods to the given executor,
  • unconfigurableExecutorService
    Returns an object that delegates all defined ExecutorService methods to the given executor, but not
  • newWorkStealingPool
    Creates a thread pool that maintains enough threads to support the given parallelism level, and may
  • privilegedThreadFactory
    Legacy security code; do not use.
  • privilegedCallable
    Legacy security code; do not use.
  • privilegedCallableUsingCurrentClassLoader
    Legacy security code; do not use.
  • privilegedCallable,
  • privilegedCallableUsingCurrentClassLoader

Popular in Java

  • Reading from database using SQL prepared statement
  • setRequestProperty (URLConnection)
  • getSharedPreferences (Context)
  • getContentResolver (Context)
  • KeyStore (java.security)
    KeyStore is responsible for maintaining cryptographic keys and their owners. The type of the syste
  • GregorianCalendar (java.util)
    GregorianCalendar is a concrete subclass of Calendarand provides the standard calendar used by most
  • Executors (java.util.concurrent)
    Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory,
  • ReentrantLock (java.util.concurrent.locks)
    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor
  • BoxLayout (javax.swing)
  • Get (org.apache.hadoop.hbase.client)
    Used to perform Get operations on a single row. To get everything for a row, instantiate a Get objec
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now