reactor.core.publisher.BaseSubscriber Java Examples

The following examples show how to use reactor.core.publisher.BaseSubscriber. 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: ITSpringConfiguredReactorClient.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void cancelInFlight() throws Exception {
	BaseSubscriber<Integer> subscriber = new BaseSubscriber<Integer>() {
	};

	CountDownLatch latch = new CountDownLatch(1);

	server.setDispatcher(new Dispatcher() {
		@Override
		public MockResponse dispatch(RecordedRequest request) {
			subscriber.cancel();
			latch.countDown();
			return new MockResponse();
		}
	});

	getMono(client, "/foo").subscribe(subscriber);

	latch.await();

	assertThat(server.getRequestCount()).isOne();

	this.testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "CANCELLED");
}
 
Example #2
Source File: ITSpringConfiguredReactorClient.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
/**
 * This assumes that implementations do not issue an HTTP request until
 * {@link Subscription#request(long)} is called. Since a client span is only for
 * remote operations, we should not create one when we know a network request won't
 * happen. In this case, we ensure a canceled subscription doesn't end up traced.
 */
@Test
public void cancelledSubscription_doesntTrace() throws Exception {
	CountDownLatch latch = new CountDownLatch(1);

	BaseSubscriber<Integer> subscriber = new BaseSubscriber<Integer>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			subscription.cancel();
			latch.countDown();
		}
	};

	getMono(client, "/foo").subscribe(subscriber);

	latch.await();

	assertThat(server.getRequestCount()).isZero();
	// post-conditions will prove no span was created
}
 
Example #3
Source File: GuideTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void baseSubscriberFineTuneBackpressure() {
	Flux<String> source = someStringSource();

	source.map(String::toUpperCase)
	      .subscribe(new BaseSubscriber<String>() { // <1>
		      @Override
		      protected void hookOnSubscribe(Subscription subscription) {
			      // <2>
			      request(1); // <3>
		      }

		      @Override
		      protected void hookOnNext(String value) {
			      request(1); // <4>
		      }

		      //<5>
	      });
}
 
Example #4
Source File: DefaultTestPublisherTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void misbehavingFluxIgnoresCancellation() {
	TestPublisher<String> publisher = TestPublisher.createNoncompliant(Violation.DEFER_CANCELLATION);
	AtomicLong emitCount = new AtomicLong();

	publisher.flux().subscribe(new BaseSubscriber<String>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			subscription.request(Long.MAX_VALUE);
			subscription.cancel();
		}

		@Override
		protected void hookOnNext(String value) {
			emitCount.incrementAndGet();
		}
	});

	publisher.emit("A", "B", "C");

	publisher.assertCancelled();
	assertThat(emitCount.get()).isEqualTo(3);
}
 
Example #5
Source File: ReactorProbe.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
public void printEventNumbers(Flux<Long> source, PrintWriter writer) {
    source
            .filter(x -> x % 2 == 0)
            .subscribe(new BaseSubscriber<Long>() {
                @Override
                protected void hookOnSubscribe(Subscription subscription) {
                    request(1);
                }

                @Override
                protected void hookOnNext(Long value) {
                    request(1);
                }

            });
}
 
Example #6
Source File: SchedulerLeakRx.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    AtomicLong counter = new AtomicLong(0L);
    Scheduler scheduler = new ParallelScheduler(10);
    Flowable
    .<Long>generate(sink -> sink.onNext(counter.getAndIncrement()))
    .concatMap(i -> {
        return Flowable.just(i)
                .observeOn(scheduler)
                .map(number -> number * 2L);
    })
    .subscribeOn(new SingleScheduler())
    .subscribe(new BaseSubscriber<Long>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            subscription.request(10);
        }

        @Override
        protected void hookOnNext(Long value) {
            upstream().request(1);
        }
    });

    Thread.sleep(100000000);
}
 
Example #7
Source File: NettyToStyxRequestDecoderTest.java    From styx with Apache License 2.0 6 votes vote down vote up
private static StringBuilder subscribeToContent(ByteStream contentStream, CountDownLatch onCompleteLatch) {
    StringBuilder builder = new StringBuilder();
    contentStream.subscribe(new BaseSubscriber<Buffer>() {
        @Override
        public void hookOnComplete() {
            // no-op
            onCompleteLatch.countDown();
        }

        @Override
        public void hookOnNext(Buffer buffer) {
            builder.append(new String(buffer.content(), UTF_8));
        }
    });
    return builder;
}
 
