reactor.core.Disposable Java Examples

The following examples show how to use reactor.core.Disposable. 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: SerialTaskManagerWorker.java    From james-project with Apache License 2.0 7 votes vote down vote up
@Override
public Mono<Task.Result> executeTask(TaskWithId taskWithId) {
    if (!cancelledTasks.remove(taskWithId.getId())) {
        Mono<Task.Result> taskMono = Mono.fromCallable(() -> runWithMdc(taskWithId, listener)).subscribeOn(taskExecutor);
        CompletableFuture<Task.Result> future = taskMono.toFuture();
        runningTask.set(Tuples.of(taskWithId.getId(), future));

        return Mono.using(
            () -> pollAdditionalInformation(taskWithId).subscribe(),
            ignored -> Mono.fromFuture(future)
                .onErrorResume(exception -> Mono.from(handleExecutionError(taskWithId, listener, exception))
                        .thenReturn(Task.Result.PARTIAL)),
            Disposable::dispose);
    } else {
        return Mono.from(listener.cancelled(taskWithId.getId(), taskWithId.getTask().details()))
            .then(Mono.empty());
    }
}
 
Example #2
Source File: VirtualTimeScheduler.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public Disposable schedulePeriodically(Runnable task,
		long initialDelay,
		long period,
		TimeUnit unit) {
	final long periodInNanoseconds = unit.toNanos(period);
	final long firstNowNanoseconds = nanoTime;
	final long firstStartInNanoseconds = firstNowNanoseconds + unit.toNanos(initialDelay);

	PeriodicTask periodicTask = new PeriodicTask(firstStartInNanoseconds, task,
			firstNowNanoseconds,
			periodInNanoseconds);

	replace(periodicTask, schedule(periodicTask, initialDelay, unit));
	return periodicTask;
}
 
Example #3
Source File: FluxReplayTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void cancel() {
	ConnectableFlux<Integer> replay = Processors.<Integer>unicast().replay(2);

	replay.subscribe(v -> {}, e -> { throw Exceptions.propagate(e); });

	Disposable connected = replay.connect();

	//the lambda subscriber itself is cancelled so it will bubble the exception
	//propagated by connect().dispose()
	assertThatExceptionOfType(RuntimeException.class)
			.isThrownBy(connected::dispose)
            .withMessage("Disconnected");

	boolean cancelled = ((FluxReplay.ReplaySubscriber) connected).cancelled;
	assertThat(cancelled).isTrue();
}
 
Example #4
Source File: InstantPeriodicWorkerTaskTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void restCancelRace() {
    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.setRest(f1);
            Runnable r2 = task::dispose;

            RaceTestUtils.race(r1, r2);

            assertTrue(f1.isCancelled());
            assertTrue(task.isDisposed());
        }
    }
    finally {
        exec.shutdownNow();
        Schedulers.resetOnHandleError();
    }
}
 
Example #5
Source File: MessageGatewayRuleNode.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@Override
protected Disposable doStart() {
    if (config.getType() == PubSubType.producer) {
        return super.doStart();
    }

    //订阅网关中的消息
    return gatewayManager
        .getGateway(config.getGatewayId())
        .switchIfEmpty(Mono.fromRunnable(() -> context.getLogger().error("消息网关[{" + config.getGatewayId() + "}]不存在")))
        .flatMapMany(gateway -> gateway.subscribe(config.createTopics()))
        .map(config::convert)
        .flatMap(data -> context.getOutput().write(Mono.just(RuleData.create(data))))
        .onErrorContinue((err, obj) -> {
            context.getLogger().error(err.getMessage(), err);
        })
        .subscribe();
}
 
Example #6
Source File: LocalSchedulerTransactionLogger.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
static Disposable logEvents(LocalScheduler localScheduler) {
    return localScheduler.events()
            .retryWhen(error -> Flux.just(1).delayElements(RETRY_DELAY))
            .subscribe(
                    event -> {
                        boolean failure = event.getSchedule().getCurrentAction().getStatus().getError().isPresent();
                        if (failure) {
                            logger.info(doFormat(event));
                        } else {
                            logger.debug(doFormat(event));
                        }
                    },
                    e -> logger.error("Event stream terminated with an error", e),
                    () -> logger.info("Event stream completed")
            );
}
 
