java.util.concurrent.Flow Java Examples

The following examples show how to use java.util.concurrent.Flow. 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: Lesson4.java    From Java-Concurrency-Multithreading-in-Practice with MIT License 7 votes vote down vote up
public static void main(String[] args) {
	SubmissionPublisher<WeatherForecast> weatherForecastPublisher = new WeatherForecastPublisher();

	weatherForecastPublisher.subscribe(new DatabaseSubscriber());
	weatherForecastPublisher.subscribe(new TwitterSubscriber<WeatherForecast>());

	Flow.Processor<WeatherForecast, MetricWeatherForecast> metricConverter = new UsToMetricProcessor();
	weatherForecastPublisher.subscribe(metricConverter);
	metricConverter.subscribe(new TwitterSubscriber<MetricWeatherForecast>());

	// close the publisher and associated resources after 10 seconds
	try {
		TimeUnit.SECONDS.sleep(10);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	weatherForecastPublisher.close();
}
 
Example #2
Source File: PgRowPublisherOperation.java    From pgadba with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ParameterizedRowPublisherOperation<R> subscribe(Flow.Subscriber<? super Result.RowColumn> subscriber,
    CompletionStage<? extends R> result) {
  if (result == null) {
    throw new IllegalArgumentException("result is not allowed to be null");
  }
  if (subscriber == null) {
    throw new IllegalArgumentException("subscriber is not allowed to be null");
  }

  publisher.subscribe(subscriber);
  this.result = result;
  result.thenAccept(r -> {
    if (groupSubmission != null) {
      groupSubmission.addGroupResult(r);
    }
    submission.getCompletionStage().toCompletableFuture().complete(r);
  });
  return this;
}
 
Example #3
Source File: PostController.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@GetMapping
    public Flow.Publisher<Post> all() {
//        Executor proxyExecutor = (Runnable command)-> ForkJoinPool.commonPool().execute(command);
//        SubmissionPublisher publisher  = new SubmissionPublisher(proxyExecutor, Flow.defaultBufferSize());
//        publisher.submit(new Post(1L, "post one", "content of post one"));
//        publisher.submit(new Post(2L, "post two", "content of post two"));
//
//        return publisher;
        // see: https://stackoverflow.com/questions/46597924/spring-5-supports-java-9-flow-apis-in-its-reactive-feature
        return JdkFlowAdapter.publisherToFlowPublisher(
                Flux.just(
                        new Post(1L, "post one", "content of post one"),
                        new Post(2L, "post two", "content of post two")
                )
        );
    }
 
Example #4
Source File: Stream.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    if (this.subscription != null) {
        throw new IllegalStateException();
    }
    this.subscription = subscription;
    subscription.request(1);
}
 
Example #5
Source File: ResponseProcessors.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    if (this.subscription != null) {
        subscription.cancel();
        return;
    }
    this.subscription = subscription;
    // We can handle whatever you've got
    subscription.request(Long.MAX_VALUE);
}
 
Example #6
Source File: AdaptedBlackBoxSubscriberVerificationTest.java    From java-async-util with Apache License 2.0 5 votes vote down vote up
@Override
public Subscriber<Integer> createFlowSubscriber() {
  return new FlowAdapter.SubscribingIterator<Integer>() {
    @Override
    public void onSubscribe(final Flow.Subscription subscription) {
      super.onSubscribe(subscription);
      consume();
    }
  };
}
 
Example #7
Source File: FlowAdapterTest.java    From java-async-util with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testDoubleSubscription() throws Throwable {
  final Flow.Publisher<Long> publisher = FlowAdapter.toPublisher(AsyncIterator.range(0, 5));
  final ConsumingSubscriber<Long> s = new ConsumingSubscriber<>();
  publisher.subscribe(s);
  s.join();

  final ConsumingSubscriber<Long> s2 = new ConsumingSubscriber<>();
  try {
    publisher.subscribe(s2);
  } catch (final Throwable e) {
    Assert.fail("failure should be notified via onError, got: " + e);
  }
  FlowAdapterTest.unwrap(s2);
}
 
Example #8
Source File: ResponseProcessors.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    this.subscription = subscription;
    try {
        out = FileChannel.open(file, options);
    } catch (IOException e) {
        result.completeExceptionally(e);
        subscription.cancel();
        return;
    }
    subscription.request(1);
}
 