Example #8
Source File: StyxHostHttpClientTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void releasesIfRequestIsCancelledBeforeHeaders() {
    Connection connection = mockConnection(EmitterProcessor.create());
    ConnectionPool pool = mockPool(connection);
    Context context = mockContext();

    StyxHostHttpClient hostClient = new StyxHostHttpClient(pool);
    AtomicReference<Subscription> subscription = new AtomicReference<>();

    Flux.from(hostClient.sendRequest(request, context))
            .subscribe(new BaseSubscriber<LiveHttpResponse>() {
                @Override
                protected void hookOnSubscribe(Subscription s) {
                    super.hookOnSubscribe(s);
                    s.request(1);
                    subscription.set(s);
                }
            });

    subscription.get().cancel();
    verify(pool).closeConnection(any(Connection.class));
    verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin"));
}
 
Example #9
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void allocatedReleasedOrAbortedIfCancelRequestRace(int round, AtomicInteger newCount, AtomicInteger releasedCount, boolean cancelFirst) throws InterruptedException {
    Scheduler scheduler = Schedulers.newParallel("poolable test allocator");

    PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
            Mono.defer(() -> Mono.delay(Duration.ofMillis(50)).thenReturn(new PoolableTest(newCount.incrementAndGet())))
                .subscribeOn(scheduler),
            pt -> releasedCount.incrementAndGet());
    SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(testConfig);

    //acquire the only element and capture the subscription, don't request just yet
    CountDownLatch latch = new CountDownLatch(1);
    final BaseSubscriber<PoolableTest> baseSubscriber = new BaseSubscriber<PoolableTest>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            //don't request
            latch.countDown();
        }
    };
    pool.withPoolable(Mono::just).subscribe(baseSubscriber);
    latch.await();

    final ExecutorService executorService = Executors.newFixedThreadPool(2);
    if (cancelFirst) {
        executorService.submit(baseSubscriber::cancel);
        executorService.submit(baseSubscriber::requestUnbounded);
    }
    else {
        executorService.submit(baseSubscriber::requestUnbounded);
        executorService.submit(baseSubscriber::cancel);
    }

    //release due to cancel is async, give it a bit of time
    await().atMost(100, TimeUnit.MILLISECONDS).with().pollInterval(10, TimeUnit.MILLISECONDS)
           .untilAsserted(() -> assertThat(releasedCount)
                   .as("released vs created in round " + round + (cancelFirst? " (cancel first)" : " (request first)"))
                   .hasValue(newCount.get()));
}
 
Example #10
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorrectFrameOrder() {
  MonoProcessor<Object> delayer = MonoProcessor.create();
  BaseSubscriber<Payload> subscriber =
      new BaseSubscriber<Payload>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {}
      };
  rule.socket
      .requestChannel(
          Flux.concat(Flux.just(0).delayUntil(i -> delayer), Flux.range(1, 999))
              .map(i -> DefaultPayload.create(i + "")))
      .subscribe(subscriber);

  subscriber.request(1);
  subscriber.request(Long.MAX_VALUE);
  delayer.onComplete();

  Iterator<ByteBuf> iterator = rule.connection.getSent().iterator();

  ByteBuf initialFrame = iterator.next();

  Assertions.assertThat(FrameHeaderCodec.frameType(initialFrame)).isEqualTo(REQUEST_CHANNEL);
  Assertions.assertThat(RequestChannelFrameCodec.initialRequestN(initialFrame))
      .isEqualTo(Long.MAX_VALUE);
  Assertions.assertThat(RequestChannelFrameCodec.data(initialFrame).toString(CharsetUtil.UTF_8))
      .isEqualTo("0");
  Assertions.assertThat(initialFrame.release()).isTrue();

  Assertions.assertThat(iterator.hasNext()).isFalse();
  rule.assertHasNoLeaks();
}
 
Example #11
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(2_000)
public void testStreamInitialN() {
  Flux<Payload> stream = rule.socket.requestStream(EmptyPayload.INSTANCE);

  BaseSubscriber<Payload> subscriber =
      new BaseSubscriber<Payload>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
          // don't request here
        }
      };
  stream.subscribe(subscriber);

  Assertions.assertThat(rule.connection.getSent()).isEmpty();

  subscriber.request(5);

  List<ByteBuf> sent = new ArrayList<>(rule.connection.getSent());

  assertThat("sent frame count", sent.size(), is(1));

  ByteBuf f = sent.get(0);

  assertThat("initial frame", frameType(f), is(REQUEST_STREAM));
  assertThat("initial request n", RequestStreamFrameCodec.initialRequestN(f), is(5L));
  assertThat("should be released", f.release(), is(true));
  rule.assertHasNoLeaks();
}
 
