Java Code Examples for java.util.concurrent.ForkJoinPool#commonPool()

The following examples show how to use java.util.concurrent.ForkJoinPool#commonPool() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Chapter07Concurrency04.java    From Java-9-Cookbook with MIT License 6 votes vote down vote up
private static void demo4_Flow_submissionPublisher() {
    System.out.println();

    ExecutorService execService =  ForkJoinPool.commonPool();//Executors.newFixedThreadPool(3);
    try (SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>()){//execService, 1)){
        demoSubscribe(publisher, execService, "One");
        demoSubscribe(publisher, execService, "Two");
        demoSubscribe(publisher, execService, "Three");
        IntStream.range(1, 5).forEach(publisher::submit);
    } finally {
        try {
            execService.shutdown();
            int shutdownDelaySec = 1;
            System.out.println("Waiting for " + shutdownDelaySec + " sec before shutting down service...");
            execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
        } catch (Exception ex) {
            System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
        } finally {
            System.out.println("Calling execService.shutdownNow()...");
            List<Runnable> l = execService.shutdownNow();
            System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
        }

    }

}
 
Example 2
Source File: DockerXDemoApplication.java    From Java-9-Spring-Webflux with Apache License 2.0 6 votes vote down vote up
private static void Flow_customsubmissionPublisher() {
    ExecutorService execService =  ForkJoinPool.commonPool();//Executors.newFixedThreadPool(3);
    try (DockerXDemoPublisher<Integer> publisher = new  DockerXDemoPublisher<>(execService)){
        demoSubscribe(publisher,  "One");
        demoSubscribe(publisher,  "Two");
        demoSubscribe(publisher,  "Three");
        IntStream.range(1, 5).forEach(publisher::submit);
    } finally {
        try {
            execService.shutdown();
            int shutdownDelaySec = 1;
            System.out.println("………………等待 " + shutdownDelaySec + " 秒后结束服务……………… ");
            execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
        } catch (Exception ex) {
            System.out.println("捕获到 execService.awaitTermination()方法的异常: " + ex.getClass().getName());
        } finally {
            System.out.println("调用 execService.shutdownNow()结束服务...");
            List<Runnable> l = execService.shutdownNow();
            System.out.println("还剩 "+l.size() + " 个任务等待被执行,服务已关闭 ");
        }

    }
}
 
Example 3
Source File: ReactorClientStreamObserverAndPublisherTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void multiThreadedProducerTest() {
    ReactorClientStreamObserverAndPublisher<Integer> processor =
            new ReactorClientStreamObserverAndPublisher<>(null);
    int countPerThread = 100000;
    TestCallStreamObserverProducer observer =
        new TestCallStreamObserverProducer(ForkJoinPool.commonPool(), processor, countPerThread);
    processor.beforeStart(observer);
    StepVerifier.create(Flux.from(processor)
                            .subscribeOn(Schedulers.single()))
                .expectNextCount(countPerThread)
                .verifyComplete();

    Assertions.assertThat(observer.requestsQueue.size()).isBetween((countPerThread - DEFAULT_CHUNK_SIZE) / PART_OF_CHUNK + 1, (countPerThread - DEFAULT_CHUNK_SIZE) / PART_OF_CHUNK + 3);
}
 
Example 4
Source File: CompletableFuture.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Null-checks user executor argument, and translates uses of
 * commonPool to asyncPool in case parallelism disabled.
 */
static Executor screenExecutor(Executor e) {
    if (!useCommonPool && e == ForkJoinPool.commonPool())
        return asyncPool;
    if (e == null) throw new NullPointerException();
    return e;
}
 
Example 5
Source File: ThreadPools.java    From cyclops with Apache License 2.0 5 votes vote down vote up
/**
 * @return Standard Parallel Executor, uses the ForkJoin Common Pool is @see {@link ThreadPools#isUseCommon()} is true
 *         Otherwise a new Executor sized to the number of threads is used.
 */
public static Executor getStandard() {
    if (useCommon)
        return ForkJoinPool.commonPool();
    return new ForkJoinPool(
                            Runtime.getRuntime()
                                   .availableProcessors());
}
 
Example 6
Source File: ConfigBase.java    From algoliasearch-client-java-2 with MIT License 5 votes vote down vote up
/**
 * Builds a base configuration
 *
 * @param applicationID The Algolia Application ID
 * @param apiKey The API Key: could be Admin API Key or Search API Key
 * @throws NullPointerException If the ApplicationID or the APIKey or the hosts are null
 * @throws IllegalArgumentException If the ApplicationID or the APIKey are empty
 */
public Builder(
    @Nonnull String applicationID,
    @Nonnull String apiKey,
    @Nonnull List<StatefulHost> defaultHosts,
    @Nonnull CompressionType compressionType) {

  this.applicationID = applicationID;
  this.apiKey = apiKey;

  this.useSystemProxy = false;
  this.batchSize = 1000;
  this.hosts = defaultHosts;
  this.connectTimeOut = Defaults.CONNECT_TIMEOUT_MS;
  this.compressionType = compressionType;

  this.defaultHeaders = new HashMap<>();
  this.defaultHeaders.put(Defaults.ALGOLIA_APPLICATION_HEADER, applicationID);
  this.defaultHeaders.put(Defaults.ALGOLIA_KEY_HEADER, apiKey);
  String clientVersion = this.getClass().getPackage().getImplementationVersion();
  this.defaultHeaders.put(
      Defaults.USER_AGENT_HEADER,
      String.format("Algolia for Java (%s); JVM (%s)", clientVersion, JAVA_VERSION));
  this.defaultHeaders.put(Defaults.ACCEPT_HEADER, Defaults.APPLICATION_JSON);
  this.defaultHeaders.put(Defaults.ACCEPT_ENCODING_HEADER, Defaults.CONTENT_ENCODING_GZIP);

  this.executor = ForkJoinPool.commonPool();
}
 
