Example usage for io.netty.channel Channel unsafe

List of usage examples for io.netty.channel Channel unsafe

Introduction

In this page you can find the example usage for io.netty.channel Channel unsafe.

Prototype

Unsafe unsafe();

Source Link

Document

Returns an internal-use-only object that provides unsafe operations.

Usage

From source file:at.yawk.accordion.netty.NettyConnection.java

License:Mozilla Public License

/**
 * Tries to close a channel through a bunch of different methods, ensuring no file descriptors are leaked.
 *//*from   ww w.  ja  va 2  s. c  o m*/
static void close(Channel channel) {
    try {
        // first, disconnect
        channel.disconnect().addListener(f -> {
            try {
                // close
                channel.close().addListener(g -> {
                    try {
                        // use unsafe access to make sure underlying socket is closed
                        channel.unsafe().closeForcibly();
                    } catch (Exception ignored) {
                    }
                });
            } catch (Exception ignored) {
            }
        });
    } catch (Exception ignored) {
    }
}

From source file:channel.ClientChannel.java

@Override
public Channel.Unsafe unsafe() {
    return ch.unsafe();
}

From source file:com.lambdaworks.redis.reliability.AtLeastOnceTest.java

License:Apache License

@Test
public void commandNotFailedChannelClosesWhileFlush() throws Exception {

    assumeTrue(Version.identify().get("netty-transport").artifactVersion().startsWith("4.0.2"));

    RedisCommands<String, String> connection = client.connect().sync();
    RedisCommands<String, String> verificationConnection = client.connect().sync();
    RedisChannelWriter<String, String> channelWriter = getRedisChannelHandler(connection).getChannelWriter();

    connection.set(key, "1");
    assertThat(verificationConnection.get(key)).isEqualTo("1");

    final CountDownLatch block = new CountDownLatch(1);

    ConnectionWatchdog connectionWatchdog = Connections
            .getConnectionWatchdog(connection.getStatefulConnection());

    AsyncCommand<String, String, Object> command = getBlockOnEncodeCommand(block);

    channelWriter.write(command);/*from  w w w.  java 2s .  c o  m*/

    connectionWatchdog.setReconnectSuspended(true);

    Channel channel = getChannel(getRedisChannelHandler(connection));
    channel.unsafe().disconnect(channel.newPromise());

    assertThat(channel.isOpen()).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();
    block.countDown();
    assertThat(command.await(2, TimeUnit.SECONDS)).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();

    assertThat(verificationConnection.get(key)).isEqualTo("1");

    assertThat(getQueue(getRedisChannelHandler(connection))).isEmpty();
    assertThat(getCommandBuffer(getRedisChannelHandler(connection))).isNotEmpty().contains(command);

    connection.close();
}

From source file:com.lambdaworks.redis.reliability.AtLeastOnceTest.java

License:Apache License

@Test
public void commandRetriedChannelClosesWhileFlush() throws Exception {

    assumeTrue(Version.identify().get("netty-transport").artifactVersion().startsWith("4.0.2"));

    RedisCommands<String, String> connection = client.connect().sync();
    RedisCommands<String, String> verificationConnection = client.connect().sync();
    RedisChannelWriter<String, String> channelWriter = getRedisChannelHandler(connection).getChannelWriter();

    connection.set(key, "1");
    assertThat(verificationConnection.get(key)).isEqualTo("1");

    final CountDownLatch block = new CountDownLatch(1);

    ConnectionWatchdog connectionWatchdog = Connections
            .getConnectionWatchdog(connection.getStatefulConnection());

    AsyncCommand<String, String, Object> command = getBlockOnEncodeCommand(block);

    channelWriter.write(command);/*from   w  ww  .  jav  a 2s  . c  o  m*/

    connectionWatchdog.setReconnectSuspended(true);

    Channel channel = getChannel(getRedisChannelHandler(connection));
    channel.unsafe().disconnect(channel.newPromise());

    assertThat(channel.isOpen()).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();
    block.countDown();
    assertThat(command.await(2, TimeUnit.SECONDS)).isFalse();

    connectionWatchdog.setReconnectSuspended(false);
    connectionWatchdog.scheduleReconnect();

    assertThat(command.await(2, TimeUnit.SECONDS)).isTrue();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isTrue();

    assertThat(verificationConnection.get(key)).isEqualTo("2");

    assertThat(getQueue(getRedisChannelHandler(connection))).isEmpty();
    assertThat(getCommandBuffer(getRedisChannelHandler(connection))).isEmpty();

    connection.close();
    verificationConnection.close();
}

