Search in sources :

Example 91 with AtomicReference

use of java.util.concurrent.atomic.AtomicReference in project vert.x by eclipse.

the class AsynchronousLockTest method testAcquireOnExecuteBlocking.

@Test
public void testAcquireOnExecuteBlocking() {
    Vertx vertx = getVertx();
    SharedData sharedData = vertx.sharedData();
    AtomicReference<Long> start = new AtomicReference<>();
    vertx.<Lock>executeBlocking(future -> {
        CountDownLatch acquireLatch = new CountDownLatch(1);
        AtomicReference<AsyncResult<Lock>> lockReference = new AtomicReference<>();
        sharedData.getLock("foo", ar -> {
            lockReference.set(ar);
            acquireLatch.countDown();
        });
        try {
            awaitLatch(acquireLatch);
            AsyncResult<Lock> ar = lockReference.get();
            if (ar.succeeded()) {
                future.complete(ar.result());
            } else {
                future.fail(ar.cause());
            }
        } catch (InterruptedException e) {
            future.fail(e);
        }
    }, ar -> {
        if (ar.succeeded()) {
            start.set(System.currentTimeMillis());
            vertx.setTimer(1000, tid -> {
                ar.result().release();
            });
            vertx.executeBlocking(future -> {
                CountDownLatch acquireLatch = new CountDownLatch(1);
                AtomicReference<AsyncResult<Lock>> lockReference = new AtomicReference<>();
                sharedData.getLock("foo", ar2 -> {
                    lockReference.set(ar2);
                    acquireLatch.countDown();
                });
                try {
                    awaitLatch(acquireLatch);
                    AsyncResult<Lock> ar3 = lockReference.get();
                    if (ar3.succeeded()) {
                        future.complete(ar3.result());
                    } else {
                        future.fail(ar3.cause());
                    }
                } catch (InterruptedException e) {
                    future.fail(e);
                }
            }, ar4 -> {
                if (ar4.succeeded()) {
                    assertTrue(System.currentTimeMillis() - start.get() >= 1000);
                    testComplete();
                } else {
                    fail(ar4.cause());
                }
            });
        } else {
            fail(ar.cause());
        }
    });
    await();
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) Vertx(io.vertx.core.Vertx) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult) SharedData(io.vertx.core.shareddata.SharedData) Lock(io.vertx.core.shareddata.Lock) Test(org.junit.Test)

Example 92 with AtomicReference

use of java.util.concurrent.atomic.AtomicReference in project vert.x by eclipse.

the class AsynchronousLockTest method testAcquireOnSameEventLoop.

@Test
public void testAcquireOnSameEventLoop() {
    Vertx vertx = getVertx();
    Context context = vertx.getOrCreateContext();
    SharedData sharedData = vertx.sharedData();
    AtomicReference<Long> start = new AtomicReference<>();
    context.runOnContext(v -> {
        sharedData.getLock("foo", ar -> {
            assertTrue(ar.succeeded());
            start.set(System.currentTimeMillis());
            Lock lock = ar.result();
            vertx.setTimer(1000, tid -> {
                lock.release();
            });
            context.runOnContext(v2 -> {
                sharedData.getLock("foo", ar2 -> {
                    assertTrue(ar2.succeeded());
                    assertTrue(System.currentTimeMillis() - start.get() >= 1000);
                    testComplete();
                });
            });
        });
    });
    await();
}
Also used : Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Vertx(io.vertx.core.Vertx) SharedData(io.vertx.core.shareddata.SharedData) Lock(io.vertx.core.shareddata.Lock) Test(org.junit.Test)

Example 93 with AtomicReference

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

the class HttpRedirector method redirect.

/**
     * Redirects the given {@code response}, blocking until the redirect is complete.
     *
     * @param request the original request that triggered the redirect
     * @param response the response to the original request
     * @return a {@link Result} object containing the request to the redirected location and its response
     * @throws InterruptedException if the thread is interrupted while waiting for the redirect to complete
     * @throws ExecutionException if the redirect failed
     * @see #redirect(Request, Response, Response.CompleteListener)
     */