Example #9
Source File: FlowAdapter.java    From java-async-util with Apache License 2.0 5 votes vote down vote up
@Override
public void onSubscribe(final Flow.Subscription subscription) {
  Objects.requireNonNull(subscription);
  if (this.subscription != null) {
    subscription.cancel();
    return;
  }
  this.subscription = subscription;
}
 
Example #10
Source File: SubmissionPublisherTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A default-constructed SubmissionPublisher has no subscribers,
 * is not closed, has default buffer size, and uses the
 * defaultExecutor
 */
public void testConstructor1() {
    SubmissionPublisher<Integer> p = new SubmissionPublisher<>();
    checkInitialState(p);
    assertEquals(p.getMaxBufferCapacity(), Flow.defaultBufferSize());
    Executor e = p.getExecutor(), c = ForkJoinPool.commonPool();
    if (ForkJoinPool.getCommonPoolParallelism() > 1)
        assertSame(e, c);
    else
        assertNotSame(e, c);
}
 
Example #11
Source File: FlowAdapter.java    From java-async-util with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(final Flow.Subscriber<? super T> subscriber) {
  if ((boolean) SUBSCRIBED_HANDLE.getAndSet(this, true)) {
    subscriber.onError(new IllegalStateException(
        "Publisher " + this + " does not support multiple subscribers"));
    return;
  }
  subscriber.onSubscribe(new IteratorBackedSubscription<>(this.asyncIterator, subscriber));
}
 
Example #12
Source File: DockerXDemoSubscriber.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
public void onSubscribe(Flow.Subscription subscription) {
    //count = bufferSize - bufferSize / 2;// 当消费一半的时候重新请求
    (this.subscription = subscription).request(bufferSize);
    System.out.println("开始onSubscribe订阅");
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: DefaultPublisher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void subscribe(Flow.Subscriber<? super T> subscriber) {
    try {
        subscriber.onSubscribe(new Subscription(subscriber));
    } catch (RejectedExecutionException e) {
        subscriber.onError(new IllegalStateException(e));
    }
}
 
Example #14
Source File: AdapterExample.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Flow.Publisher jdkPublisher = FlowAdapters.toFlowPublisher(new NewsServicePublisher(smp ->
        Flowable.intervalRange(0, 10, 0, 10, TimeUnit.MILLISECONDS, Schedulers.computation())
                .map(e -> NewsLetter.template()
                                    .title(String.valueOf(e))
                                    .digest(Collections.emptyList())
                                    .build())
                .subscribe(smp)
    ));
    Publisher external = FlowAdapters.toPublisher(jdkPublisher);
    Flow.Publisher jdkPublisher2 = FlowAdapters.toFlowPublisher(
            external
    );

    NewsServiceSubscriber newsServiceSubscriber = new NewsServiceSubscriber(2);
    jdkPublisher2.subscribe(FlowAdapters.toFlowSubscriber(newsServiceSubscriber));



    while (true) {
        Optional<NewsLetter> letterOptional = newsServiceSubscriber.eventuallyReadDigest();

        if (letterOptional.isPresent()) {
            NewsLetter letter = letterOptional.get();
            System.out.println(letter);

            if (letter.getTitle().equals("9")) {
                break;
            }
        }
    }
}
 
Example #15
Source File: DockerXDemoSubscriber.java    From Java-programming-methodology-Rxjava-articles with Apache License 2.0 5 votes vote down vote up
public void onSubscribe(Flow.Subscription subscription) {
    //count = bufferSize - bufferSize / 2;// 当消费一半的时候重新请求
    (this.subscription = subscription).request(bufferSize);
    System.out.println("开始onSubscribe订阅");
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: Http1Request.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    if (this.subscription != null) {
        throw new IllegalStateException("already subscribed");
    }
    this.subscription = subscription;
    subscription.request(1);
}
 
Example #17
Source File: Http1Request.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    if (this.subscription != null) {
        throw new IllegalStateException("already subscribed");
    }
    this.subscription = subscription;
    subscription.request(1);
}
 
