Java Code Examples for reactor.core.Disposable#Composite

The following examples show how to use reactor.core.Disposable#Composite . 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: SchedulersTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testWorkerScheduleSupportZeroPeriod() throws InterruptedException {
	try(TaskCheckingScheduledExecutor executorService = new TaskCheckingScheduledExecutor()) {
		CountDownLatch latch = new CountDownLatch(2);
		Disposable.Composite tasks = Disposables.composite();
		Disposable disposable = Schedulers.workerSchedulePeriodically(executorService, tasks,
				latch::countDown, 0, 0, TimeUnit.MILLISECONDS);
		latch.await();

		disposable.dispose();

		Thread.sleep(100);

		int tasksBefore = executorService.tasks.size();

		Thread.sleep(100);

		int tasksAfter = executorService.tasks.size();

		assertThat(tasksAfter).isEqualTo(tasksBefore);
		assertThat(tasks.size()).isEqualTo(0);
	}
}
 
Example 2
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void runFuture() {
	for (int i = 0; i < RACE_DEFAULT_LOOPS; i++) {
		Disposable.Composite set = Disposables.composite();
		final WorkerTask run = new WorkerTask(() -> {}, set);
		set.add(run);

		final FutureTask<Void> ft = new FutureTask<>(() -> {
		}, null);

		Runnable r1 = run::call;

		Runnable r2 = () -> run.setFuture(ft);

		RaceTestUtils.race(r1, r2);
	}
}
 
Example 3
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void pluginCrash() {
	Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
		throw new IllegalStateException("Second");
	});

	Disposable.Composite set = Disposables.composite();
	final WorkerTask run = new WorkerTask(() -> {
		throw new IllegalStateException("First");
	}, set);
	set.add(run);

	try {
		run.run();

		fail("Should have thrown!");
	} catch (IllegalStateException ex) {
		assertThat(ex).hasMessage("Second");
	} finally {
		Thread.currentThread().setUncaughtExceptionHandler(null);
	}
	assertThat(run.isDisposed()).as("isDisposed").isTrue();

	assertThat(set.size()).isZero();
}
 
Example 4
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void runDispose() {
	for (int i = 0; i < RACE_DEFAULT_LOOPS; i++) {
		Disposable.Composite set = Disposables.composite();
		final WorkerTask run = new WorkerTask(() -> {}, set);
		set.add(run);

		Runnable r1 = run::call;

		Runnable r2 = run::dispose;

		RaceTestUtils.race(r1, r2);

		assertThat(set.size()).isZero();
	}
}
 
Example 5
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void setFutureRunRace() {
	for (int i = 0; i < RACE_DEFAULT_LOOPS; i++) {
		Disposable.Composite set = Disposables.composite();
		final WorkerTask run = new WorkerTask(() -> {}, set);
		set.add(run);

		final FutureTask<Object> ft = new FutureTask<>(() -> {
		}, 0);

		Runnable r1 = () -> run.setFuture(ft);

		Runnable r2 = run::run;

		RaceTestUtils.race(r1, r2);

		assertThat(set.size()).isZero();
	}
}
 
Example 6
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void setFutureCancelRace() {
	for (int i = 0; i < RACE_DEFAULT_LOOPS; i++) {
		Disposable.Composite set = Disposables.composite();
		final WorkerTask run = new WorkerTask(() -> {}, set);
		set.add(run);

		final FutureTask<Object> ft = new FutureTask<>(() -> {
		}, 0);

		Runnable r1 = () -> run.setFuture(ft);

		Runnable r2 = run::dispose;

		RaceTestUtils.race(r1, r2);

		assertThat(set.size()).isZero();
	}
}
 
Example 7
Source File: InstantPeriodicWorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void firstCancelRace() {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Disposable.Composite composit = Disposables.composite();

    try {
        for (int i = 0; i < 10000; i++) {
            final InstantPeriodicWorkerTask task = new InstantPeriodicWorkerTask(errorRunnable, exec, composit);

            final FutureTask<Void>
              f1 = new FutureTask<Void>(emptyRunnable, null);
            Runnable r1 = () -> task.setFirst(f1);
            Runnable r2 = task::dispose;

            RaceTestUtils.race(r1, r2);

            assertTrue(f1.isCancelled());
            assertTrue(task.isDisposed());
        }
    }
    finally {
        exec.shutdownNow();
        Schedulers.resetOnHandleError();
    }
}
 