Example #12
Source File: ScopePassingSpanSubscriberTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void should_put_current_span_to_context() {
	try (Scope ws = this.currentTraceContext.newScope(context2)) {
		CoreSubscriber<?> subscriber = new ScopePassingSpanSubscriber<>(
				new BaseSubscriber<Object>() {
				}, Context.empty(), currentTraceContext, context);

		then(subscriber.currentContext().get(TraceContext.class)).isEqualTo(context);
	}
}
 
Example #13
Source File: WebClientTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
/**
 * Cancel before {@link Subscription#request(long)} means a network request was never
 * sent
 */
@Test
@Disabled("flakey")
public void shouldNotTagOnCancel() {
	this.webClient.get().uri("http://localhost:" + this.port + "/doNotSkip")
			.retrieve().bodyToMono(String.class)
			.subscribe(new BaseSubscriber<String>() {
				@Override
				protected void hookOnSubscribe(Subscription subscription) {
					cancel();
				}
			});

	then(this.spans).isEmpty();
}
 
Example #14
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void allocatedReleasedOrAbortedIfCancelRequestRace(int round, AtomicInteger newCount, AtomicInteger releasedCount, boolean cancelFirst) throws InterruptedException {
    Scheduler scheduler = Schedulers.newParallel("poolable test allocator");

    PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
            Mono.defer(() -> Mono.delay(Duration.ofMillis(50)).thenReturn(new PoolableTest(newCount.incrementAndGet())))
                .subscribeOn(scheduler),
            pt -> releasedCount.incrementAndGet());
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(testConfig);

    //acquire the only element and capture the subscription, don't request just yet
    CountDownLatch latch = new CountDownLatch(1);
    final BaseSubscriber<PoolableTest> baseSubscriber = new BaseSubscriber<PoolableTest>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            //don't request
            latch.countDown();
        }
    };
    pool.withPoolable(Mono::just).subscribe(baseSubscriber);
    latch.await();

    final ExecutorService executorService = Executors.newFixedThreadPool(2);
    if (cancelFirst) {
        executorService.submit(baseSubscriber::cancel);
        executorService.submit(baseSubscriber::requestUnbounded);
    }
    else {
        executorService.submit(baseSubscriber::requestUnbounded);
        executorService.submit(baseSubscriber::cancel);
    }

    //release due to cancel is async, give it a bit of time
    await().atMost(100, TimeUnit.MILLISECONDS).with().pollInterval(10, TimeUnit.MILLISECONDS)
           .untilAsserted(() -> assertThat(releasedCount)
                   .as("released vs created in round " + round + (cancelFirst? " (cancel first)" : " (request first)"))
                   .hasValue(newCount.get()));
}
 
Example #15
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void allocatedReleasedOrAbortedIfCancelRequestRace(int round, AtomicInteger newCount, AtomicInteger releasedCount, boolean cancelFirst) throws InterruptedException {
    Scheduler scheduler = Schedulers.newParallel("poolable test allocator");

    PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
            Mono.defer(() -> Mono.delay(Duration.ofMillis(50)).thenReturn(new PoolableTest(newCount.incrementAndGet())))
                .subscribeOn(scheduler),
            pt -> releasedCount.incrementAndGet());
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(testConfig);

    //acquire the only element and capture the subscription, don't request just yet
    CountDownLatch latch = new CountDownLatch(1);
    final BaseSubscriber<PooledRef<PoolableTest>> baseSubscriber = new BaseSubscriber<PooledRef<PoolableTest>>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            //don't request
            latch.countDown();
        }
    };
    pool.acquire().subscribe(baseSubscriber);
    latch.await();

    final ExecutorService executorService = Executors.newFixedThreadPool(2);
    if (cancelFirst) {
        executorService.submit(baseSubscriber::cancel);
        executorService.submit(baseSubscriber::requestUnbounded);
    }
    else {
        executorService.submit(baseSubscriber::requestUnbounded);
        executorService.submit(baseSubscriber::cancel);
    }

    //release due to cancel is async, give it a bit of time
    await().atMost(200, TimeUnit.MILLISECONDS).with().pollInterval(10, TimeUnit.MILLISECONDS)
           .untilAsserted(() -> assertThat(releasedCount)
                   .as("released vs created in round " + round + (cancelFirst? " (cancel first)" : " (request first)"))
                   .hasValue(newCount.get()));
}
 