Example #7
Source File: BoundedElasticSchedulerTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void estimateRemainingTaskCapacityResetWhenWorkerTaskIsExecuted()
		throws InterruptedException {
	BoundedElasticScheduler boundedElasticScheduler = afterTest.autoDispose(new BoundedElasticScheduler(1, 1, Thread::new, 10));
	Worker worker = afterTest.autoDispose(boundedElasticScheduler.createWorker());
	CountDownLatch latch = new CountDownLatch(1);
	AtomicBoolean taskRan = new AtomicBoolean();
	//occupy the scheduler
	worker.schedule(() -> {
		try {
			latch.await();
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	});
	Thread.sleep(10); //small window to start the first task
	//enqueue task on worker
	Disposable task = worker.schedule(() -> taskRan.set(true));

	assertThat(boundedElasticScheduler.estimateRemainingTaskCapacity()).as("capacity when running").isZero();
	latch.countDown();
	Awaitility.await().untilTrue(taskRan);
	assertThat(boundedElasticScheduler.estimateRemainingTaskCapacity()).as("capacity after run").isOne();
}
 
Example #8
Source File: ReactorNettyClient.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> sendOnly(SendOnlyMessage message) {
    requireNonNull(message, "message must not be null");

    return Mono.<Mono<Void>>create(sink -> {
        if (!isConnected()) {
            if (message instanceof Disposable) {
                ((Disposable) message).dispose();
            }
            sink.error(new IllegalStateException("Cannot send messages because the connection is closed"));
            return;
        }

        requestQueue.submit(RequestTask.wrap(message, sink, () -> send(message).doOnTerminate(requestQueue)));
    }).flatMap(identity());
}
 
Example #9
Source File: FluxCreate.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public final FluxSink<T> onCancel(Disposable d) {
	Objects.requireNonNull(d, "onCancel");
	SinkDisposable sd = new SinkDisposable(null, d);
	if (!DISPOSABLE.compareAndSet(this, null, sd)) {
		Disposable c = disposable;
		if (c == CANCELLED) {
			d.dispose();
		}
		else if (c instanceof SinkDisposable) {
			SinkDisposable current = (SinkDisposable) c;
			if (current.onCancel == null) {
				current.onCancel = d;
			}
			else {
				d.dispose();
			}
		}
	}
	return this;
}
 
Example #10
Source File: FluxPublishMulticastTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
protected List<Scenario<String, String>> scenarios_errorFromUpstreamFailure() {
	return Arrays.asList(scenario(f -> f.publish(p -> p)),

			scenario(f -> f.publish(p ->
					p.subscribeWith(Processors.unicast())))
					.fusionMode(Fuseable.ASYNC),

			scenario(f -> f.publish(p -> p))
					.shouldHitDropNextHookAfterTerminate(false),

			scenario(f -> Flux.never().publish(p -> {
				Disposable d = p.subscribe();
				Disposable d2 = p.subscribe();
				d.dispose();
				d2.dispose();

				return f;
			})).shouldHitDropErrorHookAfterTerminate(false)
			   .shouldHitDropNextHookAfterTerminate(false)

	);
}
 
Example #11
Source File: UnicastProcessorTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void createOverrideAll() {
	Disposable onTerminate = () -> {};
	Consumer<? super Integer> onOverflow = t -> {};
	Queue<Integer> queue = Queues.<Integer>get(10).get();
	UnicastProcessor<Integer> processor = UnicastProcessor.create(queue, onOverflow, onTerminate);
	assertProcessor(processor, queue, onOverflow, onTerminate);
}
 
Example #12
Source File: AbstractPool.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
private void defaultDestroy(@Nullable POOLABLE poolable) {
    if (poolable instanceof Disposable) {
        ((Disposable) poolable).dispose();
    }
    else if (poolable instanceof Closeable) {
        try {
            ((Closeable) poolable).close();
        } catch (IOException e) {
            logger.trace("Failure while discarding a released Poolable that is Closeable, could not close", e);
        }
    }
    //TODO anything else to throw away the Poolable?
}
 
Example #13
Source File: FluxAutoConnect.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
FluxAutoConnect(ConnectableFlux<? extends T> source,
		int n, Consumer<? super Disposable> cancelSupport) {
	if (n <= 0) {
		throw new IllegalArgumentException("n > required but it was " + n);
	}
	this.source = Objects.requireNonNull(source, "source");
	this.cancelSupport = Objects.requireNonNull(cancelSupport, "cancelSupport");
	REMAINING.lazySet(this, n);
}
 
Example #14
Source File: FluxAutoConnectTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void connectImmediately() {
	FluxIdentityProcessor<Integer> e = Processors.multicast();

	AtomicReference<Disposable> cancel = new AtomicReference<>();
	
	e.publish().autoConnect(0, cancel::set);
	
	Assert.assertNotNull(cancel.get());
	Assert.assertTrue("sp has no subscribers?", e.downstreamCount() != 0);

	cancel.get().dispose();
	Assert.assertFalse("sp has subscribers?", e.downstreamCount() != 0);
}
 
Example #15
Source File: TestScheduler.java    From retrofit2-reactor-adapter with Apache License 2.0 5 votes vote down vote up
@Override public Worker createWorker() {
  return new Worker() {
    private final List<Runnable> workerTasks = new ArrayList<>();

    @Override public Disposable schedule(Runnable task) {
      workerTasks.add(task);
      tasks.add(task);
      return () -> tasks.remove(task);
    }

    @Override public void dispose() {
      tasks.removeAll(workerTasks);
    }
  };
}
 
Example #16
Source File: WorkerTaskTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void disposeRace() {
	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::dispose;

		RaceTestUtils.race(r1, r1);

		assertThat(set.size()).isZero();
	}
}
 
