reactor.core.scheduler.Scheduler Java Examples

The following examples show how to use reactor.core.scheduler.Scheduler. 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: TemperatureSensor.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
@PostConstruct
public void init() {
   ScheduledExecutorService executor =
      new MeteredScheduledThreadPoolExecutor("temp.sensor", 3, meterRegistry);

   Scheduler eventsScheduler = Schedulers.fromExecutor(executor);
   dataStream = Flux
      .range(0, 10)
      .repeat()
      .concatMap(ignore -> this.probe()
         .delayElement(randomDelay(1000), eventsScheduler)
         .name("temperature.probe")
         .metrics()
         .log("temperature.measurement", Level.FINE))
      .publish()
      .refCount();
   log.info("Temperature Sensor is ready");
}
 
Example #2
Source File: DefaultPoolConfig.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
public DefaultPoolConfig(Mono<POOLABLE> allocator,
		AllocationStrategy allocationStrategy,
		int maxPending,
		Function<POOLABLE, ? extends Publisher<Void>> releaseHandler,
		Function<POOLABLE, ? extends Publisher<Void>> destroyHandler,
		BiPredicate<POOLABLE, PooledRefMetadata> evictionPredicate,
		Scheduler acquisitionScheduler,
		PoolMetricsRecorder metricsRecorder,
		Clock clock) {
	this.allocator = allocator;
	this.allocationStrategy = allocationStrategy;
	this.maxPending = maxPending;
	this.releaseHandler = releaseHandler;
	this.destroyHandler = destroyHandler;
	this.evictionPredicate = evictionPredicate;
	this.acquisitionScheduler = acquisitionScheduler;
	this.metricsRecorder = metricsRecorder;
	this.clock = clock;
}
 
