Search in sources :

Example 86 with AtomicReference

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

the class EventLoopGroupTest method testNettyServerUsesContextEventLoop.

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channel(NioServerSocketChannel.class);
    bs.option(ChannelOption.SO_BACKLOG, 100);
    bs.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            assertSame(contextThread.get(), Thread.currentThread());
            context.executeFromIO(() -> {
                assertSame(contextThread.get(), Thread.currentThread());
                assertSame(context, Vertx.currentContext());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = (ByteBuf) msg;
                        assertEquals("hello", buf.toString(StandardCharsets.UTF_8));
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        });
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    bs.bind("localhost", 1234).sync();
    vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
        assertTrue(ar.succeeded());
        NetSocket so = ar.result();
        so.write(Buffer.buffer("hello"));
    });
    await();
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NetClientOptions(io.vertx.core.net.NetClientOptions) ContextInternal(io.vertx.core.impl.ContextInternal) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 87 with AtomicReference

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

the class DeploymentTest method testIsolationGroup.

// TODO
// Multi-threaded workers
private void testIsolationGroup(String group1, String group2, int count1, int count2, List<String> isolatedClasses, String verticleID) throws Exception {
    Map<String, Integer> countMap = new ConcurrentHashMap<>();
    vertx.eventBus().<JsonObject>consumer("testcounts").handler((Message<JsonObject> msg) -> {
        countMap.put(msg.body().getString("deploymentID"), msg.body().getInteger("count"));
    });
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<String> deploymentID1 = new AtomicReference<>();
    AtomicReference<String> deploymentID2 = new AtomicReference<>();
    vertx.deployVerticle(verticleID, new DeploymentOptions().setIsolationGroup(group1).setIsolatedClasses(isolatedClasses), ar -> {
        assertTrue(ar.succeeded());
        deploymentID1.set(ar.result());
        assertEquals(0, TestVerticle.instanceCount.get());
        vertx.deployVerticle(verticleID, new DeploymentOptions().setIsolationGroup(group2).setIsolatedClasses(isolatedClasses), ar2 -> {
            assertTrue(ar2.succeeded());
            deploymentID2.set(ar2.result());
            assertEquals(0, TestVerticle.instanceCount.get());
            latch.countDown();
        });
    });
    awaitLatch(latch);
    // Wait until two entries in the map
    waitUntil(() -> countMap.size() == 2);
    assertEquals(count1, countMap.get(deploymentID1.get()).intValue());
    assertEquals(count2, countMap.get(deploymentID2.get()).intValue());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Message(io.vertx.core.eventbus.Message) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 88 with AtomicReference

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

the class ContextTest method testWorkerExecuteFromIo.

@Test
public void testWorkerExecuteFromIo() throws Exception {
    AtomicReference<ContextInternal> workerContext = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    vertx.deployVerticle(new AbstractVerticle() {

        @Override
        public void start() throws Exception {
            workerContext.set((ContextInternal) context);
            latch.countDown();
        }
    }, new DeploymentOptions().setWorker(true));
    awaitLatch(latch);
    workerContext.get().nettyEventLoop().execute(() -> {
        assertNull(Vertx.currentContext());
        workerContext.get().executeFromIO(() -> {
            assertSame(workerContext.get(), Vertx.currentContext());
            assertTrue(Context.isOnWorkerThread());
            testComplete();
        });
    });
    await();
}
Also used : DeploymentOptions(io.vertx.core.DeploymentOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) ContextInternal(io.vertx.core.impl.ContextInternal) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractVerticle(io.vertx.core.AbstractVerticle) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Test(org.junit.Test)

Example 89 with AtomicReference

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

the class Usage method testGETAsync.

@Test
public void testGETAsync() throws Exception {
    HttpClient client = new HttpClient();
    client.start();
    final AtomicReference<Response> responseRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    client.newRequest("localhost", 8080).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded()) {
                responseRef.set(result.getResponse());
                latch.countDown();
            }
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Response response = responseRef.get();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
}
Also used : HttpClient(org.eclipse.jetty.client.HttpClient) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 90 with AtomicReference

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

the class HttpChannelState method onTimeout.

protected void onTimeout() {
    final List<AsyncListener> listeners;
    AsyncContextEvent event;
    try (Locker.Lock lock = _locker.lock()) {
        if (LOG.isDebugEnabled())
            LOG.debug("onTimeout {}", toStringLocked());
        if (_async != Async.STARTED)
            return;
        _async = Async.EXPIRING;
        event = _event;
        listeners = _asyncListeners;
    }
    final AtomicReference<Throwable> error = new AtomicReference<>();
    if (listeners != null) {
        Runnable task = new Runnable() {

            @Override
            public void run() {
                for (AsyncListener listener : listeners) {
                    try {
                        listener.onTimeout(event);
                    } catch (Throwable x) {
                        LOG.warn(x + " while invoking onTimeout listener " + listener);
                        LOG.debug(x);
                        if (error.get() == null)
                            error.set(x);
                        else
                            error.get().addSuppressed(x);
                    }
                }
            }

            @Override
            public String toString() {
                return "onTimeout";
            }
        };
        runInContext(event, task);
    }
    Throwable th = error.get();
    boolean dispatch = false;
    try (Locker.Lock lock = _locker.lock()) {
        switch(_async) {
            case EXPIRING:
                _async = th == null ? Async.EXPIRED : Async.ERRORING;
                break;
            case COMPLETE:
            case DISPATCH:
                if (th != null) {
                    LOG.ignore(th);
                    th = null;
                }
                break;
            default:
                throw new IllegalStateException();
        }
        if (_state == State.ASYNC_WAIT) {
            _state = State.ASYNC_WOKEN;
            dispatch = true;
        }
    }
    if (th != null) {
        if (LOG.isDebugEnabled())
            LOG.debug("Error after async timeout {}", this, th);
        onError(th);
    }
    if (dispatch) {
        if (LOG.isDebugEnabled())
            LOG.debug("Dispatch after async timeout {}", this);
        scheduleDispatch();
    }
}
Also used : Locker(org.eclipse.jetty.util.thread.Locker) AsyncListener(javax.servlet.AsyncListener) AtomicReference(java.util.concurrent.atomic.AtomicReference)

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