Example #18
Source File: Lesson2.java    From Java-Concurrency-Multithreading-in-Practice with MIT License 5 votes vote down vote up
WeatherForecastPublisher() {
	super(Executors.newFixedThreadPool(2), Flow.defaultBufferSize());
	scheduler = new ScheduledThreadPoolExecutor(1);
	periodicTask = scheduler.scheduleAtFixedRate( //
			// runs submit()
			() -> submit(WeatherForecast.nextRandomWeatherForecast()), //
			500, 500, TimeUnit.MILLISECONDS);
}
 
Example #19
Source File: RequestProcessors.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized void subscribe(Flow.Subscriber<? super ByteBuffer> subscriber) {
    if (!(subscriber instanceof ProcessorBase)) {
        throw new UnsupportedOperationException();
    }
    ProcessorBase base = (ProcessorBase)subscriber;
    HttpClientImpl client = base.getClient();
    InputStream is = streamSupplier.get();
    if (is == null) {
        throw new UncheckedIOException(new IOException("no inputstream supplied"));
    }
    this.delegate = new PullPublisher<>(() -> new StreamIterator(is));
    delegate.subscribe(subscriber);
}
 
Example #20
Source File: TestReactiveSubscribers.java    From Fibry with MIT License 5 votes vote down vote up
@Override
public void subscribe(Flow.Subscriber<? super Integer> subscriber) {
    subscriber.onSubscribe(new Flow.Subscription() {
        private final AtomicBoolean completed = new AtomicBoolean(false);
        private final AtomicInteger numMessagesToSend = new AtomicInteger();
        private final Actor<Flow.Subscriber<? super Integer>, Void, Void> actorRefill = ActorSystem.anonymous().newActor(sub -> {
            while (numSent.get() < numMax && numMessagesToSend.get() > 0) {
                subscriber.onNext(numSent.incrementAndGet());
                numMessagesToSend.decrementAndGet();
            }

            if (numSent.get() >= numMax) {
                if (completed.compareAndSet(false, true))
                    subscriber.onComplete();
            }
        });

        @Override
        public void request(long n) {
            if (numSent.get() >= numMax)
                return;

            numMessagesToSend.accumulateAndGet((int) n, Math::max);

            actorRefill.sendMessage(subscriber);
        }

        @Override
        public void cancel() {
            numSent.set(numMax);
        }
    });
}
 
Example #21
Source File: HttpInputStreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    synchronized (this) {
        closed = true;
        Flow.Subscription s = subscription;
        if (s != null) {
            s.cancel();
        }
        subscription = null;
    }
    super.close();
}
 
Example #22
Source File: FlowApiLiveVideo.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    this.subscription = subscription;
    subscription.request(1);
}
 
Example #23
Source File: ResponseProcessors.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    this.subscription = subscription;
    subscription.request(1);
}
 
Example #24
Source File: PushPublisher.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void subscribe(Flow.Subscriber<? super T> subscriber) {
    subscription = new Subscription(subscriber);
    subscriber.onSubscribe(subscription);
}
 
Example #25
Source File: ResponseProcessors.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onSubscribe(Flow.Subscription subscription) {
    this.subscription = subscription;
    subscription.request(Long.MAX_VALUE);
}
 
Example #26
Source File: RequestProcessors.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void subscribe(Flow.Subscriber<? super ByteBuffer> subscriber) {
    List<ByteBuffer> copy = copy(content, offset, length);
    this.delegate = new PullPublisher<>(copy);
    delegate.subscribe(subscriber);
}
 
Example #27
Source File: PushPublisher.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
Subscription(Flow.Subscriber<? super T> subscriber) {
    PushPublisher.this.subscriber = subscriber;
}
 
Example #28
Source File: PseudoPublisher.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void subscribe(Flow.Subscriber<? super T> subscriber) {
    subscriber.onSubscribe(new Subscription(subscriber));
}
 
Example #29
Source File: PseudoPublisher.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
Subscription(Flow.Subscriber<? super T> subscriber) {
    this.subscriber = subscriber;
}
 
Example #30
Source File: PullPublisher.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
Subscription(Flow.Subscriber<? super T> subscriber, Iterator<T> iter) {
    this.subscriber = subscriber;
    this.iter = iter;
}