Example #17
Source File: SchedulerTask.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose() {
	for (;;) {
		Future f = future;
		if (f == FINISHED || f == CANCELLED) {
			break;
		}
		if (FUTURE.compareAndSet(this, f, CANCELLED)) {
			if (f != null) {
				f.cancel(thread != Thread.currentThread());
			}
			break;
		}
	}

	Disposable d;
	for (;;) {
		d = parent;
		if (d == TAKEN || d == null) {
			break;
		}
		if (PARENT.compareAndSet(this, d, TAKEN)) {
			d.dispose();
			break;
		}
	}
}
 
Example #18
Source File: ConnectableFlux.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * Connects this {@link ConnectableFlux} to the upstream source when the specified amount of
 * {@link org.reactivestreams.Subscriber} subscribes and calls the supplied consumer with a {@link Disposable}
 * that allows disconnecting.
 * <p>
 * <img class="marble" src="doc-files/marbles/autoConnectWithMinSubscribers.svg" alt="">
 *
 * @param minSubscribers the minimum number of subscribers
 * @param cancelSupport the consumer that will receive the {@link Disposable} that allows disconnecting
 * @return a {@link Flux} that connects to the upstream source when the given amount of subscribers subscribed
 */
public final Flux<T> autoConnect(int minSubscribers, Consumer<? super Disposable> cancelSupport) {
	if (minSubscribers == 0) {
		connect(cancelSupport);
		return this;
	}
	if(this instanceof Fuseable){
		return onAssembly(new FluxAutoConnectFuseable<>(this,
				minSubscribers,
				cancelSupport));
	}
	return onAssembly(new FluxAutoConnect<>(this, minSubscribers,
			cancelSupport));
}
 
Example #19
Source File: WatchStoreImpl.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void removeWatchesForPeer(String peerId)
{
    Map<Integer, Tuple2<Watch, Disposable>> watchesForPeer = watchesByPeer.remove(peerId);
    if (watchesForPeer != null)
    {
        removeWatches(watchesForPeer.values());
    }
}
 
Example #20
Source File: ElasticScheduler.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public Disposable schedulePeriodically(Runnable task, long initialDelay, long period, TimeUnit unit) {
	CachedService cached = pick();

	return Disposables.composite(Schedulers.directSchedulePeriodically(cached.exec,
			task,
			initialDelay,
			period,
			unit), cached);
}
 
Example #21
Source File: RabbitMQTerminationSubscriber.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
@PreDestroy
public void close() {
    Optional.ofNullable(sendQueueHandle).ifPresent(Disposable::dispose);
    Optional.ofNullable(listenQueueHandle).ifPresent(Disposable::dispose);
    Optional.ofNullable(listenerReceiver).ifPresent(Receiver::close);
}
 
Example #22
Source File: RequestTask.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static <T> RequestTask<T> wrap(ClientMessage message, MonoSink<T> sink, Supplier<T> supplier) {
    if (message instanceof Disposable) {
        return new RequestTask<>((Disposable) message, sink, supplier);
    }

    return new RequestTask<>(null, sink, supplier);
}
 
