Path: blob/master/test/jdk/java/net/httpclient/BufferingSubscriberCancelTest.java
41149 views
/*1* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.nio.ByteBuffer;24import java.util.List;25import java.util.concurrent.CompletionStage;26import java.util.concurrent.CountDownLatch;27import java.util.concurrent.ExecutorService;28import java.util.concurrent.Executors;29import java.util.concurrent.Flow.Subscription;30import java.util.concurrent.SubmissionPublisher;31import java.util.function.IntSupplier;32import java.util.stream.IntStream;33import java.net.http.HttpResponse.BodySubscriber;34import org.testng.annotations.DataProvider;35import org.testng.annotations.Test;36import static java.lang.Long.MAX_VALUE;37import static java.lang.Long.MIN_VALUE;38import static java.lang.System.out;39import static java.nio.ByteBuffer.wrap;40import static java.util.concurrent.TimeUnit.SECONDS;41import static java.net.http.HttpResponse.BodySubscribers.buffering;42import static org.testng.Assert.*;4344/*45* @test46* @summary Direct test for HttpResponse.BodySubscriber.buffering() cancellation47* @run testng/othervm BufferingSubscriberCancelTest48*/4950public class BufferingSubscriberCancelTest {5152@DataProvider(name = "bufferSizes")53public Object[][] bufferSizes() {54return new Object[][]{55// bufferSize should be irrelevant56{1}, {100}, {511}, {512}, {513}, {1024}, {2047}, {2048}57};58}5960@Test(dataProvider = "bufferSizes")61public void cancelWithoutAnyItemsPublished(int bufferSize) throws Exception {62ExecutorService executor = Executors.newFixedThreadPool(1);63SubmissionPublisher<List<ByteBuffer>> publisher =64new SubmissionPublisher<>(executor, 1);6566CountDownLatch gate = new CountDownLatch(1); // single onSubscribe67ExposingSubscriber exposingSubscriber = new ExposingSubscriber(gate);68BodySubscriber subscriber = buffering(exposingSubscriber, bufferSize);69publisher.subscribe(subscriber);70gate.await(30, SECONDS);71assertEqualsWithRetry(publisher::getNumberOfSubscribers, 1);72exposingSubscriber.subscription.cancel();73assertEqualsWithRetry(publisher::getNumberOfSubscribers, 0);7475// further cancels/requests should be a no-op76Subscription s = exposingSubscriber.subscription;77s.cancel(); s.request(1);78s.cancel(); s.request(100); s.cancel();79s.cancel(); s.request(MAX_VALUE); s.cancel(); s.cancel();80s.cancel(); s.cancel(); s.cancel(); s.cancel();81s.request(MAX_VALUE); s.request(MAX_VALUE); s.request(MAX_VALUE);82s.request(-1); s.request(-100); s.request(MIN_VALUE);83assertEqualsWithRetry(publisher::getNumberOfSubscribers, 0);84executor.shutdown();85}8687@DataProvider(name = "sizeAndItems")88public Object[][] sizeAndItems() {89return new Object[][] {90// bufferSize and item bytes must be equal to count onNext calls91// bufferSize items92{ 1, List.of(wrap(new byte[] { 1 })) },93{ 2, List.of(wrap(new byte[] { 1, 2 })) },94{ 3, List.of(wrap(new byte[] { 1, 2, 3})) },95{ 4, List.of(wrap(new byte[] { 1, 2 , 3, 4})) },96{ 5, List.of(wrap(new byte[] { 1, 2 , 3, 4, 5})) },97{ 6, List.of(wrap(new byte[] { 1, 2 , 3, 4, 5, 6})) },98{ 7, List.of(wrap(new byte[] { 1, 2 , 3, 4, 5, 6, 7})) },99{ 8, List.of(wrap(new byte[] { 1, 2 , 3, 4, 5, 6, 7, 8})) },100{ 9, List.of(wrap(new byte[] { 1, 2 , 3, 4, 5, 6, 7, 8, 9})) },101{ 10, List.of(wrap(new byte[] { 1, 2 , 3, 4, 5, 6, 7, 8, 9, 10})) },102};103}104105@Test(dataProvider = "sizeAndItems")106public void cancelWithItemsPublished(int bufferSize, List<ByteBuffer> items)107throws Exception108{109ExecutorService executor = Executors.newFixedThreadPool(1);110SubmissionPublisher<List<ByteBuffer>> publisher =111new SubmissionPublisher<>(executor, 24);112113final int ITERATION_TIMES = 10;114// onSubscribe + onNext ITERATION_TIMES115CountDownLatch gate = new CountDownLatch(1 + ITERATION_TIMES);116ExposingSubscriber exposingSubscriber = new ExposingSubscriber(gate);117BodySubscriber subscriber = buffering(exposingSubscriber, bufferSize);118publisher.subscribe(subscriber);119120assertEqualsWithRetry(publisher::getNumberOfSubscribers, 1);121IntStream.range(0, ITERATION_TIMES).forEach(x -> publisher.submit(items));122gate.await(30, SECONDS);123exposingSubscriber.subscription.cancel();124IntStream.range(0, ITERATION_TIMES+1).forEach(x -> publisher.submit(items));125126assertEqualsWithRetry(publisher::getNumberOfSubscribers, 0);127assertEquals(exposingSubscriber.onNextInvocations, ITERATION_TIMES);128executor.shutdown();129}130131// same as above but with more racy conditions, do not wait on the gate132@Test(dataProvider = "sizeAndItems")133public void cancelWithItemsPublishedNoWait(int bufferSize, List<ByteBuffer> items)134throws Exception135{136ExecutorService executor = Executors.newFixedThreadPool(1);137SubmissionPublisher<List<ByteBuffer>> publisher =138new SubmissionPublisher<>(executor, 24);139140final int ITERATION_TIMES = 10;141// any callback will so, since onSub is guaranteed to be before onNext142CountDownLatch gate = new CountDownLatch(1);143ExposingSubscriber exposingSubscriber = new ExposingSubscriber(gate);144BodySubscriber subscriber = buffering(exposingSubscriber, bufferSize);145publisher.subscribe(subscriber);146147IntStream.range(0, ITERATION_TIMES).forEach(x -> publisher.submit(items));148gate.await(30, SECONDS);149exposingSubscriber.subscription.cancel();150IntStream.range(0, ITERATION_TIMES+1).forEach(x -> publisher.submit(items));151152int onNextInvocations = exposingSubscriber.onNextInvocations;153assertTrue(onNextInvocations <= ITERATION_TIMES,154"Expected <= " + ITERATION_TIMES + ", got " + onNextInvocations);155executor.shutdown();156}157158static class ExposingSubscriber implements BodySubscriber<Void> {159final CountDownLatch gate;160volatile Subscription subscription;161volatile int onNextInvocations;162163ExposingSubscriber(CountDownLatch gate) {164this.gate = gate;165}166167@Override168public void onSubscribe(Subscription subscription) {169//out.println("onSubscribe " + subscription);170this.subscription = subscription;171gate.countDown();172subscription.request(MAX_VALUE); // forever173}174175@Override176public void onNext(List<ByteBuffer> item) {177//out.println("onNext " + item);178onNextInvocations++;179gate.countDown();180}181182@Override183public void onError(Throwable throwable) {184out.println("onError " + throwable);185}186187@Override188public void onComplete() {189out.println("onComplete ");190}191192@Override193public CompletionStage<Void> getBody() {194throw new UnsupportedOperationException("getBody is unsupported");195}196}197198// There is a race between cancellation and subscriber callbacks, the199// following mechanism retries a number of times to allow for this race. The200// only requirement is that the expected result is actually observed.201202static final int TEST_RECHECK_TIMES = 30;203204static void assertEqualsWithRetry(IntSupplier actualSupplier, int expected)205throws Exception206{207int actual = expected + 1; // anything other than expected208for (int i=0; i< TEST_RECHECK_TIMES; i++) {209actual = actualSupplier.getAsInt();210if (actual == expected)211return;212Thread.sleep(100);213}214assertEquals(actual, expected); // will fail with the usual testng message215}216}217218219