Example #16
Source File: DataBufferUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // gh-22107
public void readAsynchronousFileChannelCancelWithoutDemand() throws Exception {
	URI uri = this.resource.getURI();
	Flux<DataBuffer> flux = DataBufferUtils.readAsynchronousFileChannel(
			() -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ),
			this.bufferFactory, 3);

	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber);
	subscriber.cancel();
}
 
Example #17
Source File: BackPressureTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public  void testBackPressureOps() throws  Exception{
    Flux<Integer> numberGenerator = Flux.create(x -> {
        System.out.println("Requested Events :"+x.requestedFromDownstream());
        int number = 1;
        while(number < 100) {
            x.next(number);
            number++;
        }
        x.complete();
    });

    CountDownLatch latch = new CountDownLatch(1);
    numberGenerator
            .onBackpressureBuffer(2,x -> System.out.println("Dropped :"+x),BufferOverflowStrategy.DROP_LATEST)
            .subscribe(new BaseSubscriber<Integer>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            request(1);
        }

        @Override
        protected void hookOnNext(Integer value) {
            System.out.println(value);
        }

        @Override
        protected void hookOnError(Throwable throwable) {
            throwable.printStackTrace();
            latch.countDown();
        }

        @Override
        protected void hookOnComplete() {
            latch.countDown();
        }
    });
    assertTrue(latch.await(1L, TimeUnit.SECONDS));
}
 
Example #18
Source File: BackPressureTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public  void testBackPressure() throws  Exception{
    Flux<Integer> numberGenerator = Flux.create(x -> {
        System.out.println("Requested Events :"+x.requestedFromDownstream());
        int number = 1;
        while(number < 100) {
            x.next(number);
            number++;
        }
        x.complete();
    }, FluxSink.OverflowStrategy.ERROR);

    CountDownLatch latch = new CountDownLatch(1);
    numberGenerator.subscribe(new BaseSubscriber<Integer>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            request(1);
        }

        @Override
        protected void hookOnNext(Integer value) {
            System.out.println(value);
        }

        @Override
        protected void hookOnError(Throwable throwable) {
            throwable.printStackTrace();
            latch.countDown();
        }

        @Override
        protected void hookOnComplete() {
            latch.countDown();
        }
    });
    assertTrue(latch.await(1L, TimeUnit.SECONDS));
}
 
Example #19
Source File: BroadcastTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public void testPublishBroadcast() throws Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        System.out.println("generating next of "+ state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator=fibonacciGenerator.doFinally(x -> {
        System.out.println("Closing ");
    }).publish().autoConnect(2);

    fibonacciGenerator.subscribe(new BaseSubscriber<Long>() {
        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            request(1);
        }

        @Override
        protected void hookOnNext(Long value) {
            System.out.println("1st: "+value);
        }
    });

    fibonacciGenerator.subscribe(x -> System.out.println("2nd : "+x));
    Thread.sleep(500);

}
 
Example #20
Source File: CancelWithoutDemandCodecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
	Flux<? extends DataBuffer> flux = Flux.from(body).concatMap(Flux::from);
	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber); // Assume sync execution (e.g. encoding with Flux.just)..
	subscriber.cancel();
	return Mono.empty();
}
 
Example #21
Source File: CancelWithoutDemandCodecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
	Flux<? extends DataBuffer> flux = Flux.from(body);
	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber); // Assume sync execution (e.g. encoding with Flux.just)..
	subscriber.cancel();
	return Mono.empty();
}
 
Example #22
Source File: CancelWithoutDemandCodecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // gh-22543
public void cancelWithProtobufEncoder() {
	ProtobufEncoder encoder = new ProtobufEncoder();
	Msg msg = Msg.newBuilder().setFoo("Foo").setBlah(SecondMsg.newBuilder().setBlah(123).build()).build();

	Flux<DataBuffer> flux = encoder.encode(Mono.just(msg),
			this.bufferFactory, ResolvableType.forClass(Msg.class),
			new MimeType("application", "x-protobuf"), Collections.emptyMap());

	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber); // Assume sync execution (e.g. encoding with Flux.just)..
	subscriber.cancel();
}
 