public Result redirect(Request request, Response response) throws InterruptedException, ExecutionException {
    final AtomicReference<Result> resultRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    Request redirect = redirect(request, response, new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            resultRef.set(new Result(result.getRequest(), result.getRequestFailure(), new HttpContentResponse(result.getResponse(), getContent(), getMediaType(), getEncoding()), result.getResponseFailure()));
            latch.countDown();
        }
    });
    try {
        latch.await();
        Result result = resultRef.get();
        if (result.isFailed())
            throw new ExecutionException(result.getFailure());
        return result;
    } catch (InterruptedException x) {
        // If the application interrupts, we need to abort the redirect
        redirect.abort(x);
        throw x;
    }
}
Also used : Request(org.eclipse.jetty.client.api.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutionException(java.util.concurrent.ExecutionException) Result(org.eclipse.jetty.client.api.Result) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener)

Example 94 with AtomicReference

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

the class HTTP2ServerTest method testRequestResponseNoContent.

@Test
public void testRequestResponseNoContent() throws Exception {
    final CountDownLatch latch = new CountDownLatch(3);
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            latch.countDown();
        }
    });
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    generator.control(lease, new HeadersFrame(1, metaData, null, true));
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) {
            output.write(BufferUtil.toArray(buffer));
        }
        final AtomicReference<HeadersFrame> frameRef = new AtomicReference<>();
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onSettings(SettingsFrame frame) {
                latch.countDown();
            }

            @Override
            public void onHeaders(HeadersFrame frame) {
                frameRef.set(frame);
                latch.countDown();
            }
        }, 4096, 8192);
        parseResponse(client, parser);
        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
        HeadersFrame response = frameRef.get();
        Assert.assertNotNull(response);
        MetaData.Response responseMetaData = (MetaData.Response) response.getMetaData();
        Assert.assertEquals(200, responseMetaData.getStatus());
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) HttpServletResponse(javax.servlet.http.HttpServletResponse) Socket(java.net.Socket) Test(org.junit.Test)

Example 95 with AtomicReference

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

the class CloseTest method testClientAbruptlyClosesConnection.

@Test
public void testClientAbruptlyClosesConnection() throws Exception {
    final CountDownLatch closeLatch = new CountDownLatch(1);
    final AtomicReference<Session> sessionRef = new AtomicReference<>();
    startServer(new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            try {
                sessionRef.set(stream.getSession());
                MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
                // Reply with HEADERS.
                stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP);
                closeLatch.await(5, TimeUnit.SECONDS);
                return null;
            } catch (InterruptedException x) {
                return null;
            }
        }
    });
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    generator.control(lease, new HeadersFrame(1, metaData, null, true));
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) {
            output.write(BufferUtil.toArray(buffer));
        }
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onHeaders(HeadersFrame frame) {
                try {
                    // Close the connection just after
                    // receiving the response headers.
                    client.close();
                    closeLatch.countDown();
                } catch (IOException x) {
                    throw new RuntimeIOException(x);
                }
            }
        }, 4096, 8192);
        parseResponse(client, parser);
        // We need to give some time to the server to receive and process the TCP FIN.
        Thread.sleep(1000);
        Session session = sessionRef.get();
        Assert.assertTrue(session.isClosed());
        Assert.assertTrue(((HTTP2Session) session).isDisconnected());
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) 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) Stream(org.eclipse.jetty.http2.api.Stream) OutputStream(java.io.OutputStream) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) AtomicReference(java.util.concurrent.atomic.AtomicReference) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Socket(java.net.Socket) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Aggregations

AtomicReference (java.util.concurrent.atomic.AtomicReference)1331 Test (org.junit.Test)668 CountDownLatch (java.util.concurrent.CountDownLatch)437 IOException (java.io.IOException)263 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)205 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)159 ArrayList (java.util.ArrayList)108 HashMap (java.util.HashMap)105 List (java.util.List)95 Map (java.util.Map)77 Test (org.testng.annotations.Test)76 File (java.io.File)64 ExecutionException (java.util.concurrent.ExecutionException)60 HashSet (java.util.HashSet)54 URI (java.net.URI)48 TimeoutException (java.util.concurrent.TimeoutException)48 HttpServletRequest (javax.servlet.http.HttpServletRequest)48 HttpServletResponse (javax.servlet.http.HttpServletResponse)46 MockResponse (okhttp3.mockwebserver.MockResponse)46 ByteBuffer (java.nio.ByteBuffer)44