From source file:com.lambdaworks.redis.reliability.AtMostOnceTest.java

License:Apache License

@Test
public void commandNotExecutedChannelClosesWhileFlush() throws Exception {

    assumeTrue(Version.identify().get("netty-transport").artifactVersion().startsWith("4.0.2"));

    RedisCommands<String, String> connection = client.connect().sync();
    RedisCommands<String, String> verificationConnection = client.connect().sync();
    RedisChannelWriter<String, String> channelWriter = getRedisChannelHandler(connection).getChannelWriter();

    connection.set(key, "1");
    assertThat(verificationConnection.get(key)).isEqualTo("1");

    final CountDownLatch block = new CountDownLatch(1);

    AsyncCommand<String, String, Object> command = new AsyncCommand<String, String, Object>(
            new Command<>(CommandType.INCR, new IntegerOutput(CODEC), new CommandArgs<>(CODEC).addKey(key))) {

        @Override//from   ww  w .j a va2  s . c o m
        public void encode(ByteBuf buf) {
            try {
                block.await();
            } catch (InterruptedException e) {
            }
            super.encode(buf);
        }
    };

    channelWriter.write(command);

    Channel channel = getChannel(getRedisChannelHandler(connection));
    channel.unsafe().disconnect(channel.newPromise());

    assertThat(channel.isOpen()).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();
    block.countDown();
    assertThat(command.await(2, TimeUnit.SECONDS)).isTrue();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isTrue();

    assertThat(verificationConnection.get(key)).isEqualTo("1");

    assertThat(getQueue(getRedisChannelHandler(connection))).isEmpty();
    assertThat(getCommandBuffer(getRedisChannelHandler(connection))).isEmpty();

    connection.close();
}

From source file:com.linecorp.armeria.internal.ConnectionLimitingHandler.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    final Channel child = (Channel) msg;

    int conn = numConnections.incrementAndGet();
    if (conn > 0 && conn <= maxNumConnections) {
        childChannels.add(child);//from w ww.j a  va  2  s  .  c  o  m
        child.closeFuture().addListener(future -> {
            childChannels.remove(child);
            numConnections.decrementAndGet();
        });
        super.channelRead(ctx, msg);
    } else {
        numConnections.decrementAndGet();

        // Set linger option to 0 so that the server doesn't get too many TIME_WAIT states.
        child.config().setOption(ChannelOption.SO_LINGER, 0);
        child.unsafe().closeForcibly();

        numDroppedConnections.increment();

        if (loggingScheduled.compareAndSet(false, true)) {
            ctx.executor().schedule(this::writeNumDroppedConnectionsLog, 1, TimeUnit.SECONDS);
        }
    }
}

From source file:com.test.AbstractBootstrap.java

License:Apache License

final ChannelFuture initAndRegister() {
    final Channel channel = channelFactory().newChannel();
    try {/*  w w w.  ja v  a 2  s.  com*/
        init(channel);
    } catch (Throwable t) {
        channel.unsafe().closeForcibly();
        // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
        return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
    }

    ChannelFuture regFuture = group().register(channel);
    if (regFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
    }

    // If we are here and the promise is not failed, it's one of the following cases:
    // 1) If we attempted registration from the event loop, the registration has been completed at this point.
    //    i.e. It's safe to attempt bind() or connect() now because the channel has been registered.
    // 2) If we attempted registration from the other thread, the registration request has been successfully
    //    added to the event loop's task queue for later execution.
    //    i.e. It's safe to attempt bind() or connect() now:
    //         because bind() or connect() will be executed *after* the scheduled registration task is executed
    //         because register(), bind(), and connect() are all bound to the same thread.

    return regFuture;
}