Example #23
Source File: CancelWithoutDemandCodecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // gh-22107
public void cancelWithJaxb2() {
	Jaxb2XmlEncoder encoder = new Jaxb2XmlEncoder();

	Flux<DataBuffer> flux = encoder.encode(Mono.just(new Pojo("foo", "bar")),
			this.bufferFactory, ResolvableType.forClass(Pojo.class),
			MediaType.APPLICATION_XML, Collections.emptyMap());

	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber); // Assume sync execution (e.g. encoding with Flux.just)..
	subscriber.cancel();
}
 
Example #24
Source File: CancelWithoutDemandCodecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // gh-22107
public void cancelWithJackson() {
	Jackson2JsonEncoder encoder = new Jackson2JsonEncoder();

	Flux<DataBuffer> flux = encoder.encode(Flux.just(new Pojo("foofoo", "barbar"), new Pojo("bar", "baz")),
			this.bufferFactory, ResolvableType.forClass(Pojo.class),
			MediaType.APPLICATION_JSON, Collections.emptyMap());

	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber); // Assume sync execution (e.g. encoding with Flux.just)..
	subscriber.cancel();
}
 
Example #25
Source File: ChannelSendOperatorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // gh-22720
public void errorFromWriteSourceWhileItemCached() {

	// 1. First item received
	// 2. writeFunction applied and writeCompletionBarrier subscribed to it
	// 3. Write Publisher fails right after that and before request(n) from server

	LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory();
	ZeroDemandSubscriber writeSubscriber = new ZeroDemandSubscriber();

	ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>(
			Flux.create(sink -> {
				DataBuffer dataBuffer = bufferFactory.allocateBuffer();
				dataBuffer.write("foo", StandardCharsets.UTF_8);
				sink.next(dataBuffer);
				sink.error(new IllegalStateException("err"));
			}),
			publisher -> {
				publisher.subscribe(writeSubscriber);
				return Mono.never();
			});


	operator.subscribe(new BaseSubscriber<Void>() {});
	try {
		writeSubscriber.signalDemand(1);  // Let cached signals ("foo" and error) be published..
	}
	catch (Throwable ex) {
		assertNotNull(ex.getCause());
		assertEquals("err", ex.getCause().getMessage());
	}

	bufferFactory.checkForLeaks();
}
 
Example #26
Source File: DataBufferUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void splitWithoutDemand() {
	Flux<DataBuffer> source = Flux.concat(
			deferStringBuffer("foo--"),
			deferStringBuffer("bar--")
	);
	byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);

	Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter);

	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	result.subscribe(subscriber);
	subscriber.cancel();
}
 
Example #27
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void allocatedReleasedOrAbortedIfCancelRequestRace(int round, AtomicInteger newCount, AtomicInteger releasedCount, boolean cancelFirst) throws InterruptedException {
    Scheduler scheduler = Schedulers.newParallel("poolable test allocator");
    final ExecutorService executorService = Executors.newFixedThreadPool(2);

    try {

        PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
                Mono.defer(() -> Mono.delay(Duration.ofMillis(50)).thenReturn(new PoolableTest(newCount.incrementAndGet())))
                    .subscribeOn(scheduler),
                pt -> releasedCount.incrementAndGet());
        SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(testConfig);

        //acquire the only element and capture the subscription, don't request just yet
        CountDownLatch latch = new CountDownLatch(1);
        final BaseSubscriber<PooledRef<PoolableTest>> baseSubscriber = new BaseSubscriber<PooledRef<PoolableTest>>() {
            @Override
            protected void hookOnSubscribe(Subscription subscription) {
                //don't request
                latch.countDown();
            }
        };
        pool.acquire().subscribe(baseSubscriber);
        latch.await();

        if (cancelFirst) {
            executorService.submit(baseSubscriber::cancel);
            executorService.submit(baseSubscriber::requestUnbounded);
        }
        else {
            executorService.submit(baseSubscriber::requestUnbounded);
            executorService.submit(baseSubscriber::cancel);
        }

        //release due to cancel is async, give it ample time
        await().atMost(200, TimeUnit.MILLISECONDS).with().pollInterval(10, TimeUnit.MILLISECONDS)
               .untilAsserted(() -> assertThat(releasedCount)
                       .as("released vs created in round " + round + (cancelFirst? " (cancel first)" : " (request first)"))
                       .hasValue(newCount.get()));
    }
    finally {
        scheduler.dispose();
        executorService.shutdownNow();
    }
}