Example 8
Source File: InstantPeriodicWorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void dispose() {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Disposable.Composite composit = Disposables.composite();

    try {
        InstantPeriodicWorkerTask task = new InstantPeriodicWorkerTask(errorRunnable, exec, composit);

        assertThat(task.isDisposed()).isFalse();

        task.dispose();

        assertThat(task.isDisposed()).isTrue();

        task.dispose();

        assertThat(task.isDisposed()).isTrue();
    }
    finally {
        exec.shutdownNow();
        Schedulers.resetOnHandleError();
    }
}
 
Example 9
Source File: SchedulersTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testWorkerScheduleRejectedWithDisposedParent() {
	try(TaskCheckingScheduledExecutor executorService = new TaskCheckingScheduledExecutor()) {
		Disposable.Composite tasks = Disposables.composite();
		tasks.dispose();

		assertThatExceptionOfType(RejectedExecutionException.class)
				.as("zero period, zero delay")
				.isThrownBy(() -> Schedulers.workerSchedulePeriodically(executorService, tasks, () -> {}, 0, 0, TimeUnit.MILLISECONDS));

		assertThatExceptionOfType(RejectedExecutionException.class)
				.as("zero period, some delay")
				.isThrownBy(() -> Schedulers.workerSchedulePeriodically(executorService, tasks, () -> {}, 10, 0, TimeUnit.MILLISECONDS));

		assertThatExceptionOfType(RejectedExecutionException.class)
				.as("periodic, zero delay")
				.isThrownBy(() -> Schedulers.workerSchedulePeriodically(executorService, tasks, () -> {}, 0, 10, TimeUnit.MILLISECONDS));

		assertThatExceptionOfType(RejectedExecutionException.class)
				.as("periodic, some delay")
				.isThrownBy(() -> Schedulers.workerSchedulePeriodically(executorService, tasks, () -> {}, 10, 10, TimeUnit.MILLISECONDS));

		assertThat(executorService.tasks).isEmpty();
	}
}
 
Example 10
Source File: InstantPeriodicWorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void dispose2() {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Disposable.Composite composit = Disposables.composite();

    try {
        InstantPeriodicWorkerTask task = new InstantPeriodicWorkerTask(errorRunnable, exec, composit);

        task.setFirst(new FutureTask<Void>(emptyRunnable, null));
        task.setRest(new FutureTask<Void>(emptyRunnable, null));

        assertThat(task.isDisposed()).isFalse();

        task.dispose();

        assertThat(task.isDisposed()).isTrue();

        task.dispose();

        assertThat(task.isDisposed()).isTrue();
    }
    finally {
        exec.shutdownNow();
        Schedulers.resetOnHandleError();
    }
}
 
Example 11
Source File: InstantPeriodicWorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void dispose3() {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Disposable.Composite composit = Disposables.composite();

    try {
        InstantPeriodicWorkerTask task = new InstantPeriodicWorkerTask(errorRunnable, exec, composit);

        task.dispose();

        FutureTask<Void> f1 = new FutureTask<Void>(emptyRunnable, null);
        task.setFirst(f1);

        assertThat(f1.isCancelled()).isTrue();

        FutureTask<Void> f2 = new FutureTask<Void>(emptyRunnable, null);
        task.setRest(f2);

        assertThat(f2.isCancelled()).isTrue();
    }
    finally {
        exec.shutdownNow();
        Schedulers.resetOnHandleError();
    }
}
 
Example 12
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void disposeRun() {
	Disposable.Composite set = Disposables.composite();
	WorkerTask run = new WorkerTask(() -> {}, set);
	set.add(run);

	assertThat(run.isDisposed()).isFalse();

	run.dispose();
	run.dispose();

	assertThat(run.isDisposed()).isTrue();
}
 
Example 13
Source File: Schedulers.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
static Disposable workerSchedule(ScheduledExecutorService exec,
		Disposable.Composite tasks,
		Runnable task,
		long delay,
		TimeUnit unit) {
	task = onSchedule(task);

	WorkerTask sr = new WorkerTask(task, tasks);
	if (!tasks.add(sr)) {
		throw Exceptions.failWithRejected();
	}

	try {
		Future<?> f;
		if (delay <= 0L) {
			f = exec.submit((Callable<?>) sr);
		}
		else {
			f = exec.schedule((Callable<?>) sr, delay, unit);
		}
		sr.setFuture(f);
	}
	catch (RejectedExecutionException ex) {
		sr.dispose();
		//RejectedExecutionException are propagated up
		throw ex;
	}

	return sr;
}
 
