Search in sources :

Example 66 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class FlowControlStrategyTest method testServerFlowControlOneBigWrite.

@Test
public void testServerFlowControlOneBigWrite() throws Exception {
    final int windowSize = 1536;
    final int length = 5 * windowSize;
    final CountDownLatch settingsLatch = new CountDownLatch(1);
    start(new ServerSessionListener.Adapter() {

        @Override
        public void onSettings(Session session, SettingsFrame frame) {
            settingsLatch.countDown();
        }

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame requestFrame) {
            MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
            HeadersFrame responseFrame = new HeadersFrame(stream.getId(), metaData, null, false);
            CompletableFuture<Void> completable = new CompletableFuture<>();
            stream.headers(responseFrame, Callback.from(completable));
            completable.thenRun(() -> {
                DataFrame dataFrame = new DataFrame(stream.getId(), ByteBuffer.allocate(length), true);
                stream.data(dataFrame, Callback.NOOP);
            });
            return null;
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    Map<Integer, Integer> settings = new HashMap<>();
    settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, windowSize);
    session.settings(new SettingsFrame(settings, false), Callback.NOOP);
    Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS));
    final CountDownLatch dataLatch = new CountDownLatch(1);
    final Exchanger<Callback> exchanger = new Exchanger<>();
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    HeadersFrame requestFrame = new HeadersFrame(metaData, null, true);
    session.newStream(requestFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        private AtomicInteger dataFrames = new AtomicInteger();

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            try {
                int dataFrames = this.dataFrames.incrementAndGet();
                if (dataFrames == 1 || dataFrames == 2) {
                    // Do not consume the data frame.
                    // We should then be flow-control stalled.
                    exchanger.exchange(callback);
                } else if (dataFrames == 3 || dataFrames == 4 || dataFrames == 5) {
                    // Consume totally.
                    callback.succeeded();
                    if (frame.isEndStream())
                        dataLatch.countDown();
                } else {
                    Assert.fail();
                }
            } catch (InterruptedException x) {
                callback.failed(x);
            }
        }
    });
    Callback callback = exchanger.exchange(null, 5, TimeUnit.SECONDS);
    checkThatWeAreFlowControlStalled(exchanger);
    // Consume the first chunk.
    callback.succeeded();
    callback = exchanger.exchange(null, 5, TimeUnit.SECONDS);
    checkThatWeAreFlowControlStalled(exchanger);
    // Consume the second chunk.
    callback.succeeded();
    Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) Exchanger(java.util.concurrent.Exchanger) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) CompletableFuture(java.util.concurrent.CompletableFuture) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HTTP2Stream(org.eclipse.jetty.http2.HTTP2Stream) Stream(org.eclipse.jetty.http2.api.Stream) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FuturePromise(org.eclipse.jetty.util.FuturePromise) Promise(org.eclipse.jetty.util.Promise) Callback(org.eclipse.jetty.util.Callback) FutureCallback(org.eclipse.jetty.util.FutureCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 67 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class FlowControlStrategyTest method testClientFlowControlOneBigWrite.

@Test
public void testClientFlowControlOneBigWrite() throws Exception {
    final int windowSize = 1536;
    final Exchanger<Callback> exchanger = new Exchanger<>();
    final CountDownLatch settingsLatch = new CountDownLatch(1);
    final CountDownLatch dataLatch = new CountDownLatch(1);
    start(new ServerSessionListener.Adapter() {

        @Override
        public Map<Integer, Integer> onPreface(Session session) {
            Map<Integer, Integer> settings = new HashMap<>();
            settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, windowSize);
            return settings;
        }

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame requestFrame) {
            MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
            HeadersFrame responseFrame = new HeadersFrame(stream.getId(), metaData, null, true);
            stream.headers(responseFrame, Callback.NOOP);
            return new Stream.Listener.Adapter() {

                private AtomicInteger dataFrames = new AtomicInteger();

                @Override
                public void onData(Stream stream, DataFrame frame, Callback callback) {
                    try {
                        int dataFrames = this.dataFrames.incrementAndGet();
                        if (dataFrames == 1 || dataFrames == 2) {
                            // Do not consume the data frame.
                            // We should then be flow-control stalled.
                            exchanger.exchange(callback);
                        } else if (dataFrames == 3 || dataFrames == 4 || dataFrames == 5) {
                            // Consume totally.
                            callback.succeeded();
                            if (frame.isEndStream())
                                dataLatch.countDown();
                        } else {
                            Assert.fail();
                        }
                    } catch (InterruptedException x) {
                        callback.failed(x);
                    }
                }
            };
        }
    });
    Session session = newClient(new Session.Listener.Adapter() {

        @Override
        public void onSettings(Session session, SettingsFrame frame) {
            settingsLatch.countDown();
        }
    });
    Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS));
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    HeadersFrame requestFrame = new HeadersFrame(metaData, null, false);
    FuturePromise<Stream> streamPromise = new FuturePromise<>();
    session.newStream(requestFrame, streamPromise, null);
    Stream stream = streamPromise.get(5, TimeUnit.SECONDS);
    final int length = 5 * windowSize;
    DataFrame dataFrame = new DataFrame(stream.getId(), ByteBuffer.allocate(length), true);
    stream.data(dataFrame, Callback.NOOP);
    Callback callback = exchanger.exchange(null, 5, TimeUnit.SECONDS);
    checkThatWeAreFlowControlStalled(exchanger);
    // Consume the first chunk.
    callback.succeeded();
    callback = exchanger.exchange(null, 5, TimeUnit.SECONDS);
    checkThatWeAreFlowControlStalled(exchanger);
    // Consume the second chunk.
    callback.succeeded();
    Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Exchanger(java.util.concurrent.Exchanger) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HTTP2Stream(org.eclipse.jetty.http2.HTTP2Stream) Stream(org.eclipse.jetty.http2.api.Stream) FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) Callback(org.eclipse.jetty.util.Callback) FutureCallback(org.eclipse.jetty.util.FutureCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) HashMap(java.util.HashMap) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 68 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class AsyncIOTest method testSomeContentAvailableAfterServiceReturns.