Example #3
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void defaultThreadDeliveringWhenHasElements() throws InterruptedException {
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(1, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")));
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(testConfig);
    pool.warmup().block();

    //the pool is started and warmed up with one available element
    //we prepare to acquire it
    Mono<PoolableTest> borrower = Mono.fromDirect(pool.withPoolable(Mono::just));
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread and see from which thread the element was delivered
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("acquire-");
}
 
Example #4
Source File: StepVerifierTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
//FIXME this case of doubly-nested schedules is still not fully fixed
public void gh783_withInnerFlatmap() {
	int size = 61;
	Scheduler parallel = Schedulers.newParallel("gh-783");
	StepVerifier.withVirtualTime(() -> Flux.range(1, 10)
	                                       .take(size)
	                                       .subscribeOn(parallel)
	                                       .flatMap(message -> {
		                                       Flux<Long> interval = Flux.interval(Duration.ofSeconds(1));
		                                       return interval.flatMap( tick -> Mono.delay(Duration.ofMillis(500))
		                                                                            .thenReturn(message)
		                                                                            .subscribeOn(parallel))
		                                                      .subscribeOn(parallel);
	                                       }, 1,30)
	                                       .take(size)
	                                       .collectList()
	)
	            .thenAwait(Duration.ofMillis(1500 * (size + 10)))
	            .consumeNextWith(list -> assertThat(list).hasSize(size))
	            .expectComplete()
	            .verify(Duration.ofSeconds(5));
}
 
Example #5
Source File: RouterTest.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testCustomThreadingModel() throws Exception {
    Scheduler thread = Schedulers.single();

    String cid = Integer.toHexString(this.hashCode());

    for (int i = 0; i < 6; i++) {
        final int a = i;

        MessageCreateRequest body = MessageCreateRequest.builder()
            .content(cid + " " + a)
            .build();

        Routes.MESSAGE_CREATE.newRequest(channelId)
                .body(body)
                .exchange(router)
                .bodyToMono(MessageData.class)
                .publishOn(thread)
                .cancelOn(thread)
                .subscribeOn(thread)
                .subscribe(response -> System.out.println("response " + a + ": " + response.content()));
    }

    TimeUnit.SECONDS.sleep(10);
}
 
Example #6
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void defaultThreadDeliveringWhenNoElementsButNotFull() throws InterruptedException {
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")));
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(testConfig);

    //the pool is started with no elements, and has capacity for 1
    //we prepare to acquire, which would allocate the element
    Mono<PoolableTest> borrower = Mono.fromDirect(pool.withPoolable(Mono::just));
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread, but the allocation also happens in a dedicated thread
    //we look at which thread the element was delivered from
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("poolable test allocator-");
}
 
Example #7
Source File: FluxBufferTimeout.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
FluxBufferTimeout(Flux<T> source,
		int maxSize,
		long timespan,
		TimeUnit unit,
		Scheduler timer,
		Supplier<C> bufferSupplier) {
	super(source);
	if (timespan <= 0) {
		throw new IllegalArgumentException("Timeout period must be strictly positive");
	}
	if (maxSize <= 0) {
		throw new IllegalArgumentException("maxSize must be strictly positive");
	}
	this.timer = Objects.requireNonNull(timer, "Timer");
	this.timespan = timespan;
	this.unit = Objects.requireNonNull(unit, "unit");
	this.batchSize = maxSize;
	this.bufferSupplier = Objects.requireNonNull(bufferSupplier, "bufferSupplier");
}
 
Example #8
Source File: ScheduledActionExecutor.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
ScheduledActionExecutor(Schedule schedule,
                        ScheduleMetrics scheduleMetrics,
                        Function<ExecutionContext, Mono<Void>> actionProducer,
                        Scheduler scheduler,
                        Clock clock) {
    this.schedule = schedule;
    this.descriptor = schedule.getDescriptor();
    this.scheduleMetrics = scheduleMetrics;
    this.actionProducer = actionProducer;
    this.scheduler = scheduler;
    this.clock = clock;

    this.action = schedule.getCurrentAction();

    scheduleMetrics.onNewScheduledActionExecutor(this.getSchedule());
}
 
Example #9
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void consistentThreadDeliveringWhenHasElements() throws InterruptedException {
    Scheduler deliveryScheduler = Schedulers.newSingle("delivery");
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(1, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")),
            deliveryScheduler);
    SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(testConfig);

    //the pool is started with one available element
    //we prepare to acquire it
    Mono<PooledRef<PoolableTest>> borrower = pool.acquire();
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread and see from which thread the element was delivered
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("delivery-");
}
 
Example #10
Source File: EmployeeServiceImpl.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public Flux<Employee> readEmployeesByAscLastName() {
	Scheduler subWorker = Schedulers.newSingle("sub-thread");
	Scheduler pubWorker = Schedulers.newSingle("pub-thread");
	Supplier<Flux<Employee>> deferredTask = ()->{
		System.out.println("flux:defer task executor: " + Thread.currentThread().getName());
		System.out.println("flux:defer task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return Flux.fromIterable(employeeDaoImpl.getEmployees());
	};
	Comparator<Employee> descLName = (e1, e2) -> {
		System.out.println("flux:sort task executor: " + Thread.currentThread().getName());
		System.out.println("flux:sort task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return e1.getLastName().compareTo(e2.getLastName());
	};
	Flux<Employee> deferred = Flux.defer(deferredTask).sort(descLName).subscribeOn(subWorker).publishOn(pubWorker);
	return deferred;
}
 
Example #11
Source File: EmployeeServiceImpl.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public Flux<Employee> readEmployeesFlux(int age) {
	Scheduler subWorker = Schedulers.newSingle("sub-thread");
	Scheduler pubWorker = Schedulers.newSingle("pub-thread");
	Predicate<Employee> validAge = (e) -> {
		System.out.println("flux:filter task executor: " + Thread.currentThread().getName());
		System.out.println("flux:filter task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return e.getAge() > age;
	};
	Supplier<Flux<Employee>> deferredTask = ()->{
		System.out.println("flux:defer task executor: " + Thread.currentThread().getName());
		System.out.println("flux:defer task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return Flux.fromIterable(employeeDaoImpl.getEmployees());
	};
	Flux<Employee> deferred = Flux.defer(deferredTask).filter(validAge).subscribeOn(subWorker).publishOn(pubWorker);
	return deferred;
}
 
Example #12
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
@Tag("loops")
void acquireReleaseRaceWithMinSize_loop() {
    final Scheduler racer = Schedulers.fromExecutorService(Executors.newFixedThreadPool(2));
    AtomicInteger newCount = new AtomicInteger();
    try {
        PoolConfig<PoolableTest> testConfig = from(Mono.fromCallable(() -> new PoolableTest(newCount.getAndIncrement())))
                .sizeBetween(4, 5)
                .buildConfig();
        SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(testConfig);

        for (int i = 0; i < 100; i++) {
            RaceTestUtils.race(() -> pool.acquire().block().release().block(),
                    () -> pool.acquire().block().release().block(),
                    racer);
        }
        //we expect that only 3 element was created
        assertThat(newCount).as("elements created in total").hasValue(4);
    }
    finally {
        racer.dispose();
    }
}
 
Example #13
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void defaultThreadDeliveringWhenNoElementsButNotFull() throws InterruptedException {
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")));
    SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(testConfig);

    //the pool is started with no elements, and has capacity for 1
    //we prepare to acquire, which would allocate the element
    Mono<PoolableTest> borrower = Mono.fromDirect(pool.withPoolable(Mono::just));
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread, but the allocation also happens in a dedicated thread
    //we look at which thread the element was delivered from
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("poolable test allocator-");
}
 
Example #14
Source File: EmployeeServiceImpl.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public Flux<Employee> readEmployeesByDescAge() {
	Scheduler subWorker = Schedulers.newSingle("sub-thread");
	Scheduler pubWorker = Schedulers.newSingle("pub-thread");
	Supplier<Flux<Employee>> deferredTask = ()->{
		System.out.println("flux:defer task executor: "+ Thread.currentThread().getName());
		System.out.println("flux:defer task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return Flux.fromIterable(employeeDaoImpl.getEmployees());
	};
	Comparator<Employee> descAge = (e1, e2) -> {
		System.out.println("flux:sort task executor: " + Thread.currentThread().getName());
		System.out.println("flux:sort task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		if(e1.getAge().compareTo(e2.getAge()) == 0){
			return 0;
		} else if(e1.getAge().compareTo(e2.getAge()) > 0){
			return -1;
		} else return 1;
	};
	Flux<Employee> deferred = Flux.defer(deferredTask).sort(descAge).subscribeOn(subWorker).publishOn(pubWorker);
	return deferred;
}
 
Example #15
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void consistentThreadDeliveringWhenNoElementsButNotFull() throws InterruptedException {
    Scheduler deliveryScheduler = Schedulers.newSingle("delivery");
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")),
            deliveryScheduler);
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(testConfig);

    //the pool is started with no elements, and has capacity for 1
    //we prepare to acquire, which would allocate the element
    Mono<PooledRef<PoolableTest>> borrower = pool.acquire();
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread, but the allocation also happens in a dedicated thread
    //we look at which thread the element was delivered from
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("delivery-");
}
 
Example #16
Source File: ReactorMergeOperations.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public static <K> Mono<Map<K, Optional<Throwable>>> merge(Map<K, Mono<Void>> monos, int concurrencyLimit, Scheduler scheduler) {
    List<Flux<Pair<K, Optional<Throwable>>>> m2 = new ArrayList<>();
    monos.forEach((key, mono) -> {

        Flux<Pair<K, Optional<Throwable>>> x = mono.toProcessor().ignoreElement().materialize().map(result -> {
                    Optional<Throwable> error = result.getType() == SignalType.ON_ERROR
                            ? Optional.of(result.getThrowable())
                            : Optional.empty();
                    return Pair.of(key, error);
                }
        ).flux();
        m2.add(x);
    });

    return Flux.merge(Flux.fromIterable(m2), concurrencyLimit)
            .subscribeOn(scheduler)
            .collectList()
            .map(list -> list.stream().collect(Collectors.toMap(Pair::getLeft, Pair::getRight)));
}
 
Example #17
Source File: ReactorHedgedTransformer.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
static <T> ReactorHedgedTransformer<T> newFromThresholds(List<Duration> thresholds,
                                                         Predicate<Throwable> retryableErrorPredicate,
                                                         Map<String, String> context,
                                                         Registry registry,
                                                         Scheduler scheduler) {
    List<Pair<Duration, Long>> thresholdSteps;

    if (thresholds.isEmpty()) {
        thresholdSteps = Collections.emptyList();
    } else {
        Map<Duration, Long> grouped = thresholds.stream().collect(Collectors.groupingBy(
                Function.identity(),
                Collectors.counting()
        ));
        thresholdSteps = grouped.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry::getKey))
                .map(e -> Pair.of(e.getKey(), e.getValue()))
                .collect(Collectors.toList());
    }
    return new ReactorHedgedTransformer<>(thresholdSteps, retryableErrorPredicate, context, registry, scheduler);
}
 
Example #18
Source File: FluxWindowTimeoutTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
  public void scanMainSubscriber() {
Scheduler scheduler = new MyScheduler();
CoreSubscriber<Flux<Integer>> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
FluxWindowTimeout.WindowTimeoutSubscriber<Integer> test = new FluxWindowTimeout.WindowTimeoutSubscriber<>(actual,
		123, Long.MAX_VALUE, TimeUnit.MILLISECONDS, scheduler);
Subscription parent = Operators.emptySubscription();
test.onSubscribe(parent);

Assertions.assertThat(test.scan(Scannable.Attr.RUN_ON)).isSameAs(scheduler.createWorker());
Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
Assertions.assertThat(test.scan(Scannable.Attr.CAPACITY)).isEqualTo(123);
test.requested = 35;
Assertions.assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(35);
Assertions.assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(0);
test.onNext(1);
test.onNext(2);
Assertions.assertThat(test.inners().findFirst().get().scan(Scannable.Attr.BUFFERED)).isEqualTo(2);
Assertions.assertThat(test.inners().findFirst().get().scan(Scannable.Attr
		.CANCELLED)).isEqualTo(false);
Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
test.onComplete();
Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();

Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
  }
 
Example #19
Source File: ReactiveRepositoryAdapterFactory.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
public ResourceRepositoryAdapter decorate(ResourceRepositoryAdapter adapter) {
	Object implementation = adapter.getImplementation();
	if (implementation instanceof ReactiveResourceRepository) {
		return adapter;
	}

	boolean immediate = implementation.getClass().getAnnotation(ImmediateRepository.class) != null;
	LOGGER.debug("wrapping non-reactive repository {}, immediate={}", implementation, immediate);
	Scheduler scheduler = immediate ? Schedulers.immediate() : Schedulers.elastic();
	return new WorkerResourceRepositoryAdapter(adapter, scheduler, moduleRegistry.getHttpRequestContextProvider());
}
 
Example #20
Source File: FluxInterval.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
FluxInterval(
		long initialDelay, 
		long period, 
		TimeUnit unit, 
		Scheduler timedScheduler) {
	if (period < 0L) {
		throw new IllegalArgumentException("period >= 0 required but it was " + period);
	}
	this.initialDelay = initialDelay;
	this.period = period;
	this.unit = Objects.requireNonNull(unit, "unit");
	this.timedScheduler = Objects.requireNonNull(timedScheduler, "timedScheduler");
}
 
Example #21
Source File: ReactorSerializedInvoker.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private ReactorSerializedInvoker(String name,
                                 int size,
                                 Duration excessiveRunningTime,
                                 Scheduler scheduler,
                                 Registry registry,
                                 Clock clock) {
    this.excessiveRunningTime = excessiveRunningTime;
    this.worker = scheduler.createWorker();
    this.scheduler = scheduler;
    this.metrics = new ReactorSerializedInvokerMetrics(name, registry);

    this.actionHandlers = new LinkedBlockingQueue<>(size);
    this.clock = clock;
}
 
Example #22
Source File: MonoCacheTime.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
MonoCacheTime(Mono<? extends T> source, Duration ttl, Scheduler clock) {
	super(source);
	this.ttlGenerator = ignoredSignal -> ttl;
	this.clock = clock;
	@SuppressWarnings("unchecked")
	Signal<T> state = (Signal<T>) EMPTY;
	this.state = state;
}
 
Example #23
Source File: FluxBufferTimeoutTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void discardOnTimerRejected() {
	Scheduler scheduler = Schedulers.newSingle("discardOnTimerRejected");

	StepVerifier.create(Flux.just(1, 2, 3)
	                        .doOnNext(n -> scheduler.dispose())
	                        .bufferTimeout(10, Duration.ofMillis(100), scheduler))
	            .expectErrorSatisfies(e -> assertThat(e).isInstanceOf(RejectedExecutionException.class))
	            .verifyThenAssertThat()
	            .hasDiscardedExactly(1);
}
 
Example #24
Source File: FluxSpecTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
	public void whenProcessorIsStreamed() {
//		"When a processor is streamed"
//		given: "a source composable and a async downstream"
		FluxIdentityProcessor<Integer> source = Processors.replayAll();
		Scheduler scheduler = Schedulers.newParallel("test", 2);

		try {
			Mono<List<Integer>> res = source.subscribeOn(scheduler)
			                                .delaySubscription(Duration.ofMillis(1L))
			                                .log("streamed")
			                                .map(it -> it * 2)
			                                .buffer()
			                                .publishNext();

			res.subscribe();

//		when: "the source accepts a value"
			source.onNext(1);
			source.onNext(2);
			source.onNext(3);
			source.onNext(4);
			source.onComplete();

//		then: "the res is passed on"
			assertThat(res.block()).containsExactly(2, 4, 6, 8);
		}
		finally {
			scheduler.dispose();
		}
	}
 
Example #25
Source File: GrpcAgentReplicatorEventStream.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public GrpcAgentReplicatorEventStream(AgentManagementClient client,
                                      DataReplicatorMetrics metrics,
                                      TitusRuntime titusRuntime,
                                      Scheduler scheduler) {
    super(metrics, titusRuntime, scheduler);
    this.client = client;
}
 
Example #26
Source File: RetryableReplicatorEventStream.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public RetryableReplicatorEventStream(ReplicatorEventStream<SNAPSHOT, TRIGGER> delegate,
                                      DataReplicatorMetrics metrics,
                                      TitusRuntime titusRuntime,
                                      Scheduler scheduler) {
    this.delegate = delegate;
    this.metrics = metrics;
    this.titusRuntime = titusRuntime;
    this.scheduler = scheduler;
}
 
Example #27
Source File: SimpleLifoPoolTest.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
@Test
void defaultThreadDeliveringWhenNoElementsAndFull() throws InterruptedException {
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    Scheduler releaseScheduler = Schedulers.fromExecutorService(
            Executors.newSingleThreadScheduledExecutor((r -> new Thread(r,"release"))));
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(1, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")));
    SimpleLifoPool<PoolableTest> pool = new SimpleLifoPool<>(testConfig);

    //the pool is started with one elements, and has capacity for 1.
    //we actually first acquire that element so that next acquire will wait for a release
    PooledRef<PoolableTest> uniqueSlot = pool.acquire().block();
    assertThat(uniqueSlot).isNotNull();

    //we prepare next acquire
    Mono<PooledRef<PoolableTest>> borrower = pool.acquire();
    CountDownLatch latch = new CountDownLatch(1);

    //we actually perform the acquire from its dedicated thread, capturing the thread on which the element will actually get delivered
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()),
            e -> latch.countDown(), latch::countDown));
    //after a short while, we release the acquired unique element from a third thread
    releaseScheduler.schedule(uniqueSlot.release()::block, 500, TimeUnit.MILLISECONDS);
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .isEqualTo("release");
}
 
Example #28
Source File: GcpPubSubReactiveAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public PubSubReactiveFactory pubSubReactiveFactory(
		PubSubSubscriberTemplate subscriberTemplate,
		@Qualifier("pubSubReactiveScheduler") Optional<Scheduler> userProvidedScheduler) {

	Scheduler scheduler = userProvidedScheduler.orElseGet(() -> Schedulers.parallel());
	return new PubSubReactiveFactory(subscriberTemplate, scheduler);
}
 
Example #29
Source File: ReviewServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Autowired
public ReviewServiceImpl(Scheduler scheduler, ReviewRepository repository, ReviewMapper mapper, ServiceUtil serviceUtil) {
    this.scheduler = scheduler;
    this.repository = repository;
    this.mapper = mapper;
    this.serviceUtil = serviceUtil;
}
 
Example #30
Source File: ClockGlobalRateLimiter.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a {@link ClockGlobalRateLimiter} with a specified interval and number of
 * permits per tick.
 *
 * @param permitsPerTick the max number of requests per tick
 * @param interval the interval between two ticks
 */
public ClockGlobalRateLimiter(int permitsPerTick, Duration interval, Scheduler scheduler) {
    if ((Objects.requireNonNull(interval)).isNegative() || interval.isZero()) {
        throw new IllegalArgumentException("interval must be a non-zero positive duration");
    }
    this.limitedUntil = new AtomicLong();
    this.permitsRemaining = new AtomicInteger();
    this.permitsResetAfter = new AtomicLong();
    Flux.interval(interval, scheduler)
            .doOnNext(tick -> permitsRemaining.set(permitsPerTick))
            .doOnNext(tick -> permitsResetAfter.set(System.nanoTime() + interval.toNanos()))
            .subscribe();
}