下面列出了java.util.concurrent.ForkJoinPool#commonPool ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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.");
}
}
}
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() + " 个任务等待被执行,服务已关闭 ");
}
}
}
@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);
}
/**
* 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;
}
/**
* @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());
}
/**
* 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();
}
/** 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);
}
@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));
}
/**
* 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;
}
@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);
}
/**
* 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();
}
}
/**
* 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);
}
@Override
public ExecutorService getExecutorService() {
ExecutorService executor = executorService;
return executor != null ? executor : ForkJoinPool.commonPool();
}
private static void test1() {
// -Djava.util.concurrent.ForkJoinPool.common.parallelism=5
ForkJoinPool commonPool = ForkJoinPool.commonPool();
System.out.println(commonPool.getParallelism());
}
@Override
public SharedInformerFactory informers() { return new SharedInformerFactory(ForkJoinPool.commonPool(), httpClient, getConfiguration()); }
public ListCursor(@Nonnull List<T> list, byte []continuation) {
this(ForkJoinPool.commonPool(), list, continuation != null ? ByteBuffer.wrap(continuation).getInt() : 0);
}
private NoopBatchWrite(long maxBytes, int maxMessages, Duration maxDelay) {
super(maxBytes, maxMessages, maxDelay, null, ForkJoinPool.commonPool());
}
@NonNull
Executor getExecutor() {
return (executor == null) ? ForkJoinPool.commonPool() : executor;
}
@Override
public void afterPropertiesSet() {
this.forkJoinPool = (this.commonPool ? ForkJoinPool.commonPool() :
new ForkJoinPool(this.parallelism, this.threadFactory, this.uncaughtExceptionHandler, this.asyncMode));
}
/**
* 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);
}