Example 14
Source File: SchedulersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkerScheduleSupportZeroPeriodWithDelayPeriod() {
	try(TaskCheckingScheduledExecutor executorService = new TaskCheckingScheduledExecutor()) {
		Disposable.Composite tasks = Disposables.composite();
		Disposable disposable = Schedulers.workerSchedulePeriodically(executorService, tasks,
				() -> { }, 1000, 0, TimeUnit.MILLISECONDS);

		disposable.dispose();

		assertThat(executorService.isAllTasksCancelled()).isTrue();
	}
}
 
Example 15
Source File: InstantPeriodicWorkerTaskTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void disposeOnCurrentThread() {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Disposable.Composite composit = Disposables.composite();

    try {
        InstantPeriodicWorkerTask task = new InstantPeriodicWorkerTask(errorRunnable, exec, composit);

        task.thread = Thread.currentThread();

        task.dispose();

        FutureTask<Void> f1 = new FutureTask<Void>(emptyRunnable, null);
        task.setFirst(f1);

        assertThat(f1.isCancelled()).isTrue();

        FutureTask<Void> f2 = new FutureTask<Void>(emptyRunnable, null);
        task.setRest(f2);

        assertThat(f2.isCancelled()).isTrue();
    }
    finally {
        exec.shutdownNow();
        Schedulers.resetOnHandleError();
    }
}
 
Example 16
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void withParentIsDisposed() {
	Disposable.Composite set = Disposables.composite();
	WorkerTask run = new WorkerTask(() -> {}, set);
	set.add(run);

	assertThat(run.isDisposed()).as("not yet disposed").isFalse();

	run.run();
	assertThat(run.isDisposed()).as("isDisposed").isTrue();

	assertThat(set.remove(run)).isFalse();
}
 
Example 17
Source File: SchedulersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkerSchedulePeriodicallyCancelsSchedulerTask() throws Exception {
	try(TaskCheckingScheduledExecutor executorService = new TaskCheckingScheduledExecutor()) {
		AtomicInteger zeroDelayZeroPeriod = new AtomicInteger();
		AtomicInteger zeroPeriod = new AtomicInteger();
		AtomicInteger zeroDelayPeriodic = new AtomicInteger();
		AtomicInteger periodic = new AtomicInteger();

		Disposable.Composite tasks = Disposables.composite();

		Schedulers.workerSchedulePeriodically(executorService, tasks,
				() -> zeroDelayZeroPeriod.incrementAndGet(), 0, 0, TimeUnit.MINUTES);

		Schedulers.workerSchedulePeriodically(executorService, tasks,
				() -> zeroPeriod.incrementAndGet(), 1, 0, TimeUnit.MINUTES);

		Schedulers.workerSchedulePeriodically(executorService, tasks,
				() -> zeroDelayPeriodic.incrementAndGet(), 0, 1, TimeUnit.MINUTES);

		Schedulers.workerSchedulePeriodically(executorService, tasks,
				() -> periodic.incrementAndGet(), 1, 1, TimeUnit.MINUTES);

		Thread.sleep(100);
		tasks.dispose();

		await().atMost(50, TimeUnit.MILLISECONDS)
		       .pollInterval(10, TimeUnit.MILLISECONDS)
		       .alias("all tasks cancelled or done")
		       .until(executorService::isAllTasksCancelledOrDone);

		//when no initial delay, the periodic task(s) have time to be schedule. A 0 period results in a lot of schedules
		assertThat(zeroDelayZeroPeriod).as("zeroDelayZeroPeriod").hasPositiveValue();
		assertThat(zeroDelayPeriodic).as("zeroDelayPeriodic").hasValue(1);
		//the below have initial delays and as such shouldn't have had time to schedule
		assertThat(zeroPeriod).as("zeroDelayPeriodic").hasValue(0);
		assertThat(periodic).as("periodic").hasValue(0);
	}
}
 
