Search in sources :

Example 41 with Disposable

use of reactor.core.Disposable in project reactor-core by reactor.

the class BoundedElasticSchedulerTest method taskPutInPendingQueueCanBeRemovedOnCancel.

@Test
public void taskPutInPendingQueueCanBeRemovedOnCancel() throws InterruptedException {
    BoundedElasticScheduler boundedElasticScheduler = afterTest.autoDispose(new BoundedElasticScheduler(1, 1, Thread::new, 10));
    boundedElasticScheduler.start();
    Worker worker = afterTest.autoDispose(boundedElasticScheduler.createWorker());
    AtomicBoolean ranTask = new AtomicBoolean();
    CountDownLatch latch = new CountDownLatch(1);
    // block worker
    worker.schedule(() -> {
        try {
            latch.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    // small window to start the first task
    Thread.sleep(10);
    // enqueue task on worker
    Disposable task = worker.schedule(() -> ranTask.set(true));
    assertThat(ranTask).as("is pending execution").isFalse();
    Awaitility.with().pollInterval(50, TimeUnit.MILLISECONDS).await().atMost(100, TimeUnit.MILLISECONDS).untilAsserted(() -> assertThat(boundedElasticScheduler.estimateRemainingTaskCapacity()).as("queue full").isZero());
    task.dispose();
    Awaitility.with().pollInterval(50, TimeUnit.MILLISECONDS).await().atMost(100, TimeUnit.MILLISECONDS).untilAsserted(() -> assertThat(boundedElasticScheduler.estimateRemainingTaskCapacity()).as("queue cleared").isOne());
    latch.countDown();
    Thread.sleep(100);
    assertThat(ranTask).as("not executed after latch countdown").isFalse();
}
Also used : Disposable(reactor.core.Disposable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Worker(reactor.core.scheduler.Scheduler.Worker) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 42 with Disposable

use of reactor.core.Disposable in project reactor-core by reactor.

the class BoundedElasticSchedulerTest method testGh1973.

// gh-1973 smoke test
@Test
@Tag("slow")
public void testGh1973() throws InterruptedException {
    Scheduler scheduler = afterTest.autoDispose(Schedulers.newBoundedElastic(3, 100000, "subscriberElastic", 600, true));
    LinkedList<MonoSink<String>> listeners = new LinkedList<>();
    List<Disposable> scheduled = new LinkedList<>();
    ExecutorService producer = startProducer(listeners);
    Consumer<MonoSink<String>> addListener = sink -> {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            LOGGER.trace("listener cancelled");
        }
        listeners.add(sink);
        sink.onDispose(() -> listeners.remove(sink));
    };
    for (int i = 0; i < 50; i++) {
        scheduled.add(Mono.create(addListener).subscribeOn(scheduler).subscribe(LOGGER::info));
    }
    Thread.sleep(1000);
    scheduled.forEach(Disposable::dispose);
    Thread.sleep(1000);
    Mono.<String>create(sink -> {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            LOGGER.warn("last listener improperly cancelled");
        }
        listeners.add(sink);
        sink.onDispose(() -> listeners.remove(sink));
    }).subscribeOn(scheduler).map(res -> res + " the end").doOnNext(LOGGER::info).as(StepVerifier::create).assertNext(n -> assertThat(n).endsWith(" the end")).expectComplete().verify(Duration.ofSeconds(5));
}
Also used : MonoSink(reactor.core.publisher.MonoSink) Disposable(reactor.core.Disposable) Offset(org.assertj.core.data.Offset) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) AfterAll(org.junit.jupiter.api.AfterAll) BoundedServices(reactor.core.scheduler.BoundedElasticScheduler.BoundedServices) Loggers(reactor.util.Loggers) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Logger(reactor.util.Logger) BoundedState(reactor.core.scheduler.BoundedElasticScheduler.BoundedState) Assertions(org.assertj.core.api.Assertions) Tag(org.junit.jupiter.api.Tag) Disposables(reactor.core.Disposables) AtomicIntegerArray(java.util.concurrent.atomic.AtomicIntegerArray) Set(java.util.Set) Worker(reactor.core.scheduler.Scheduler.Worker) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) ThrowingSupplier(com.pivovarit.function.ThrowingSupplier) Awaitility(org.awaitility.Awaitility) CsvSource(org.junit.jupiter.params.provider.CsvSource) Disposable(reactor.core.Disposable) Scannable(reactor.core.Scannable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MonoSink(reactor.core.publisher.MonoSink) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ThrowingRunnable(com.pivovarit.function.ThrowingRunnable) MockUtils(reactor.test.MockUtils) LinkedList(java.util.LinkedList) RaceTestUtils(reactor.test.util.RaceTestUtils) ExecutorService(java.util.concurrent.ExecutorService) BoundedScheduledExecutorService(reactor.core.scheduler.BoundedElasticScheduler.BoundedScheduledExecutorService) ParameterizedTestWithName(reactor.test.ParameterizedTestWithName) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Flux(reactor.core.publisher.Flux) Clock(java.time.Clock) Comparator(java.util.Comparator) ExecutorService(java.util.concurrent.ExecutorService) BoundedScheduledExecutorService(reactor.core.scheduler.BoundedElasticScheduler.BoundedScheduledExecutorService) LinkedList(java.util.LinkedList) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Example 43 with Disposable

use of reactor.core.Disposable in project reactor-core by reactor.

the class FluxTests method shouldCorrectlyDispatchComplexFlow.

@Test
public void shouldCorrectlyDispatchComplexFlow() throws InterruptedException {
    Sinks.Many<Integer> globalFeed = Sinks.many().multicast().onBackpressureBuffer();
    CountDownLatch afterSubscribe = new CountDownLatch(1);
    CountDownLatch latch = new CountDownLatch(4);
    Flux<Integer> s = Flux.just("2222").map(Integer::parseInt).flatMap(l -> Flux.merge(globalFeed.asFlux().publishOn(asyncGroup), Flux.just(1111, l, 3333, 4444, 5555, 6666)).log("merged").publishOn(asyncGroup).log("dispatched").doOnSubscribe(x -> afterSubscribe.countDown()).filter(nearbyLoc -> 3333 >= nearbyLoc).filter(nearbyLoc -> 2222 <= nearbyLoc));
    /*Disposable action = */
    s.limitRate(1).subscribe(integer -> {
        latch.countDown();
        System.out.println(integer);
    });
    afterSubscribe.await(5, TimeUnit.SECONDS);
    globalFeed.emitNext(2223, FAIL_FAST);
    globalFeed.emitNext(2224, FAIL_FAST);
    latch.await(5, TimeUnit.SECONDS);
    assertThat(latch.getCount()).as("latch count").isEqualTo(0);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Sinks(reactor.core.publisher.Sinks) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) TestLogger(reactor.test.util.TestLogger) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Tuples(reactor.util.function.Tuples) TimeoutException(java.util.concurrent.TimeoutException) Hooks(reactor.core.publisher.Hooks) Timer(java.util.Timer) Disabled(org.junit.jupiter.api.Disabled) CoreSubscriber(reactor.core.CoreSubscriber) Loggers(reactor.util.Loggers) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) Logger(reactor.util.Logger) Tag(org.junit.jupiter.api.Tag) AutoDisposingExtension(reactor.test.AutoDisposingExtension) IdentityHashMap(java.util.IdentityHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Signal(reactor.core.publisher.Signal) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) LockSupport(java.util.concurrent.locks.LockSupport) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Fuseable(reactor.core.Fuseable) Assertions.fail(org.assertj.core.api.Assertions.fail) LoggerUtils(reactor.test.util.LoggerUtils) Exceptions(reactor.core.Exceptions) IntStream(java.util.stream.IntStream) Disposable(reactor.core.Disposable) Scannable(reactor.core.Scannable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Tuple2(reactor.util.function.Tuple2) Callable(java.util.concurrent.Callable) Scheduler(reactor.core.scheduler.Scheduler) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Queues(reactor.util.concurrent.Queues) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Schedulers(reactor.core.scheduler.Schedulers) Operators(reactor.core.publisher.Operators) Semaphore(java.util.concurrent.Semaphore) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Flux(reactor.core.publisher.Flux) FAIL_FAST(reactor.core.publisher.Sinks.EmitFailureHandler.FAIL_FAST) Phaser(java.util.concurrent.Phaser) Subscription(org.reactivestreams.Subscription) AssertSubscriber(reactor.test.subscriber.AssertSubscriber) Comparator(java.util.Comparator) Collections(java.util.Collections) Timeout(org.junit.jupiter.api.Timeout) Sinks(reactor.core.publisher.Sinks) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 44 with Disposable

use of reactor.core.Disposable in project reactor-core by reactor.

the class AbstractSchedulerTest method directScheduleAndDisposePeriod.

@Test
@Timeout(10)
public final void directScheduleAndDisposePeriod() throws Exception {
    Scheduler s = schedulerNotCached();
    try {
        assertThat(s.isDisposed()).isFalse();
        if (!shouldCheckDirectTimeScheduling()) {
            assertThatExceptionOfType(RejectedExecutionException.class).isThrownBy(() -> s.schedule(() -> {
            }, 10, TimeUnit.MILLISECONDS)).as("Scheduler marked as not supporting time scheduling").isSameAs(Exceptions.failWithRejectedNotTimeCapable());
            return;
        }
        CountDownLatch latch = new CountDownLatch(2);
        CountDownLatch latch2 = new CountDownLatch(1);
        Disposable d = s.schedulePeriodically(() -> {
            try {
                latch.countDown();
                if (latch.getCount() == 0) {
                    latch2.await(10, TimeUnit.SECONDS);
                }
            } catch (InterruptedException e) {
            }
        }, 10, 10, TimeUnit.MILLISECONDS);
        // will throw if rejected
        assertThat(d.isDisposed()).isFalse();
        latch.await();
        d.dispose();
        Thread.yield();
        latch2.countDown();
        s.dispose();
        assertThat(s.isDisposed()).isTrue();
        assertThatExceptionOfType(RejectedExecutionException.class).isThrownBy(() -> s.schedule(() -> {
        }));
    } finally {
        s.dispose();
    }
}
Also used : Disposable(reactor.core.Disposable) CountDownLatch(java.util.concurrent.CountDownLatch) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 45 with Disposable

use of reactor.core.Disposable in project reactor-core by reactor.

the class AbstractSchedulerTest method directScheduleAndDispose.

@Test
@Timeout(10)
public final void directScheduleAndDispose() throws Exception {
    Scheduler s = schedulerNotCached();
    try {
        assertThat(s.isDisposed()).isFalse();
        CountDownLatch latch = new CountDownLatch(1);
        CountDownLatch latch2 = shouldCheckDisposeTask() ? new CountDownLatch(1) : null;
        try {
            Disposable d = s.schedule(() -> {
                try {
                    latch.countDown();
                    if (latch2 != null && !latch2.await(10, TimeUnit.SECONDS) && shouldCheckInterrupted()) {
                        fail("Should have interrupted");
                    }
                } catch (InterruptedException e) {
                }
            });
            latch.await();
            if (shouldCheckDisposeTask()) {
                assertThat(d.isDisposed()).isFalse();
            } else {
                // noop
                d.isDisposed();
            }
            d.dispose();
            // noop
            d.dispose();
        } catch (Throwable schedulingError) {
            fail("unexpected scheduling error", schedulingError);
        }
        Thread.yield();
        if (latch2 != null) {
            latch2.countDown();
        }
        s.dispose();
        // noop
        s.dispose();
        if (s == ImmediateScheduler.instance()) {
            return;
        }
        assertThat(s.isDisposed()).isTrue();
        try {
            Disposable d = s.schedule(() -> {
                if (shouldCheckInterrupted()) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            });
            d.dispose();
            assertThat(d.isDisposed()).isTrue();
        } catch (Throwable schedulingError) {
            assertThat(schedulingError).isInstanceOf(RejectedExecutionException.class);
        }
    } finally {
        s.dispose();
        // noop
        s.dispose();
    }
}
Also used : Disposable(reactor.core.Disposable) CountDownLatch(java.util.concurrent.CountDownLatch) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Aggregations

Disposable (reactor.core.Disposable)120 Test (org.junit.jupiter.api.Test)101 CountDownLatch (java.util.concurrent.CountDownLatch)33 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)32 StepVerifier (reactor.test.StepVerifier)29 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)25 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 Duration (java.time.Duration)15 List (java.util.List)15 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)15 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 Subscription (org.reactivestreams.Subscription)15 TimeUnit (java.util.concurrent.TimeUnit)14 Timeout (org.junit.jupiter.api.Timeout)13 CoreSubscriber (reactor.core.CoreSubscriber)12 ArrayList (java.util.ArrayList)11 Arrays (java.util.Arrays)11 Disabled (org.junit.jupiter.api.Disabled)11 Scannable (reactor.core.Scannable)11 Fuseable (reactor.core.Fuseable)10