Example #23
Source File: SchedulersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void schedulerDecoratorDisposedWhenRemoved() {
	AtomicBoolean disposeTracker = new AtomicBoolean();

	class DisposableDecorator implements BiFunction<Scheduler, ScheduledExecutorService, ScheduledExecutorService>,
	                                     Disposable {

		@Override
		public ScheduledExecutorService apply(Scheduler scheduler,
				ScheduledExecutorService service) {
			return service;
		}

		@Override
		public void dispose() {
			disposeTracker.set(true);
		}
	}

	DisposableDecorator decorator = new DisposableDecorator();

	Schedulers.addExecutorServiceDecorator("k1", decorator);

	assertThat(Schedulers.removeExecutorServiceDecorator("k1"))
			.as("decorator removed")
			.isSameAs(decorator);

	assertThat(disposeTracker)
			.as("decorator disposed")
			.isTrue();
}
 
Example #24
Source File: ReactorExt.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static void safeDispose(Disposable... disposables) {
    for (Disposable disposable : disposables) {
        try {
            disposable.dispose();
        } catch (Exception ignore) {
        }
    }
}
 
Example #25
Source File: WatchStoreTest.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void removeWatchForPeerAndId()
    throws Exception
{
    Disposable disposable = Mockito.mock(Disposable.class);
    Disposable otherDisposable = Mockito.mock(Disposable.class);
    Disposable otherPeerDisposable = Mockito.mock(Disposable.class);

    String testPeerId = "TestPeer";
    Integer testWatchId = 7;

    Watch peerWatch =
        new Watch(UUID.randomUUID(), testPeerId, testWatchId, resourceEventIdentifier);
    Watch otherWatch =
        new Watch(UUID.randomUUID(), testPeerId, 8, resourceEventIdentifier);
    Watch otherPeerWatch =
        new Watch(UUID.randomUUID(), "OtherPeer", 9, resourceEventIdentifier);
    watchStore.addWatch(peerWatch, disposable);
    watchStore.addWatch(otherWatch, otherDisposable);
    watchStore.addWatch(otherPeerWatch, otherPeerDisposable);

    watchStore.removeWatchForPeerAndId(testPeerId, testWatchId);

    Mockito.verify(disposable).dispose();
    Mockito.verify(otherDisposable, Mockito.never()).dispose();
    Mockito.verify(otherPeerDisposable, Mockito.never()).dispose();
}
 
Example #26
Source File: DefaultAgentManagementServiceGrpc.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public void updateInstanceGroupTier(TierUpdate request, StreamObserver<Empty> responseObserver) {
    Disposable subscription = agentManagementService.updateInstanceGroupTier(request).subscribe(
            next -> {
                // Never
            },
            e -> safeOnError(logger, e, responseObserver),
            () -> emitEmptyReply(responseObserver)
    );
    attachCancellingCallback(responseObserver, subscription);
}
 
Example #27
Source File: ElasticScheduler.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public Disposable schedule(Runnable task, long delay, TimeUnit unit) {
	CachedService cached = pick();

	return Schedulers.directSchedule(cached.exec,
			task,
			cached,
			delay,
			unit);
}
 
Example #28
Source File: PublisherProbeTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void assertWasNotCancelledMono() {
	PublisherProbe<Void> probe = PublisherProbe.of(Mono.never());
	Disposable d = probe.mono().subscribe();

	probe.assertWasNotCancelled();

	d.dispose();

	assertThatExceptionOfType(AssertionError.class)
			.isThrownBy(probe::assertWasNotCancelled)
			.withMessage("PublisherProbe should not have been cancelled but it was");
}
 
Example #29
Source File: VirtualTimeScheduler.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public Disposable schedule(Runnable task) {
	if (shutdown) {
		throw Exceptions.failWithRejected();
	}
	return directWorker.schedule(task);
}
 
Example #30
Source File: OfframpClientImplTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void messages() throws Exception {
  doReturn(1).when(options).getInitialRequestAmount();
  doReturn(1).when(options).getReplenishingRequestAmount();
  Disposable subscribe = Flux.from(underTest.messages()).subscribe();
  subscribe.dispose();

  InOrder inOrder = Mockito.inOrder(socket);

  inOrder.verify(socket).send(new Request(1));
  inOrder.verify(socket).send(new Cancel());
}