Example 18
Source File: CommonPoolTest.java    From reactor-pool with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("allPools")
void pendingLimitSync(Function<PoolBuilder<Integer, ?>, AbstractPool<Integer>> configAdjuster) {
	AtomicInteger allocatorCount = new AtomicInteger();
	Disposable.Composite composite = Disposables.composite();

	try {
		PoolBuilder<Integer, ?> builder = PoolBuilder.from(Mono.fromCallable(allocatorCount::incrementAndGet))
		                                             .sizeBetween(1, 1)
		                                             .maxPendingAcquire(1);
		AbstractPool<Integer> pool = configAdjuster.apply(builder);
		pool.warmup().block();
		PooledRef<Integer> hold = pool.acquire().block();

		AtomicReference<Throwable> error = new AtomicReference<>();
		AtomicInteger errorCount = new AtomicInteger();
		AtomicInteger otherTerminationCount = new AtomicInteger();

		for (int i = 0; i < 2; i++) {
			composite.add(
					pool.acquire()
					    .doFinally(fin -> {
						    if (SignalType.ON_ERROR == fin) errorCount.incrementAndGet();
						    else otherTerminationCount.incrementAndGet();
					    })
					    .doOnError(error::set)
					    .subscribe()
			);
		}

		assertThat(AbstractPool.PENDING_COUNT.get(pool)).as("pending counter limited to 1").isEqualTo(1);

		assertThat(errorCount).as("immediate error of extraneous pending").hasValue(1);
		assertThat(otherTerminationCount).as("no other immediate termination").hasValue(0);
		assertThat(error.get()).as("extraneous pending error")
		                       .isInstanceOf(PoolAcquirePendingLimitException.class)
		                       .hasMessage("Pending acquire queue has reached its maximum size of 1");

		hold.release().block();

		assertThat(errorCount).as("error count stable after release").hasValue(1);
		assertThat(otherTerminationCount).as("pending succeeds after release").hasValue(1);
	}
	finally {
		composite.dispose();
	}
}
 
Example 19
Source File: ReactorQLTaskExecutorProvider.java    From jetlinks-community with Apache License 2.0 4 votes vote down vote up
@Override
protected Disposable doStart() {
    Disposable.Composite composite = Disposables.composite();
    Flux<Map<String, Object>> dataStream;
    //有上游节点
    if (!CollectionUtils.isEmpty(context.getJob().getInputs())) {

        dataStream = context.getInput()
            .accept()
            .map(RuleDataHelper::toContextMap)
            .as(reactorQL::start)
        ;
    } else {
        dataStream = reactorQL
            .start(table -> {
                if (table == null || table.equalsIgnoreCase("dual")) {
                    return Flux.just(1);
                }
                if (table.startsWith("/")) {
                    //转换为消息
                    return messageGateway
                        .subscribe(
                            Collections.singleton(new Subscription(table)),
                            "rule-engine:".concat(context.getInstanceId()),
                            false)
                        .map(TopicMessage::convertMessage);
                }
                return Flux.just(1);
            });
    }

    return dataStream
        .flatMap(result -> {
            RuleData data = context.newRuleData(result);
            //输出到下一节点
            return context.getOutput()
                .write(Mono.just(data))
                .then(context.fireEvent(RuleConstants.Event.result, data));
        })
        .onErrorResume(err -> context.onError(err, null))
        .subscribe();
}
 
Example 20
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void syncWorkerCancelRace() {
	for (int i = 0; i < RACE_DEFAULT_LOOPS; i++) {
		final Disposable.Composite set = Disposables.composite();
		final AtomicBoolean interrupted = new AtomicBoolean();
		final AtomicInteger sync = new AtomicInteger(2);
		final AtomicInteger syncb = new AtomicInteger(2);

		Runnable r0 = () -> {
			set.dispose();
			if (sync.decrementAndGet() != 0) {
				while (sync.get() != 0) { }
			}
			if (syncb.decrementAndGet() != 0) {
				while (syncb.get() != 0) { }
			}
			for (int j = 0; j < 1000; j++) {
				if (Thread.currentThread().isInterrupted()) {
					interrupted.set(true);
					break;
				}
			}
		};

		final WorkerTask run = new WorkerTask(r0, set);
		set.add(run);

		final FutureTask<Void> ft = new FutureTask<>(run, null);

		Runnable r2 = () -> {
			if (sync.decrementAndGet() != 0) {
				while (sync.get() != 0) { }
			}
			run.setFuture(ft);
			if (syncb.decrementAndGet() != 0) {
				while (syncb.get() != 0) { }
			}
		};

		RaceTestUtils.race(ft, r2);

		assertThat(interrupted.get()).as("The task was interrupted").isFalse();
	}
}