From source file:cz.znj.kvr.sw.exp.java.netty.netty.MyEmbeddedEventLoop.java

License:Apache License

@Override
public ChannelFuture register(Channel channel, ChannelPromise promise) {
    channel.unsafe().register(this, promise);
    return promise;
}

From source file:io.lettuce.core.reliability.AtLeastOnceTest.java

License:Apache License

@Test
public void commandNotFailedChannelClosesWhileFlush() throws Exception {

    assumeTrue(Version.identify().get("netty-transport").artifactVersion().startsWith("4.0.2"));

    StatefulRedisConnection<String, String> connection = client.connect();
    RedisCommands<String, String> verificationConnection = client.connect().sync();
    RedisChannelWriter channelWriter = ConnectionTestUtil.getChannelWriter(connection);

    RedisCommands<String, String> sync = connection.sync();
    sync.set(key, "1");
    assertThat(verificationConnection.get(key)).isEqualTo("1");

    final CountDownLatch block = new CountDownLatch(1);

    ConnectionWatchdog connectionWatchdog = ConnectionTestUtil.getConnectionWatchdog(connection);

    AsyncCommand<String, String, Object> command = getBlockOnEncodeCommand(block);

    channelWriter.write(command);/* w ww .j  a va 2s .  c o m*/

    connectionWatchdog.setReconnectSuspended(true);

    Channel channel = ConnectionTestUtil.getChannel(connection);
    channel.unsafe().disconnect(channel.newPromise());

    assertThat(channel.isOpen()).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();
    block.countDown();
    assertThat(command.await(2, TimeUnit.SECONDS)).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();

    assertThat(verificationConnection.get(key)).isEqualTo("1");

    assertThat(ConnectionTestUtil.getStack(connection)).isEmpty();
    assertThat(ConnectionTestUtil.getCommandBuffer(connection)).isNotEmpty().contains(command);

    connection.close();
}

From source file:io.lettuce.core.reliability.AtLeastOnceTest.java

License:Apache License

@Test
public void commandRetriedChannelClosesWhileFlush() throws Exception {

    assumeTrue(Version.identify().get("netty-transport").artifactVersion().startsWith("4.0.2"));

    StatefulRedisConnection<String, String> connection = client.connect();
    RedisCommands<String, String> sync = connection.sync();
    RedisCommands<String, String> verificationConnection = client.connect().sync();
    RedisChannelWriter channelWriter = ConnectionTestUtil.getChannelWriter(connection);

    sync.set(key, "1");
    assertThat(verificationConnection.get(key)).isEqualTo("1");

    final CountDownLatch block = new CountDownLatch(1);

    ConnectionWatchdog connectionWatchdog = ConnectionTestUtil
            .getConnectionWatchdog(sync.getStatefulConnection());

    AsyncCommand<String, String, Object> command = getBlockOnEncodeCommand(block);

    channelWriter.write(command);/*from ww w .  j a v  a2s .  c o  m*/

    connectionWatchdog.setReconnectSuspended(true);

    Channel channel = ConnectionTestUtil.getChannel(sync.getStatefulConnection());
    channel.unsafe().disconnect(channel.newPromise());

    assertThat(channel.isOpen()).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();
    block.countDown();
    assertThat(command.await(2, TimeUnit.SECONDS)).isFalse();

    connectionWatchdog.setReconnectSuspended(false);
    connectionWatchdog.scheduleReconnect();

    assertThat(command.await(2, TimeUnit.SECONDS)).isTrue();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isTrue();

    assertThat(verificationConnection.get(key)).isEqualTo("2");

    assertThat(ConnectionTestUtil.getStack(sync.getStatefulConnection())).isEmpty();
    assertThat(ConnectionTestUtil.getCommandBuffer(sync.getStatefulConnection())).isEmpty();

    sync.getStatefulConnection().close();
    verificationConnection.getStatefulConnection().close();
}