@Test
public void testSomeContentAvailableAfterServiceReturns() throws Exception {
    final AtomicInteger count = new AtomicInteger();
    start(new HttpServlet() {

        @Override
        protected void service(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            final AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            request.getInputStream().setReadListener(new EmptyReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    count.incrementAndGet();
                    ServletInputStream input = request.getInputStream();
                    while (input.isReady()) {
                        int read = input.read();
                        if (read < 0)
                            break;
                    }
                    if (input.isFinished())
                        asyncContext.complete();
                }
            });
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, false);
    final CountDownLatch latch = new CountDownLatch(1);
    FuturePromise<Stream> promise = new FuturePromise<>();
    session.newStream(frame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                latch.countDown();
        }
    });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    // Wait until service() returns.
    Thread.sleep(1000);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(1), false), Callback.NOOP);
    // Wait until onDataAvailable() returns.
    Thread.sleep(1000);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(1), true), Callback.NOOP);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    // Make sure onDataAvailable() has been called twice
    Assert.assertEquals(2, count.get());
}
Also used : ReadListener(javax.servlet.ReadListener) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServletInputStream(javax.servlet.ServletInputStream) Stream(org.eclipse.jetty.http2.api.Stream) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 69 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class ThreadMonitorTest method monitorTest.

@Ignore
@Test
public void monitorTest() throws Exception {
    try (StacklessLogging stackless = new StacklessLogging(ThreadMonitor.class)) {
        final AtomicInteger countLogs = new AtomicInteger(0);
        final AtomicInteger countSpin = new AtomicInteger(0);
        ThreadMonitor monitor = new ThreadMonitor(1000, 50, 1, 1) {

            @Override
            protected void logThreadInfo(boolean logAll) {
                if (logAll)
                    countLogs.incrementAndGet();
                else
                    countSpin.incrementAndGet();
                super.logThreadInfo(logAll);
            }
        };
        monitor.setDumpable(new Dumpable() {

            public void dump(Appendable out, String indent) throws IOException {
                out.append(dump());
            }

            public String dump() {
                return "Dump Spinning";
            }
        });
        monitor.logCpuUsage(2000, 0);
        monitor.start();
        Random rnd = new Random();
        for (long cnt = 0; cnt < 100; cnt++) {
            long value = rnd.nextLong() % 50 + 50;
            Sleeper sleeper = new Sleeper(value);
            Thread runner = new Thread(sleeper);
            runner.setDaemon(true);
            runner.start();
        }
        Spinner spinner = new Spinner();
        Thread runner = new Thread(spinner);
        runner.start();
        Thread.sleep(DURATION);
        spinner.setDone();
        monitor.stop();
        assertTrue(countLogs.get() >= 1);
        assertTrue(countSpin.get() >= 2);
    }
}
Also used : Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) IOException(java.io.IOException) Dumpable(org.eclipse.jetty.util.component.Dumpable) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 70 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class ConnectionOpenCloseTest method testOpenRequestClose.

@Slow
@Test
public void testOpenRequestClose() throws Exception {
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
        }
    });
    server.start();
    final AtomicInteger callbacks = new AtomicInteger();
    final CountDownLatch openLatch = new CountDownLatch(1);
    final CountDownLatch closeLatch = new CountDownLatch(1);
    connector.addBean(new Connection.Listener.Adapter() {

        @Override
        public void onOpened(Connection connection) {
            callbacks.incrementAndGet();
            openLatch.countDown();
        }

        @Override
        public void onClosed(Connection connection) {
            callbacks.incrementAndGet();
            closeLatch.countDown();
        }
    });
    try (Socket socket = new Socket("localhost", connector.getLocalPort())) {
        socket.setSoTimeout((int) connector.getIdleTimeout());
        OutputStream output = socket.getOutputStream();
        output.write(("GET / HTTP/1.1\r\n" + "Host: localhost:" + connector.getLocalPort() + "\r\n" + "Connection: close\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8));
        output.flush();
        InputStream inputStream = socket.getInputStream();
        HttpTester.Response response = HttpTester.parseResponse(inputStream);
        assertThat("Status Code", response.getStatus(), is(200));
        Assert.assertEquals(-1, inputStream.read());
        socket.close();
        Assert.assertTrue(openLatch.await(5, TimeUnit.SECONDS));
        Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS));
        // Wait some time to see if the callbacks are called too many times
        TimeUnit.SECONDS.sleep(1);
        Assert.assertEquals(2, callbacks.get());
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) Connection(org.eclipse.jetty.io.Connection) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Test(org.junit.Test) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow)

Aggregations

AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7986 Test (org.junit.Test)3775 CountDownLatch (java.util.concurrent.CountDownLatch)1072 ArrayList (java.util.ArrayList)1018 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)849 List (java.util.List)740 IOException (java.io.IOException)719 AtomicReference (java.util.concurrent.atomic.AtomicReference)574 HashMap (java.util.HashMap)499 Map (java.util.Map)460 Test (org.testng.annotations.Test)419 File (java.io.File)337 ExecutorService (java.util.concurrent.ExecutorService)337 Test (org.junit.jupiter.api.Test)334 AtomicLong (java.util.concurrent.atomic.AtomicLong)329 TimeUnit (java.util.concurrent.TimeUnit)323 HashSet (java.util.HashSet)315 Arrays (java.util.Arrays)308 Set (java.util.Set)284 Collections (java.util.Collections)266