Example 7
Source File: GcsWriteTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/** Prepare a mock BQ response. */
@Before
public void mockBigQueryResponse() {
  storage = mock(Storage.class);
  output = new Gcs.Write.Ndjson(storage, MAX_BYTES, MAX_MESSAGES, MAX_DELAY, BATCH_KEY_TEMPLATE,
      ForkJoinPool.commonPool(), PubsubMessageToObjectNode.Raw.of(), this::batchCloseHook);
}
 
Example 8
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) {

    System.setProperty("java.util.logging.SimpleFormatter.format",
            "[%1$tT] [%4$-7s] %5$s %n");

    ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();

    Task taskA = new Task("Task-A", new Adder(1));
    Task taskB = new Task("Task-B", new Adder(2), taskA);
    Task taskC = new Task("Task-C", new Adder(3), taskA, taskB);
    Task taskD = new Task("Task-D", new Adder(4), taskA, taskB, taskC);

    logger.info(() -> "Result: " + forkJoinPool.invoke(taskD));
}
 
Example 9
Source File: CompletableFuture.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Null-checks user executor argument, and translates uses of
 * commonPool to asyncPool in case parallelism disabled.
 */
static Executor screenExecutor(Executor e) {
    if (!useCommonPool && e == ForkJoinPool.commonPool())
        return asyncPool;
    if (e == null) throw new NullPointerException();
    return e;
}
 
Example 10
Source File: ObservableTest.java    From Java-programming-methodology-Rxjava-articles with Apache License 2.0 5 votes vote down vote up
@Test
void pool_pushCollectionDANGER() {
    List<Integer> integers = new ArrayList<>();
    integers.add(1);
    integers.add(2);
    integers.add(3);
    ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
    pushCollectionDANGER(integers, forkJoinPool).subscribe(x -> log(x + "我是订阅者1"));
    pushCollectionDANGER(integers, forkJoinPool).subscribe(x -> log(x + "我是订阅者2"));
    sleep(2, TimeUnit.SECONDS);
}
 
Example 11
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * defaultExecutor by default returns the commonPool if
 * it supports more than one thread.
 */
public void testDefaultExecutor() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    Executor e = f.defaultExecutor();
    Executor c = ForkJoinPool.commonPool();
    if (ForkJoinPool.getCommonPoolParallelism() > 1)
        assertSame(e, c);
    else
        assertNotSame(e, c);
}
 
Example 12
Source File: BoundedLocalCache.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/**
 * Performs the maintenance work, blocking until the lock is acquired. Any exception thrown, such
 * as by {@link CacheWriter#delete}, is propagated to the caller.
 *
 * @param task an additional pending task to run, or {@code null} if not present
 */
void performCleanUp(@Nullable Runnable task) {
  evictionLock.lock();
  try {
    maintenance(task);
  } finally {
    evictionLock.unlock();
  }
  if ((drainStatus() == REQUIRED) && (executor == ForkJoinPool.commonPool())) {
    scheduleDrainBuffers();
  }
}
 
Example 13
Source File: ForkJoinPoolFactoryBean.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() {
	this.forkJoinPool = (this.commonPool ? ForkJoinPool.commonPool() :
			new ForkJoinPool(this.parallelism, this.threadFactory, this.uncaughtExceptionHandler, this.asyncMode));
}
 
Example 14
Source File: ArcContainerImpl.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public ExecutorService getExecutorService() {
    ExecutorService executor = executorService;
    return executor != null ? executor : ForkJoinPool.commonPool();
}
 
Example 15
Source File: Caffeine.java    From caffeine with Apache License 2.0 4 votes vote down vote up
@NonNull
Executor getExecutor() {
  return (executor == null) ? ForkJoinPool.commonPool() : executor;
}
 
Example 16
Source File: BatchWriteTest.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
private NoopBatchWrite(long maxBytes, int maxMessages, Duration maxDelay) {
  super(maxBytes, maxMessages, maxDelay, null, ForkJoinPool.commonPool());
}
 
Example 17
Source File: ListCursor.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
public ListCursor(@Nonnull List<T> list, byte []continuation) {
    this(ForkJoinPool.commonPool(), list, continuation != null ? ByteBuffer.wrap(continuation).getInt() : 0);
}
 
Example 18
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public SharedInformerFactory informers() { return new SharedInformerFactory(ForkJoinPool.commonPool(), httpClient, getConfiguration()); }
 
Example 19
Source File: Streams12.java    From java8-tutorial with MIT License 4 votes vote down vote up
private static void test1() {
    // -Djava.util.concurrent.ForkJoinPool.common.parallelism=5

    ForkJoinPool commonPool = ForkJoinPool.commonPool();
    System.out.println(commonPool.getParallelism());
}
 
Example 20
Source File: MiGzOutputStream.java    From migz with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Creates a new MiGzOutputStream that will output MiGz-compressed bytes to the specified underlying
 * outputStream using the default block size.  Worker tasks will execute on the current {@link ForkJoinPool} returned
 * by {@link ForkJoinTask#getPool()} if applicable, or the {@link ForkJoinPool#commonPool()} otherwise.
 *
 * @param outputStream the stream to which compressed bytes will be written
 */
public MiGzOutputStream(OutputStream outputStream) {
  this(outputStream, ForkJoinTask.inForkJoinPool() ? ForkJoinTask.getPool() : ForkJoinPool.commonPool(),
      DEFAULT_BLOCK_SIZE);
}