From 6222101924df1bc0525ec89111fe25d46af77d34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=94=B0=E6=AC=A7?= Date: Tue, 29 Jan 2019 21:06:05 +0800 Subject: [PATCH] migrate java8: use lambda and method reference (#8781) Motivation: We can use lambdas now as we use Java8. Modification: use lambda function for all package, #8751 only migrate transport package. Result: Code cleanup. --- .../io/netty/buffer/ByteBufProcessor.java | 70 +- .../java/io/netty/buffer/ByteBufUtil.java | 7 +- .../io/netty/buffer/AbstractByteBufTest.java | 200 +++-- .../java/io/netty/buffer/ByteBufUtilTest.java | 15 +- .../buffer/PooledByteBufAllocatorTest.java | 68 +- .../codec/http/CombinedHttpHeaders.java | 14 +- .../codec/http/DefaultHttpHeaders.java | 38 +- .../codec/http/DefaultLastHttpContent.java | 15 +- .../codec/http/HttpObjectAggregator.java | 22 +- .../http/cookie/ClientCookieEncoder.java | 35 +- .../websocketx/WebSocketClientHandshaker.java | 49 +- ...bSocketClientProtocolHandshakeHandler.java | 15 +- .../websocketx/WebSocketServerHandshaker.java | 17 +- ...bSocketServerProtocolHandshakeHandler.java | 23 +- .../WebSocketServerExtensionHandler.java | 21 +- .../codec/spdy/DefaultSpdyHeaders.java | 7 +- .../handler/codec/spdy/SpdyFrameCodec.java | 9 +- .../codec/spdy/SpdySessionHandler.java | 36 +- .../codec/http/HttpClientCodecTest.java | 24 +- .../http/HttpServerUpgradeHandlerTest.java | 21 +- .../codec/http/cors/CorsHandlerTest.java | 7 +- .../codec/http2/DefaultHttp2Connection.java | 25 +- .../http2/DefaultHttp2ConnectionEncoder.java | 11 +- .../codec/http2/DefaultHttp2Headers.java | 54 +- .../DefaultHttp2RemoteFlowController.java | 9 +- .../codec/http2/Http2ConnectionHandler.java | 36 +- .../handler/codec/http2/Http2FrameCodec.java | 24 +- .../codec/http2/Http2HeadersEncoder.java | 14 +- .../codec/http2/Http2MultiplexCodec.java | 80 +- .../http2/Http2StreamChannelBootstrap.java | 32 +- ...airQueueByteDistributorDependencyTest.java | 25 +- ...leartextHttp2ServerUpgradeHandlerTest.java | 14 +- .../codec/http2/DataCompressionHttp2Test.java | 96 +-- .../DefaultHttp2ConnectionDecoderTest.java | 109 +-- .../DefaultHttp2ConnectionEncoderTest.java | 131 ++-- .../http2/DefaultHttp2ConnectionTest.java | 80 +- .../http2/DefaultHttp2FrameWriterTest.java | 15 +- .../DefaultHttp2RemoteFlowControllerTest.java | 59 +- .../codec/http2/HashCollisionTest.java | 24 +- .../handler/codec/http2/HpackTestCase.java | 7 +- .../http2/Http2ConnectionHandlerTest.java | 140 ++-- .../http2/Http2ConnectionRoundtripTest.java | 723 +++++++----------- .../codec/http2/Http2FrameCodecTest.java | 50 +- .../codec/http2/Http2FrameRoundtripTest.java | 22 +- .../codec/http2/Http2MultiplexCodecTest.java | 98 +-- .../handler/codec/http2/Http2TestUtil.java | 128 +--- .../HttpToHttp2ConnectionHandlerTest.java | 27 +- .../http2/InboundHttp2ToHttpAdapterTest.java | 200 ++--- .../codec/http2/LastInboundHandler.java | 5 +- .../http2/StreamBufferingEncoderTest.java | 24 +- .../UniformStreamByteDistributorTest.java | 19 +- ...ueueByteDistributorDependencyTreeTest.java | 11 +- .../codec/socksx/v5/Socks5AddressEncoder.java | 47 +- .../handler/codec/ByteToMessageDecoder.java | 104 ++- .../netty/handler/codec/CodecOutputList.java | 7 +- .../netty/handler/codec/DefaultHeaders.java | 7 +- .../handler/codec/MessageAggregator.java | 9 +- .../codec/compression/ByteBufChecksum.java | 9 +- .../compression/Bzip2BlockCompressor.java | 7 +- .../codec/compression/Bzip2Encoder.java | 23 +- .../codec/compression/JZlibEncoder.java | 23 +- .../codec/compression/JdkZlibEncoder.java | 23 +- .../codec/compression/Lz4FrameEncoder.java | 23 +- .../compression/Lz4FrameEncoderTest.java | 20 +- .../java/io/netty/util/BooleanSupplier.java | 14 +- .../java/io/netty/util/ByteProcessor.java | 28 +- .../src/main/java/io/netty/util/NetUtil.java | 89 ++- .../src/main/java/io/netty/util/Recycler.java | 7 +- .../util/ResourceLeakDetectorFactory.java | 8 +- .../io/netty/util/ThreadDeathWatcher.java | 9 +- .../netty/util/UncheckedBooleanSupplier.java | 14 +- .../AbstractScheduledEventExecutor.java | 21 +- .../netty/util/concurrent/DefaultPromise.java | 28 +- .../util/concurrent/GlobalEventExecutor.java | 18 +- .../MultithreadEventExecutorGroup.java | 9 +- .../concurrent/RejectedExecutionHandlers.java | 32 +- .../concurrent/SingleThreadEventExecutor.java | 121 ++- .../io/netty/util/internal/CleanerJava6.java | 38 +- .../io/netty/util/internal/CleanerJava9.java | 36 +- .../util/internal/NativeLibraryLoader.java | 46 +- .../io/netty/util/internal/ObjectCleaner.java | 76 +- .../util/internal/PlatformDependent.java | 16 +- .../util/internal/PlatformDependent0.java | 164 ++-- .../io/netty/util/internal/SocketUtils.java | 104 +-- .../util/internal/SystemPropertyUtil.java | 7 +- .../util/internal/logging/Log4J2Logger.java | 23 +- .../util/AbstractReferenceCountedTest.java | 40 +- .../java/io/netty/util/ConstantPoolTest.java | 7 +- .../io/netty/util/HashedWheelTimerTest.java | 62 +- .../java/io/netty/util/NettyRuntimeTests.java | 45 +- .../test/java/io/netty/util/RecyclerTest.java | 31 +- .../io/netty/util/ThreadDeathWatcherTest.java | 30 +- .../AbstractScheduledEventExecutorTest.java | 6 +- .../util/concurrent/DefaultPromiseTest.java | 140 +--- .../concurrent/DefaultThreadFactoryTest.java | 139 ++-- .../util/concurrent/FastThreadLocalTest.java | 51 +- .../concurrent/GlobalEventExecutorTest.java | 14 +- .../NonStickyEventExecutorGroupTest.java | 49 +- .../util/concurrent/PromiseCombinerTest.java | 10 +- .../SingleThreadEventExecutorTest.java | 51 +- .../UnorderedThreadPoolEventExecutorTest.java | 14 +- .../util/internal/ObjectCleanerTest.java | 58 +- .../util/internal/PlatformDependentTest.java | 15 +- .../example/discard/DiscardClientHandler.java | 15 +- .../factorial/FactorialClientHandler.java | 24 +- .../frame/server/Http2ServerInitializer.java | 15 +- .../server/Http2ServerInitializer.java | 15 +- .../server/Http2ServerInitializer.java | 13 +- .../http2/tiles/Http1RequestHandler.java | 15 +- .../http2/tiles/Http2RequestHandler.java | 7 +- .../proxy/HexDumpProxyBackendHandler.java | 13 +- .../proxy/HexDumpProxyFrontendHandler.java | 32 +- .../io/netty/example/redis/RedisClient.java | 11 +- .../securechat/SecureChatServerHandler.java | 21 +- .../socksproxy/SocksServerConnectHandler.java | 116 ++- .../io/netty/example/uptime/UptimeClient.java | 11 +- .../example/uptime/UptimeClientHandler.java | 9 +- .../io/netty/handler/proxy/ProxyHandler.java | 18 +- .../netty/handler/proxy/ProxyHandlerTest.java | 13 +- .../io/netty/handler/proxy/ProxyServer.java | 17 +- .../flush/FlushConsolidationHandler.java | 15 +- .../handler/ipfilter/UniqueIpFilter.java | 7 +- .../netty/handler/ssl/AbstractSniHandler.java | 35 +- .../io/netty/handler/ssl/Java9SslUtils.java | 48 +- .../JdkBaseApplicationProtocolNegotiator.java | 34 +- ...kDefaultApplicationProtocolNegotiator.java | 9 +- .../java/io/netty/handler/ssl/OpenSsl.java | 10 +- .../ssl/OpenSslX509TrustManagerWrapper.java | 58 +- .../ssl/ReferenceCountedOpenSslContext.java | 19 +- .../java/io/netty/handler/ssl/SslHandler.java | 151 ++-- .../handler/stream/ChunkedWriteHandler.java | 59 +- .../traffic/ChannelTrafficShapingHandler.java | 7 +- .../GlobalChannelTrafficShapingHandler.java | 7 +- .../traffic/GlobalTrafficShapingHandler.java | 7 +- .../handler/ipfilter/UniqueIpFilterTest.java | 19 +- .../netty/handler/ssl/JdkSslEngineTest.java | 23 +- .../ssl/ParameterizedSslHandlerTest.java | 39 +- .../io/netty/handler/ssl/RenegotiateTest.java | 13 +- .../io/netty/handler/ssl/SSLEngineTest.java | 7 +- .../io/netty/handler/ssl/SniClientTest.java | 9 +- .../io/netty/handler/ssl/SniHandlerTest.java | 7 +- .../io/netty/handler/ssl/SslHandlerTest.java | 43 +- .../io/netty/handler/ssl/ocsp/OcspTest.java | 7 +- .../stream/ChunkedWriteHandlerTest.java | 8 +- .../handler/timeout/IdleStateHandlerTest.java | 28 +- .../CompositeByteBufSequentialBenchmark.java | 7 +- .../epoll/EpollSocketChannelBenchmark.java | 7 +- .../BurstCostExecutorsBenchmark.java | 52 +- ...nnableScheduledFutureAdapterBenchmark.java | 34 +- .../NoPriorityByteDistributionBenchmark.java | 15 +- .../PrivilegedSocketOperationsBenchmark.java | 60 +- .../ResourceLeakDetectorRecordBenchmark.java | 7 +- .../netty/resolver/dns/DnsNameResolver.java | 31 +- .../netty/resolver/dns/DnsQueryContext.java | 45 +- .../netty/resolver/dns/DnsResolveContext.java | 95 ++- .../resolver/dns/InflightNameResolver.java | 14 +- ...efaultAuthoritativeDnsServerCacheTest.java | 38 +- .../resolver/dns/DefaultDnsCacheTest.java | 15 +- .../dns/DefaultDnsCnameCacheTest.java | 15 +- .../resolver/dns/DnsNameResolverTest.java | 328 ++++---- .../netty/resolver/AddressResolverGroup.java | 11 +- .../netty/resolver/CompositeNameResolver.java | 26 +- .../resolver/InetSocketAddressResolver.java | 36 +- .../RoundRobinInetAddressResolver.java | 52 +- .../http2/Http2ServerInitializer.java | 13 +- .../transport/sctp/SctpTestPermutation.java | 19 +- .../socket/SocketBufReleaseTest.java | 7 +- .../socket/SocketCloseForciblyTest.java | 9 +- .../socket/SocketHalfClosedTest.java | 56 +- .../socket/SocketTestPermutation.java | 46 +- .../socket/TrafficShapingHandlerTest.java | 18 +- .../io/netty/testsuite/util/TestUtils.java | 7 +- .../channel/epoll/AbstractEpollChannel.java | 54 +- .../epoll/AbstractEpollStreamChannel.java | 64 +- .../io/netty/channel/epoll/EpollHandler.java | 21 +- .../epoll/EpollRecvByteAllocatorHandle.java | 7 +- .../epoll/EpollDomainSocketFdTest.java | 11 +- .../channel/epoll/EpollEventLoopTest.java | 7 +- .../channel/epoll/EpollReuseAddrTest.java | 23 +- .../EpollSocketStringEchoBusyWaitTest.java | 26 +- .../epoll/EpollSocketTestPermutation.java | 145 ++-- .../netty/channel/epoll/EpollSpliceTest.java | 27 +- .../io/netty/channel/epoll/EpollTest.java | 17 +- .../channel/kqueue/AbstractKQueueChannel.java | 54 +- .../kqueue/AbstractKQueueStreamChannel.java | 41 +- .../netty/channel/kqueue/KQueueHandler.java | 21 +- .../kqueue/KQueueRecvByteAllocatorHandle.java | 7 +- .../kqueue/KQueueDomainSocketFdTest.java | 11 +- .../channel/kqueue/KQueueEventLoopTest.java | 7 +- .../kqueue/KQueueSocketTestPermutation.java | 81 +- .../channel/sctp/nio/NioSctpChannel.java | 14 +- .../sctp/nio/NioSctpServerChannel.java | 14 +- 192 files changed, 2727 insertions(+), 4999 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufProcessor.java b/buffer/src/main/java/io/netty/buffer/ByteBufProcessor.java index 4e9ce6d488..3faad6e53f 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufProcessor.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufProcessor.java @@ -28,109 +28,59 @@ public interface ByteBufProcessor extends ByteProcessor { * @deprecated Use {@link ByteProcessor#FIND_NUL}. */ @Deprecated - ByteBufProcessor FIND_NUL = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != 0; - } - }; + ByteBufProcessor FIND_NUL = value -> value != 0; /** * @deprecated Use {@link ByteProcessor#FIND_NON_NUL}. */ @Deprecated - ByteBufProcessor FIND_NON_NUL = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == 0; - } - }; + ByteBufProcessor FIND_NON_NUL = value -> value == 0; /** * @deprecated Use {@link ByteProcessor#FIND_CR}. */ @Deprecated - ByteBufProcessor FIND_CR = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != '\r'; - } - }; + ByteBufProcessor FIND_CR = value -> value != '\r'; /** * @deprecated Use {@link ByteProcessor#FIND_NON_CR}. */ @Deprecated - ByteBufProcessor FIND_NON_CR = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == '\r'; - } - }; + ByteBufProcessor FIND_NON_CR = value -> value == '\r'; /** * @deprecated Use {@link ByteProcessor#FIND_LF}. */ @Deprecated - ByteBufProcessor FIND_LF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != '\n'; - } - }; + ByteBufProcessor FIND_LF = value -> value != '\n'; /** * @deprecated Use {@link ByteProcessor#FIND_NON_LF}. */ @Deprecated - ByteBufProcessor FIND_NON_LF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == '\n'; - } - }; + ByteBufProcessor FIND_NON_LF = value -> value == '\n'; /** * @deprecated Use {@link ByteProcessor#FIND_CRLF}. */ @Deprecated - ByteBufProcessor FIND_CRLF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != '\r' && value != '\n'; - } - }; + ByteBufProcessor FIND_CRLF = value -> value != '\r' && value != '\n'; /** * @deprecated Use {@link ByteProcessor#FIND_NON_CRLF}. */ @Deprecated - ByteBufProcessor FIND_NON_CRLF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == '\r' || value == '\n'; - } - }; + ByteBufProcessor FIND_NON_CRLF = value -> value == '\r' || value == '\n'; /** * @deprecated Use {@link ByteProcessor#FIND_LINEAR_WHITESPACE}. */ @Deprecated - ByteBufProcessor FIND_LINEAR_WHITESPACE = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != ' ' && value != '\t'; - } - }; + ByteBufProcessor FIND_LINEAR_WHITESPACE = value -> value != ' ' && value != '\t'; /** * @deprecated Use {@link ByteProcessor#FIND_NON_LINEAR_WHITESPACE}. */ @Deprecated - ByteBufProcessor FIND_NON_LINEAR_WHITESPACE = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == ' ' || value == '\t'; - } - }; + ByteBufProcessor FIND_NON_LINEAR_WHITESPACE = value -> value == ' ' || value == '\t'; } diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index d2b2ec334f..41e05efb35 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -1254,12 +1254,7 @@ public final class ByteBufUtil { /** * Aborts on a byte which is not a valid ASCII character. */ - private static final ByteProcessor FIND_NON_ASCII = new ByteProcessor() { - @Override - public boolean process(byte value) { - return value >= 0; - } - }; + private static final ByteProcessor FIND_NON_ASCII = value -> value >= 0; /** * Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid diff --git a/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java b/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java index d0a8631261..b88f3180c5 100644 --- a/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java @@ -2089,16 +2089,13 @@ public abstract class AbstractByteBufTest { final AtomicReference errorRef = new AtomicReference<>(); List threads = new ArrayList<>(); for (int i = 0; i < 10; i++) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - while (errorRef.get() == null && counter.decrementAndGet() > 0) { - assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1)); - } - } catch (Throwable cause) { - errorRef.compareAndSet(null, cause); + Thread thread = new Thread(() -> { + try { + while (errorRef.get() == null && counter.decrementAndGet() > 0) { + assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1)); } + } catch (Throwable cause) { + errorRef.compareAndSet(null, cause); } }); threads.add(thread); @@ -2358,34 +2355,31 @@ public abstract class AbstractByteBufTest { final CountDownLatch latch = new CountDownLatch(60000); final CyclicBarrier barrier = new CyclicBarrier(11); for (int i = 0; i < 10; i++) { - new Thread(new Runnable() { - @Override - public void run() { - while (latch.getCount() > 0) { - ByteBuf buf; - if (slice) { - buf = buffer.slice(); - } else { - buf = buffer.duplicate(); - } - TestGatheringByteChannel channel = new TestGatheringByteChannel(); + new Thread(() -> { + while (latch.getCount() > 0) { + ByteBuf buf; + if (slice) { + buf = buffer.slice(); + } else { + buf = buffer.duplicate(); + } + TestGatheringByteChannel channel = new TestGatheringByteChannel(); - while (buf.isReadable()) { - try { - buf.readBytes(channel, buf.readableBytes()); - } catch (IOException e) { - // Never happens - return; - } + while (buf.isReadable()) { + try { + buf.readBytes(channel, buf.readableBytes()); + } catch (IOException e) { + // Never happens + return; } - assertArrayEquals(bytes, channel.writtenBytes()); - latch.countDown(); - } - try { - barrier.await(); - } catch (Exception e) { - // ignore } + assertArrayEquals(bytes, channel.writtenBytes()); + latch.countDown(); + } + try { + barrier.await(); + } catch (Exception e) { + // ignore } }).start(); } @@ -2413,34 +2407,31 @@ public abstract class AbstractByteBufTest { final CountDownLatch latch = new CountDownLatch(60000); final CyclicBarrier barrier = new CyclicBarrier(11); for (int i = 0; i < 10; i++) { - new Thread(new Runnable() { - @Override - public void run() { - while (latch.getCount() > 0) { - ByteBuf buf; - if (slice) { - buf = buffer.slice(); - } else { - buf = buffer.duplicate(); - } - ByteArrayOutputStream out = new ByteArrayOutputStream(); + new Thread(() -> { + while (latch.getCount() > 0) { + ByteBuf buf; + if (slice) { + buf = buffer.slice(); + } else { + buf = buffer.duplicate(); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); - while (buf.isReadable()) { - try { - buf.readBytes(out, buf.readableBytes()); - } catch (IOException e) { - // Never happens - return; - } + while (buf.isReadable()) { + try { + buf.readBytes(out, buf.readableBytes()); + } catch (IOException e) { + // Never happens + return; } - assertArrayEquals(bytes, out.toByteArray()); - latch.countDown(); - } - try { - barrier.await(); - } catch (Exception e) { - // ignore } + assertArrayEquals(bytes, out.toByteArray()); + latch.countDown(); + } + try { + barrier.await(); + } catch (Exception e) { + // ignore } }).start(); } @@ -2469,33 +2460,30 @@ public abstract class AbstractByteBufTest { final CountDownLatch latch = new CountDownLatch(60000); final CyclicBarrier barrier = new CyclicBarrier(11); for (int i = 0; i < 10; i++) { - new Thread(new Runnable() { - @Override - public void run() { - while (cause.get() == null && latch.getCount() > 0) { - ByteBuf buf; - if (slice) { - buf = buffer.slice(); - } else { - buf = buffer.duplicate(); - } - - byte[] array = new byte[8]; - buf.readBytes(array); - - assertArrayEquals(bytes, array); - - Arrays.fill(array, (byte) 0); - buf.getBytes(0, array); - assertArrayEquals(bytes, array); - - latch.countDown(); - } - try { - barrier.await(); - } catch (Exception e) { - // ignore + new Thread(() -> { + while (cause.get() == null && latch.getCount() > 0) { + ByteBuf buf; + if (slice) { + buf = buffer.slice(); + } else { + buf = buffer.duplicate(); } + + byte[] array = new byte[8]; + buf.readBytes(array); + + assertArrayEquals(bytes, array); + + Arrays.fill(array, (byte) 0); + buf.getBytes(0, array); + assertArrayEquals(bytes, array); + + latch.countDown(); + } + try { + barrier.await(); + } catch (Exception e) { + // ignore } }).start(); } @@ -4643,30 +4631,24 @@ public abstract class AbstractByteBufTest { final ByteBuf buffer = newBuffer(4); assertEquals(1, buffer.refCnt()); final AtomicInteger cnt = new AtomicInteger(Integer.MAX_VALUE); - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - boolean released; - if (parameter) { - released = buffer.release(buffer.refCnt()); - } else { - released = buffer.release(); - } - assertTrue(released); - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - cnt.set(buffer.refCnt()); - latch.countDown(); - } - }); - t2.start(); - try { - // Keep Thread alive a bit so the ThreadLocal caches are not freed - innerLatch.await(); - } catch (InterruptedException ignore) { - // ignore - } + Thread t1 = new Thread(() -> { + boolean released; + if (parameter) { + released = buffer.release(buffer.refCnt()); + } else { + released = buffer.release(); + } + assertTrue(released); + Thread t2 = new Thread(() -> { + cnt.set(buffer.refCnt()); + latch.countDown(); + }); + t2.start(); + try { + // Keep Thread alive a bit so the ThreadLocal caches are not freed + innerLatch.await(); + } catch (InterruptedException ignore) { + // ignore } }); t1.start(); diff --git a/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java b/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java index 272933dea2..6e2f84c147 100644 --- a/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java +++ b/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java @@ -680,16 +680,13 @@ public class ByteBufUtilTest { final AtomicReference errorRef = new AtomicReference<>(); List threads = new ArrayList<>(); for (int i = 0; i < 10; i++) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - while (errorRef.get() == null && counter.decrementAndGet() > 0) { - assertTrue(ByteBufUtil.isText(buffer, CharsetUtil.ISO_8859_1)); - } - } catch (Throwable cause) { - errorRef.compareAndSet(null, cause); + Thread thread = new Thread(() -> { + try { + while (errorRef.get() == null && counter.decrementAndGet() > 0) { + assertTrue(ByteBufUtil.isText(buffer, CharsetUtil.ISO_8859_1)); } + } catch (Throwable cause) { + errorRef.compareAndSet(null, cause); } }); threads.add(thread); diff --git a/buffer/src/test/java/io/netty/buffer/PooledByteBufAllocatorTest.java b/buffer/src/test/java/io/netty/buffer/PooledByteBufAllocatorTest.java index 6cbdf0cb48..a766956077 100644 --- a/buffer/src/test/java/io/netty/buffer/PooledByteBufAllocatorTest.java +++ b/buffer/src/test/java/io/netty/buffer/PooledByteBufAllocatorTest.java @@ -257,23 +257,20 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest { + ByteBuf buf = allocator.newHeapBuffer(1024, 1024); + for (int i = 0; i < buf.capacity(); i++) { + buf.writeByte(0); } + + // Make sure that thread caches are actually created, + // so that down below we are not testing for zero + // thread caches without any of them ever having been initialized. + if (allocator.metric().numThreadLocalCaches() == 0) { + threadCachesCreated.set(false); + } + + buf.release(); }; for (int i = 0; i < numArenas; i++) { @@ -368,39 +365,32 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest { + ByteBuf buf = allocator.newHeapBuffer(1024, 1024); - @Override - public void run() { - ByteBuf buf = allocator.newHeapBuffer(1024, 1024); + // Countdown the latch after we allocated a buffer. At this point the cache must exists. + cacheLatch.countDown(); - // Countdown the latch after we allocated a buffer. At this point the cache must exists. - cacheLatch.countDown(); + buf.writeZero(buf.capacity()); - buf.writeZero(buf.capacity()); - - try { - latch.await(); - } catch (InterruptedException e) { - throw new IllegalStateException(e); - } - - buf.release(); - - FastThreadLocal.removeAll(); + try { + latch.await(); + } catch (InterruptedException e) { + throw new IllegalStateException(e); } + + buf.release(); + + FastThreadLocal.removeAll(); }); t.start(); // Wait until we allocated a buffer and so be sure the thread was started and the cache exists. cacheLatch.await(); - return new ThreadCache() { - @Override - public void destroy() throws InterruptedException { - latch.countDown(); - t.join(); - } + return () -> { + latch.countDown(); + t.join(); }; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/CombinedHttpHeaders.java b/codec-http/src/main/java/io/netty/handler/codec/http/CombinedHttpHeaders.java index b8a2d0b891..996b96d6e6 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/CombinedHttpHeaders.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/CombinedHttpHeaders.java @@ -57,24 +57,14 @@ public class CombinedHttpHeaders extends DefaultHttpHeaders { private CsvValueEscaper objectEscaper() { if (objectEscaper == null) { - objectEscaper = new CsvValueEscaper() { - @Override - public CharSequence escape(Object value) { - return StringUtil.escapeCsv(valueConverter().convertObject(value), true); - } - }; + objectEscaper = value -> StringUtil.escapeCsv(valueConverter().convertObject(value), true); } return objectEscaper; } private CsvValueEscaper charSequenceEscaper() { if (charSequenceEscaper == null) { - charSequenceEscaper = new CsvValueEscaper() { - @Override - public CharSequence escape(CharSequence value) { - return StringUtil.escapeCsv(value, true); - } - }; + charSequenceEscaper = value -> StringUtil.escapeCsv(value, true); } return charSequenceEscaper; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java index 019365582b..1f782daf8d 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java @@ -44,30 +44,24 @@ import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER; */ public class DefaultHttpHeaders extends HttpHeaders { private static final int HIGHEST_INVALID_VALUE_CHAR_MASK = ~15; - private static final ByteProcessor HEADER_NAME_VALIDATOR = new ByteProcessor() { - @Override - public boolean process(byte value) throws Exception { - validateHeaderNameElement(value); - return true; - } + private static final ByteProcessor HEADER_NAME_VALIDATOR = value -> { + validateHeaderNameElement(value); + return true; }; - static final NameValidator HttpNameValidator = new NameValidator() { - @Override - public void validateName(CharSequence name) { - if (name == null || name.length() == 0) { - throw new IllegalArgumentException("empty headers are not allowed [" + name + "]"); + static final NameValidator HttpNameValidator = name -> { + if (name == null || name.length() == 0) { + throw new IllegalArgumentException("empty headers are not allowed [" + name + "]"); + } + if (name instanceof AsciiString) { + try { + ((AsciiString) name).forEachByte(HEADER_NAME_VALIDATOR); + } catch (Exception e) { + PlatformDependent.throwException(e); } - if (name instanceof AsciiString) { - try { - ((AsciiString) name).forEachByte(HEADER_NAME_VALIDATOR); - } catch (Exception e) { - PlatformDependent.throwException(e); - } - } else { - // Go through each character in the name - for (int index = 0; index < name.length(); ++index) { - validateHeaderNameElement(name.charAt(index)); - } + } else { + // Go through each character in the name + for (int index = 0; index < name.length(); ++index) { + validateHeaderNameElement(name.charAt(index)); } } }; diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultLastHttpContent.java b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultLastHttpContent.java index 67c619a521..2ac9481400 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultLastHttpContent.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultLastHttpContent.java @@ -115,15 +115,12 @@ public class DefaultLastHttpContent extends DefaultHttpContent implements LastHt } private static final class TrailingHttpHeaders extends DefaultHttpHeaders { - private static final NameValidator TrailerNameValidator = new NameValidator() { - @Override - public void validateName(CharSequence name) { - DefaultHttpHeaders.HttpNameValidator.validateName(name); - if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(name) - || HttpHeaderNames.TRANSFER_ENCODING.contentEqualsIgnoreCase(name) - || HttpHeaderNames.TRAILER.contentEqualsIgnoreCase(name)) { - throw new IllegalArgumentException("prohibited trailing header: " + name); - } + private static final NameValidator TrailerNameValidator = name -> { + DefaultHttpHeaders.HttpNameValidator.validateName(name); + if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(name) + || HttpHeaderNames.TRANSFER_ENCODING.contentEqualsIgnoreCase(name) + || HttpHeaderNames.TRAILER.contentEqualsIgnoreCase(name)) { + throw new IllegalArgumentException("prohibited trailing header: " + name); } }; diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java index 257581fe23..9b96cd7cc5 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java @@ -251,23 +251,17 @@ public class HttpObjectAggregator if (oversized instanceof FullHttpMessage || !HttpUtil.is100ContinueExpected(oversized) && !HttpUtil.isKeepAlive(oversized)) { ChannelFuture future = ctx.writeAndFlush(TOO_LARGE_CLOSE.retainedDuplicate()); - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause()); - } - ctx.close(); + future.addListener((ChannelFutureListener) future1 -> { + if (!future1.isSuccess()) { + logger.debug("Failed to send a 413 Request Entity Too Large.", future1.cause()); } + ctx.close(); }); } else { - ctx.writeAndFlush(TOO_LARGE.retainedDuplicate()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause()); - ctx.close(); - } + ctx.writeAndFlush(TOO_LARGE.retainedDuplicate()).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause()); + ctx.close(); } }); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieEncoder.java index 0a66aaad7a..043e51ae4f 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieEncoder.java @@ -91,26 +91,23 @@ public final class ClientCookieEncoder extends CookieEncoder { * Sort cookies into decreasing order of path length, breaking ties by sorting into increasing chronological * order of creation time, as recommended by RFC 6265. */ - private static final Comparator COOKIE_COMPARATOR = new Comparator() { - @Override - public int compare(Cookie c1, Cookie c2) { - String path1 = c1.path(); - String path2 = c2.path(); - // Cookies with unspecified path default to the path of the request. We don't - // know the request path here, but we assume that the length of an unspecified - // path is longer than any specified path (i.e. pathless cookies come first), - // because setting cookies with a path longer than the request path is of - // limited use. - int len1 = path1 == null ? Integer.MAX_VALUE : path1.length(); - int len2 = path2 == null ? Integer.MAX_VALUE : path2.length(); - int diff = len2 - len1; - if (diff != 0) { - return diff; - } - // Rely on Java's sort stability to retain creation order in cases where - // cookies have same path length. - return -1; + private static final Comparator COOKIE_COMPARATOR = (c1, c2) -> { + String path1 = c1.path(); + String path2 = c2.path(); + // Cookies with unspecified path default to the path of the request. We don't + // know the request path here, but we assume that the length of an unspecified + // path is longer than any specified path (i.e. pathless cookies come first), + // because setting cookies with a path longer than the request path is of + // limited use. + int len1 = path1 == null ? Integer.MAX_VALUE : path1.length(); + int len2 = path2 == null ? Integer.MAX_VALUE : path2.length(); + int diff = len2 - len1; + if (diff != 0) { + return diff; } + // Rely on Java's sort stability to retain creation order in cases where + // cookies have same path length. + return -1; }; /** diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java index 44c91445a2..188899f957 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java @@ -174,26 +174,23 @@ public abstract class WebSocketClientHandshaker { } } - channel.writeAndFlush(request).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (future.isSuccess()) { - ChannelPipeline p = future.channel().pipeline(); - ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class); - if (ctx == null) { - ctx = p.context(HttpClientCodec.class); - } - if (ctx == null) { - promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " + - "a HttpRequestEncoder or HttpClientCodec")); - return; - } - p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder()); - - promise.setSuccess(); - } else { - promise.setFailure(future.cause()); + channel.writeAndFlush(request).addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + ChannelPipeline p = future.channel().pipeline(); + ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class); + if (ctx == null) { + ctx = p.context(HttpClientCodec.class); } + if (ctx == null) { + promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " + + "a HttpRequestEncoder or HttpClientCodec")); + return; + } + p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder()); + + promise.setSuccess(); + } else { + promise.setFailure(future.cause()); } }); return promise; @@ -274,12 +271,7 @@ public abstract class WebSocketClientHandshaker { // Delay the removal of the decoder so the user can setup the pipeline if needed to handle // WebSocketFrame messages. // See https://github.com/netty/netty/issues/4533 - channel.eventLoop().execute(new Runnable() { - @Override - public void run() { - p.remove(codec); - } - }); + channel.eventLoop().execute(() -> p.remove(codec)); } else { if (p.get(HttpRequestEncoder.class) != null) { // Remove the encoder part of the codec as the user may start writing frames after this method returns. @@ -291,12 +283,7 @@ public abstract class WebSocketClientHandshaker { // Delay the removal of the decoder so the user can setup the pipeline if needed to handle // WebSocketFrame messages. // See https://github.com/netty/netty/issues/4533 - channel.eventLoop().execute(new Runnable() { - @Override - public void run() { - p.remove(context.handler()); - } - }); + channel.eventLoop().execute(() -> p.remove(context.handler())); } } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandshakeHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandshakeHandler.java index 3d130c63d6..a7d06974c2 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandshakeHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandshakeHandler.java @@ -31,15 +31,12 @@ class WebSocketClientProtocolHandshakeHandler extends ChannelInboundHandlerAdapt @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); - handshaker.handshake(ctx.channel()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - ctx.fireExceptionCaught(future.cause()); - } else { - ctx.fireUserEventTriggered( - WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_ISSUED); - } + handshaker.handshake(ctx.channel()).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + ctx.fireExceptionCaught(future.cause()); + } else { + ctx.fireUserEventTriggered( + WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_ISSUED); } }); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java index 439595514a..0044516fda 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java @@ -191,16 +191,13 @@ public abstract class WebSocketServerHandshaker { encoderName = p.context(HttpResponseEncoder.class).name(); p.addBefore(encoderName, "wsencoder", newWebSocketEncoder()); } - channel.writeAndFlush(response).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isSuccess()) { - ChannelPipeline p = future.channel().pipeline(); - p.remove(encoderName); - promise.setSuccess(); - } else { - promise.setFailure(future.cause()); - } + channel.writeAndFlush(response).addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + ChannelPipeline p1 = future.channel().pipeline(); + p1.remove(encoderName); + promise.setSuccess(); + } else { + promise.setFailure(future.cause()); } }); return promise; diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandshakeHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandshakeHandler.java index 26e01f1860..4c9c0c5524 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandshakeHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandshakeHandler.java @@ -81,19 +81,16 @@ class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapt WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req); - handshakeFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - ctx.fireExceptionCaught(future.cause()); - } else { - // Kept for compatibility - ctx.fireUserEventTriggered( - WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE); - ctx.fireUserEventTriggered( - new WebSocketServerProtocolHandler.HandshakeComplete( - req.uri(), req.headers(), handshaker.selectedSubprotocol())); - } + handshakeFuture.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + ctx.fireExceptionCaught(future.cause()); + } else { + // Kept for compatibility + ctx.fireUserEventTriggered( + WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE); + ctx.fireUserEventTriggered( + new WebSocketServerProtocolHandler.HandshakeComplete( + req.uri(), req.headers(), handshaker.selectedSubprotocol())); } }); WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker); diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketServerExtensionHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketServerExtensionHandler.java index f63401d865..9b63fef7ee 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketServerExtensionHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketServerExtensionHandler.java @@ -115,20 +115,17 @@ public class WebSocketServerExtensionHandler extends ChannelDuplexHandler { extensionData.name(), extensionData.parameters()); } - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isSuccess()) { - for (WebSocketServerExtension extension : validExtensions) { - WebSocketExtensionDecoder decoder = extension.newExtensionDecoder(); - WebSocketExtensionEncoder encoder = extension.newExtensionEncoder(); - ctx.pipeline().addAfter(ctx.name(), decoder.getClass().getName(), decoder); - ctx.pipeline().addAfter(ctx.name(), encoder.getClass().getName(), encoder); - } + promise.addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + for (WebSocketServerExtension extension : validExtensions) { + WebSocketExtensionDecoder decoder = extension.newExtensionDecoder(); + WebSocketExtensionEncoder encoder = extension.newExtensionEncoder(); + ctx.pipeline().addAfter(ctx.name(), decoder.getClass().getName(), decoder); + ctx.pipeline().addAfter(ctx.name(), encoder.getClass().getName(), encoder); } - - ctx.pipeline().remove(ctx.name()); } + + ctx.pipeline().remove(ctx.name()); }); if (headerValue != null) { diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdyHeaders.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdyHeaders.java index 7eed710fa6..6b2b96a777 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdyHeaders.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdyHeaders.java @@ -27,12 +27,7 @@ import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER; import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER; public class DefaultSpdyHeaders extends DefaultHeaders implements SpdyHeaders { - private static final NameValidator SpdyNameValidator = new NameValidator() { - @Override - public void validateName(CharSequence name) { - SpdyCodecUtil.validateHeaderName(name); - } - }; + private static final NameValidator SpdyNameValidator = SpdyCodecUtil::validateHeaderName; public DefaultSpdyHeaders() { this(true); diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameCodec.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameCodec.java index f196d984e9..5937d9a56f 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameCodec.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameCodec.java @@ -109,12 +109,9 @@ public class SpdyFrameCodec extends ByteToMessageDecoder public void handlerAdded(ChannelHandlerContext ctx) throws Exception { super.handlerAdded(ctx); this.ctx = ctx; - ctx.channel().closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - spdyHeaderBlockDecoder.end(); - spdyHeaderBlockEncoder.end(); - } + ctx.channel().closeFuture().addListener((ChannelFutureListener) future -> { + spdyHeaderBlockDecoder.end(); + spdyHeaderBlockEncoder.end(); }); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java index 394f6c2e9a..6ef19b0cf3 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java @@ -504,12 +504,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler { // The transfer window size is pre-decremented when sending a data frame downstream. // Close the session on write failures that leave the transfer window in a corrupt state. final ChannelHandlerContext context = ctx; - ctx.write(partialDataFrame).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR); - } + ctx.write(partialDataFrame).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR); } }); return; @@ -521,12 +518,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler { // The transfer window size is pre-decremented when sending a data frame downstream. // Close the session on write failures that leave the transfer window in a corrupt state. final ChannelHandlerContext context = ctx; - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR); - } + promise.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR); } }); } @@ -781,12 +775,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler { // The transfer window size is pre-decremented when sending a data frame downstream. // Close the session on write failures that leave the transfer window in a corrupt state. - ctx.writeAndFlush(partialDataFrame).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR); - } + ctx.writeAndFlush(partialDataFrame).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR); } }); } else { @@ -802,12 +793,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler { // The transfer window size is pre-decremented when sending a data frame downstream. // Close the session on write failures that leave the transfer window in a corrupt state. - ctx.writeAndFlush(spdyDataFrame, pendingWrite.promise).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR); - } + ctx.writeAndFlush(spdyDataFrame, pendingWrite.promise).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR); } }); } diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientCodecTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientCodecTest.java index 3efb6eebe0..184df7bf61 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientCodecTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientCodecTest.java @@ -147,22 +147,16 @@ public class HttpClientCodecTest { sChannel.writeAndFlush(Unpooled.wrappedBuffer(("HTTP/1.0 200 OK\r\n" + "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" + "Content-Type: text/html\r\n\r\n").getBytes(CharsetUtil.ISO_8859_1))) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - assertTrue(future.isSuccess()); - sChannel.writeAndFlush(Unpooled.wrappedBuffer( - "hello half closed!\r\n" - .getBytes(CharsetUtil.ISO_8859_1))) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - assertTrue(future.isSuccess()); - sChannel.shutdownOutput(); - } + .addListener((ChannelFutureListener) future -> { + assertTrue(future.isSuccess()); + sChannel.writeAndFlush(Unpooled.wrappedBuffer( + "hello half closed!\r\n" + .getBytes(CharsetUtil.ISO_8859_1))) + .addListener((ChannelFutureListener) future1 -> { + assertTrue(future1.isSuccess()); + sChannel.shutdownOutput(); + }); }); - } - }); } }); serverChannelLatch.countDown(); diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerUpgradeHandlerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerUpgradeHandlerTest.java index 7c9a417c38..f7835193ff 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerUpgradeHandlerTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerUpgradeHandlerTest.java @@ -64,12 +64,7 @@ public class HttpServerUpgradeHandlerTest { @Test public void upgradesPipelineInSameMethodInvocation() { final HttpServerCodec httpServerCodec = new HttpServerCodec(); - final UpgradeCodecFactory factory = new UpgradeCodecFactory() { - @Override - public UpgradeCodec newUpgradeCodec(CharSequence protocol) { - return new TestUpgradeCodec(); - } - }; + final UpgradeCodecFactory factory = protocol -> new TestUpgradeCodec(); ChannelHandler testInStackFrame = new ChannelDuplexHandler() { // marker boolean to signal that we're in the `channelRead` method @@ -102,18 +97,8 @@ public class HttpServerUpgradeHandlerTest { // make sure the pipeline was reformed irrespective of the flush completing. assertTrue(inReadCall); writeUpgradeMessage = true; - ctx.channel().eventLoop().execute(new Runnable() { - @Override - public void run() { - ctx.write(msg, promise); - } - }); - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - writeFlushed = true; - } - }); + ctx.channel().eventLoop().execute(() -> ctx.write(msg, promise)); + promise.addListener((ChannelFutureListener) future -> writeFlushed = true); } }; diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java index c4975e32ff..f1d2ee2287 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java @@ -186,12 +186,7 @@ public class CorsHandlerTest { @Test public void preflightRequestWithValueGenerator() { final CorsConfig config = forOrigin("http://localhost:8888") - .preflightResponseHeader("GenHeader", new Callable() { - @Override - public String call() throws Exception { - return "generatedValue"; - } - }).build(); + .preflightResponseHeader("GenHeader", () -> "generatedValue").build(); final HttpResponse response = preflightRequest(config, "http://localhost:8888", "content-type, xheader1"); assertThat(response.headers().get(of("GenHeader")), equalTo("generatedValue")); assertThat(response.headers().get(VARY), equalTo(ORIGIN.toString())); diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java index e0d6220feb..623ffedcb4 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java @@ -277,14 +277,11 @@ public class DefaultHttp2Connection implements Http2Connection { private void closeStreamsGreaterThanLastKnownStreamId(final int lastKnownStream, final DefaultEndpoint endpoint) throws Http2Exception { - forEachActiveStream(new Http2StreamVisitor() { - @Override - public boolean visit(Http2Stream stream) { - if (stream.id() > lastKnownStream && endpoint.isValidStreamId(stream.id())) { - stream.close(); - } - return true; + forEachActiveStream(stream -> { + if (stream.id() > lastKnownStream && endpoint.isValidStreamId(stream.id())) { + stream.close(); } + return true; }); } @@ -942,12 +939,7 @@ public class DefaultHttp2Connection implements Http2Connection { if (allowModifications()) { addToActiveStreams(stream); } else { - pendingEvents.add(new Event() { - @Override - public void process() { - addToActiveStreams(stream); - } - }); + pendingEvents.add(() -> addToActiveStreams(stream)); } } @@ -955,12 +947,7 @@ public class DefaultHttp2Connection implements Http2Connection { if (allowModifications() || itr != null) { removeFromActiveStreams(stream, itr); } else { - pendingEvents.add(new Event() { - @Override - public void process() { - removeFromActiveStreams(stream, itr); - } - }); + pendingEvents.add(() -> removeFromActiveStreams(stream, itr)); } } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoder.java index 2254f1fb90..a4b1069fb5 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoder.java @@ -463,13 +463,10 @@ public class DefaultHttp2ConnectionEncoder implements Http2ConnectionEncoder { } private void notifyLifecycleManagerOnError(ChannelFuture future, final ChannelHandlerContext ctx) { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - Throwable cause = future.cause(); - if (cause != null) { - lifecycleManager.onError(ctx, true, cause); - } + future.addListener((ChannelFutureListener) future1 -> { + Throwable cause = future1.cause(); + if (cause != null) { + lifecycleManager.onError(ctx, true, cause); } }); } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java index 0ab5705224..c0f9774378 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java @@ -31,43 +31,35 @@ import static io.netty.util.AsciiString.isUpperCase; @UnstableApi public class DefaultHttp2Headers extends DefaultHeaders implements Http2Headers { - private static final ByteProcessor HTTP2_NAME_VALIDATOR_PROCESSOR = new ByteProcessor() { - @Override - public boolean process(byte value) { - return !isUpperCase(value); + private static final ByteProcessor HTTP2_NAME_VALIDATOR_PROCESSOR = value -> !isUpperCase(value); + static final NameValidator HTTP2_NAME_VALIDATOR = name -> { + if (name == null || name.length() == 0) { + PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, + "empty headers are not allowed [%s]", name)); } - }; - static final NameValidator HTTP2_NAME_VALIDATOR = new NameValidator() { - @Override - public void validateName(CharSequence name) { - if (name == null || name.length() == 0) { - PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, - "empty headers are not allowed [%s]", name)); + if (name instanceof AsciiString) { + final int index; + try { + index = ((AsciiString) name).forEachByte(HTTP2_NAME_VALIDATOR_PROCESSOR); + } catch (Http2Exception e) { + PlatformDependent.throwException(e); + return; + } catch (Throwable t) { + PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, t, + "unexpected error. invalid header name [%s]", name)); + return; } - if (name instanceof AsciiString) { - final int index; - try { - index = ((AsciiString) name).forEachByte(HTTP2_NAME_VALIDATOR_PROCESSOR); - } catch (Http2Exception e) { - PlatformDependent.throwException(e); - return; - } catch (Throwable t) { - PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, t, - "unexpected error. invalid header name [%s]", name)); - return; - } - if (index != -1) { + if (index != -1) { + PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, + "invalid header name [%s]", name)); + } + } else { + for (int i = 0; i < name.length(); ++i) { + if (isUpperCase(name.charAt(i))) { PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, "invalid header name [%s]", name)); } - } else { - for (int i = 0; i < name.length(); ++i) { - if (isUpperCase(name.charAt(i))) { - PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, - "invalid header name [%s]", name)); - } - } } } }; diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java index 0742c3657a..f0ef835a8b 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java @@ -641,12 +641,9 @@ public class DefaultHttp2RemoteFlowController implements Http2RemoteFlowControll final int delta = newWindowSize - initialWindowSize; initialWindowSize = newWindowSize; - connection.forEachActiveStream(new Http2StreamVisitor() { - @Override - public boolean visit(Http2Stream stream) throws Http2Exception { - state(stream).incrementStreamWindow(delta); - return true; - } + connection.forEachActiveStream(stream -> { + state(stream).incrementStreamWindow(delta); + return true; }); if (delta > 0 && isChannelWritable()) { diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java index 0c260e0a16..7141c0e203 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java @@ -606,12 +606,7 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http if (future.isDone()) { checkCloseConnection(future); } else { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - checkCloseConnection(future); - } - }); + future.addListener((ChannelFutureListener) this::checkCloseConnection); } } @@ -750,12 +745,7 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http if (future.isDone()) { closeConnectionOnError(ctx, future); } else { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - closeConnectionOnError(ctx, future); - } - }); + future.addListener((ChannelFutureListener) future1 -> closeConnectionOnError(ctx, future1)); } return future; } @@ -795,12 +785,7 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http if (future.isDone()) { processRstStreamWriteResult(ctx, stream, future); } else { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - processRstStreamWriteResult(ctx, stream, future); - } - }); + future.addListener((ChannelFutureListener) future1 -> processRstStreamWriteResult(ctx, stream, future1)); } return future; @@ -831,12 +816,8 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http if (future.isDone()) { processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future); } else { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future); - } - }); + future.addListener((ChannelFutureListener) future1 -> + processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future1)); } return future; @@ -938,11 +919,8 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http long timeout, TimeUnit unit) { this.ctx = ctx; this.promise = promise; - timeoutTask = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - ctx.close(promise); - } + timeoutTask = ctx.executor().schedule(() -> { + ctx.close(promise); }, timeout, unit); } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java index cf756cab25..d3757d41ff 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java @@ -183,15 +183,12 @@ public class Http2FrameCodec extends Http2ConnectionHandler { final void forEachActiveStream(final Http2FrameStreamVisitor streamVisitor) throws Http2Exception { assert ctx.executor().inEventLoop(); - connection().forEachActiveStream(new Http2StreamVisitor() { - @Override - public boolean visit(Http2Stream stream) { - try { - return streamVisitor.visit((Http2FrameStream) stream.getProperty(streamKey)); - } catch (Throwable cause) { - onError(ctx, false, cause); - return false; - } + connection().forEachActiveStream(stream -> { + try { + return streamVisitor.visit((Http2FrameStream) stream.getProperty(streamKey)); + } catch (Throwable cause) { + onError(ctx, false, cause); + return false; } }); } @@ -381,13 +378,10 @@ public class Http2FrameCodec extends Http2ConnectionHandler { } else { numBufferedStreams++; - writePromise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - numBufferedStreams--; + writePromise.addListener((ChannelFutureListener) future -> { + numBufferedStreams--; - notifyHeaderWritePromise(future, promise); - } + notifyHeaderWritePromise(future, promise); }); } } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2HeadersEncoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2HeadersEncoder.java index 9e88efcfb9..50bedb227d 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2HeadersEncoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2HeadersEncoder.java @@ -90,20 +90,10 @@ public interface Http2HeadersEncoder { /** * Always return {@code false} for {@link SensitivityDetector#isSensitive(CharSequence, CharSequence)}. */ - SensitivityDetector NEVER_SENSITIVE = new SensitivityDetector() { - @Override - public boolean isSensitive(CharSequence name, CharSequence value) { - return false; - } - }; + SensitivityDetector NEVER_SENSITIVE = (name, value) -> false; /** * Always return {@code true} for {@link SensitivityDetector#isSensitive(CharSequence, CharSequence)}. */ - SensitivityDetector ALWAYS_SENSITIVE = new SensitivityDetector() { - @Override - public boolean isSensitive(CharSequence name, CharSequence value) { - return true; - } - }; + SensitivityDetector ALWAYS_SENSITIVE = (name, value) -> true; } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java index b6649b5c21..69ae3c21a7 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java @@ -108,12 +108,7 @@ public class Http2MultiplexCodec extends Http2FrameCodec { private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultHttp2StreamChannel.class); - private static final ChannelFutureListener CHILD_CHANNEL_REGISTRATION_LISTENER = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - registerDone(future); - } - }; + private static final ChannelFutureListener CHILD_CHANNEL_REGISTRATION_LISTENER = Http2MultiplexCodec::registerDone; private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16); private static final ClosedChannelException CLOSED_CHANNEL_EXCEPTION = ThrowableUtil.unknownStackTrace( @@ -131,15 +126,10 @@ public class Http2MultiplexCodec extends Http2FrameCodec { static final FlowControlledFrameSizeEstimator INSTANCE = new FlowControlledFrameSizeEstimator(); - static final MessageSizeEstimator.Handle HANDLE_INSTANCE = new MessageSizeEstimator.Handle() { - @Override - public int size(Object msg) { - return msg instanceof Http2DataFrame ? - // Guard against overflow. - (int) min(Integer.MAX_VALUE, ((Http2DataFrame) msg).initialFlowControlledBytes() + - (long) MIN_HTTP2_FRAME_SIZE) : MIN_HTTP2_FRAME_SIZE; - } - }; + static final MessageSizeEstimator.Handle HANDLE_INSTANCE = msg -> msg instanceof Http2DataFrame ? + // Guard against overflow. + (int) min(Integer.MAX_VALUE, ((Http2DataFrame) msg).initialFlowControlledBytes() + + (long) MIN_HTTP2_FRAME_SIZE) : MIN_HTTP2_FRAME_SIZE; @Override public Handle newHandle() { @@ -361,16 +351,13 @@ public class Http2MultiplexCodec extends Http2FrameCodec { private void onHttp2GoAwayFrame(ChannelHandlerContext ctx, final Http2GoAwayFrame goAwayFrame) { try { - forEachActiveStream(new Http2FrameStreamVisitor() { - @Override - public boolean visit(Http2FrameStream stream) { - final int streamId = stream.id(); - final DefaultHttp2StreamChannel childChannel = ((Http2MultiplexCodecStream) stream).channel; - if (streamId > goAwayFrame.lastStreamId() && connection().local().isValidStreamId(streamId)) { - childChannel.pipeline().fireUserEventTriggered(goAwayFrame.retainedDuplicate()); - } - return true; + forEachActiveStream(stream -> { + final int streamId = stream.id(); + final DefaultHttp2StreamChannel childChannel = ((Http2MultiplexCodecStream) stream).channel; + if (streamId > goAwayFrame.lastStreamId() && connection().local().isValidStreamId(streamId)) { + childChannel.pipeline().fireUserEventTriggered(goAwayFrame.retainedDuplicate()); } + return true; }); } catch (Http2Exception e) { ctx.fireExceptionCaught(e); @@ -890,12 +877,7 @@ public class Http2MultiplexCodec extends Http2FrameCodec { promise.setSuccess(); } else if (!(promise instanceof VoidChannelPromise)) { // Only needed if no VoidChannelPromise. // This means close() was called before so we just register a listener and return - closePromise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - promise.setSuccess(); - } - }); + closePromise.addListener((ChannelFutureListener) future -> promise.setSuccess()); } return; } @@ -959,20 +941,17 @@ public class Http2MultiplexCodec extends Http2FrameCodec { // // See: // https://github.com/netty/netty/issues/4435 - invokeLater(new Runnable() { - @Override - public void run() { - if (fireChannelInactive) { - pipeline.fireChannelInactive(); - } - // The user can fire `deregister` events multiple times but we only want to fire the pipeline - // event if the channel was actually registered. - if (registered) { - registered = false; - pipeline.fireChannelUnregistered(); - } - safeSetSuccess(promise); + invokeLater(() -> { + if (fireChannelInactive) { + pipeline.fireChannelInactive(); } + // The user can fire `deregister` events multiple times but we only want to fire the pipeline + // event if the channel was actually registered. + if (registered) { + registered = false; + pipeline.fireChannelUnregistered(); + } + safeSetSuccess(promise); }); } @@ -1127,12 +1106,8 @@ public class Http2MultiplexCodec extends Http2FrameCodec { if (future.isDone()) { firstWriteComplete(future, promise); } else { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - firstWriteComplete(future, promise); - } - }); + future.addListener((ChannelFutureListener) future12 -> + firstWriteComplete(future12, promise)); } return; } @@ -1149,12 +1124,7 @@ public class Http2MultiplexCodec extends Http2FrameCodec { if (future.isDone()) { writeComplete(future, promise); } else { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - writeComplete(future, promise); - } - }); + future.addListener((ChannelFutureListener) future1 -> writeComplete(future1, promise)); } } catch (Throwable t) { promise.tryFailure(t); diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2StreamChannelBootstrap.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2StreamChannelBootstrap.java index 2607d0c6e6..05444c7694 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2StreamChannelBootstrap.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2StreamChannelBootstrap.java @@ -118,12 +118,7 @@ public final class Http2StreamChannelBootstrap { if (executor.inEventLoop()) { open0(ctx, promise); } else { - executor.execute(new Runnable() { - @Override - public void run() { - open0(ctx, promise); - } - }); + executor.execute(() -> open0(ctx, promise)); } } return promise; @@ -141,22 +136,19 @@ public final class Http2StreamChannelBootstrap { } ChannelFuture future = streamChannel.register(); - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isSuccess()) { - promise.setSuccess(streamChannel); - } else if (future.isCancelled()) { - promise.cancel(false); + future.addListener((ChannelFutureListener) future1 -> { + if (future1.isSuccess()) { + promise.setSuccess(streamChannel); + } else if (future1.isCancelled()) { + promise.cancel(false); + } else { + if (streamChannel.isRegistered()) { + streamChannel.close(); } else { - if (streamChannel.isRegistered()) { - streamChannel.close(); - } else { - streamChannel.unsafe().closeForcibly(); - } - - promise.setFailure(future.cause()); + streamChannel.unsafe().closeForcibly(); } + + promise.setFailure(future1.cause()); } }); } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java index bb1e4695ab..e9b62c2b1b 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java @@ -35,21 +35,18 @@ abstract class AbstractWeightedFairQueueByteDistributorDependencyTest { } Answer writeAnswer(final boolean closeIfNoFrame) { - return new Answer() { - @Override - public Void answer(InvocationOnMock in) throws Throwable { - Http2Stream stream = in.getArgument(0); - int numBytes = in.getArgument(1); - TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); - state.pendingBytes -= numBytes; - state.hasFrame = state.pendingBytes > 0; - state.isWriteAllowed = state.hasFrame; - if (closeIfNoFrame && !state.hasFrame) { - stream.close(); - } - distributor.updateStreamableBytes(state); - return null; + return in -> { + Http2Stream stream = in.getArgument(0); + int numBytes = in.getArgument(1); + TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); + state.pendingBytes -= numBytes; + state.hasFrame = state.pendingBytes > 0; + state.isWriteAllowed = state.hasFrame; + if (closeIfNoFrame && !state.hasFrame) { + stream.close(); } + distributor.updateStreamableBytes(state); + return null; }; } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/CleartextHttp2ServerUpgradeHandlerTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/CleartextHttp2ServerUpgradeHandlerTest.java index 49b65fa61a..487f4923c7 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/CleartextHttp2ServerUpgradeHandlerTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/CleartextHttp2ServerUpgradeHandlerTest.java @@ -63,12 +63,7 @@ public class CleartextHttp2ServerUpgradeHandlerTest { http2ConnectionHandler = new Http2ConnectionHandlerBuilder() .frameListener(frameListener).build(); - UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() { - @Override - public UpgradeCodec newUpgradeCodec(CharSequence protocol) { - return new Http2ServerUpgradeCodec(http2ConnectionHandler); - } - }; + UpgradeCodecFactory upgradeCodecFactory = protocol -> new Http2ServerUpgradeCodec(http2ConnectionHandler); userEvents = new ArrayList<>(); @@ -205,12 +200,7 @@ public class CleartextHttp2ServerUpgradeHandlerTest { protected void initChannel(Channel ch) throws Exception { } }).build(); - UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() { - @Override - public UpgradeCodec newUpgradeCodec(CharSequence protocol) { - return new Http2ServerUpgradeCodec(http2Codec); - } - }; + UpgradeCodecFactory upgradeCodecFactory = protocol -> new Http2ServerUpgradeCodec(http2Codec); http2ConnectionHandler = http2Codec; userEvents = new ArrayList<>(); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DataCompressionHttp2Test.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DataCompressionHttp2Test.java index 14018013e1..66e5dd828b 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DataCompressionHttp2Test.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DataCompressionHttp2Test.java @@ -92,24 +92,18 @@ public class DataCompressionHttp2Test { @Before public void setup() throws InterruptedException, Http2Exception { MockitoAnnotations.initMocks(this); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArgument(4)) { - serverConnection.stream((Integer) invocation.getArgument(1)).close(); - } - return null; + doAnswer(invocation -> { + if (invocation.getArgument(4)) { + serverConnection.stream((Integer) invocation.getArgument(1)).close(); } + return null; }).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class), anyInt(), anyBoolean()); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - if (invocation.getArgument(7)) { - serverConnection.stream((Integer) invocation.getArgument(1)).close(); - } - return null; + doAnswer(invocation -> { + if (invocation.getArgument(7)) { + serverConnection.stream((Integer) invocation.getArgument(1)).close(); } + return null; }).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean()); } @@ -148,12 +142,9 @@ public class DataCompressionHttp2Test { final Http2Headers headers = new DefaultHttp2Headers().method(GET).path(PATH) .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, true, newPromiseClient()); - clientHandler.flush(ctxClient()); - } + runInChannel(clientChannel, () -> { + clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, true, newPromiseClient()); + clientHandler.flush(ctxClient()); }); awaitServer(); verify(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(3), eq(headers), eq(0), @@ -169,13 +160,10 @@ public class DataCompressionHttp2Test { final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH) .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); - clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient()); - clientHandler.flush(ctxClient()); - } + runInChannel(clientChannel, () -> { + clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); + clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient()); + clientHandler.flush(ctxClient()); }); awaitServer(); assertEquals(text, serverOut.toString(CharsetUtil.UTF_8.name())); @@ -193,13 +181,10 @@ public class DataCompressionHttp2Test { final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH) .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); - clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient()); - clientHandler.flush(ctxClient()); - } + runInChannel(clientChannel, () -> { + clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); + clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient()); + clientHandler.flush(ctxClient()); }); awaitServer(); assertEquals(text, serverOut.toString(CharsetUtil.UTF_8.name())); @@ -219,14 +204,11 @@ public class DataCompressionHttp2Test { final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH) .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); - clientEncoder.writeData(ctxClient(), 3, data1.retain(), 0, false, newPromiseClient()); - clientEncoder.writeData(ctxClient(), 3, data2.retain(), 0, true, newPromiseClient()); - clientHandler.flush(ctxClient()); - } + runInChannel(clientChannel, () -> { + clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); + clientEncoder.writeData(ctxClient(), 3, data1.retain(), 0, false, newPromiseClient()); + clientEncoder.writeData(ctxClient(), 3, data2.retain(), 0, true, newPromiseClient()); + clientHandler.flush(ctxClient()); }); awaitServer(); assertEquals(text1 + text2, serverOut.toString(CharsetUtil.UTF_8.name())); @@ -247,13 +229,10 @@ public class DataCompressionHttp2Test { final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH) .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.DEFLATE); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); - clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient()); - clientHandler.flush(ctxClient()); - } + runInChannel(clientChannel, () -> { + clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient()); + clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient()); + clientHandler.flush(ctxClient()); }); awaitServer(); assertEquals(data.readerIndex(0).toString(CharsetUtil.UTF_8), @@ -281,20 +260,17 @@ public class DataCompressionHttp2Test { } }); - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock in) throws Throwable { - ByteBuf buf = (ByteBuf) in.getArguments()[2]; - int padding = (Integer) in.getArguments()[3]; - int processedBytes = buf.readableBytes() + padding; + doAnswer(in -> { + ByteBuf buf = (ByteBuf) in.getArguments()[2]; + int padding = (Integer) in.getArguments()[3]; + int processedBytes = buf.readableBytes() + padding; - buf.readBytes(serverOut, buf.readableBytes()); + buf.readBytes(serverOut, buf.readableBytes()); - if (in.getArgument(4)) { - serverConnection.stream((Integer) in.getArgument(1)).close(); - } - return processedBytes; + if (in.getArgument(4)) { + serverConnection.stream((Integer) in.getArgument(1)).close(); } + return processedBytes; }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean()); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoderTest.java index 7e87d52893..e35f1b6e26 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoderTest.java @@ -130,52 +130,38 @@ public class DefaultHttp2ConnectionDecoderTest { when(stream.state()).thenReturn(OPEN); when(stream.open(anyBoolean())).thenReturn(stream); when(pushStream.id()).thenReturn(PUSH_STREAM_ID); - doAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock in) throws Throwable { - return (headersReceivedState.get() & STATE_RECV_HEADERS) != 0; - } - }).when(stream).isHeadersReceived(); - doAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock in) throws Throwable { - return (headersReceivedState.get() & STATE_RECV_TRAILERS) != 0; - } - }).when(stream).isTrailersReceived(); - doAnswer(new Answer() { - @Override - public Http2Stream answer(InvocationOnMock in) throws Throwable { - boolean isInformational = in.getArgument(0); - if (isInformational) { - return stream; - } - for (;;) { - int current = headersReceivedState.get(); - int next = current; - if ((current & STATE_RECV_HEADERS) != 0) { - if ((current & STATE_RECV_TRAILERS) != 0) { - throw new IllegalStateException("already sent headers!"); - } - next |= STATE_RECV_TRAILERS; - } else { - next |= STATE_RECV_HEADERS; - } - if (headersReceivedState.compareAndSet(current, next)) { - break; - } - } + doAnswer((Answer) in -> + (headersReceivedState.get() & STATE_RECV_HEADERS) != 0).when(stream).isHeadersReceived(); + doAnswer((Answer) in -> + (headersReceivedState.get() & STATE_RECV_TRAILERS) != 0).when(stream).isTrailersReceived(); + doAnswer((Answer) in -> { + boolean isInformational = in.getArgument(0); + if (isInformational) { return stream; } - }).when(stream).headersReceived(anyBoolean()); - doAnswer(new Answer() { - @Override - public Http2Stream answer(InvocationOnMock in) throws Throwable { - Http2StreamVisitor visitor = in.getArgument(0); - if (!visitor.visit(stream)) { - return stream; + for (;;) { + int current = headersReceivedState.get(); + int next = current; + if ((current & STATE_RECV_HEADERS) != 0) { + if ((current & STATE_RECV_TRAILERS) != 0) { + throw new IllegalStateException("already sent headers!"); + } + next |= STATE_RECV_TRAILERS; + } else { + next |= STATE_RECV_HEADERS; + } + if (headersReceivedState.compareAndSet(current, next)) { + break; } - return null; } + return stream; + }).when(stream).headersReceived(anyBoolean()); + doAnswer((Answer) in -> { + Http2StreamVisitor visitor = in.getArgument(0); + if (!visitor.visit(stream)) { + return stream; + } + return null; }).when(connection).forEachActiveStream(any(Http2StreamVisitor.class)); when(connection.stream(STREAM_ID)).thenReturn(stream); when(connection.streamMayHaveExisted(STREAM_ID)).thenReturn(true); @@ -391,30 +377,19 @@ public class DefaultHttp2ConnectionDecoderTest { final ByteBuf data = dummyData(); final int padding = 10; final AtomicInteger unprocessed = new AtomicInteger(data.readableBytes() + padding); - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock in) throws Throwable { - return unprocessed.get(); - } - }).when(localFlow).unconsumedBytes(eq(stream)); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock in) throws Throwable { - int delta = (Integer) in.getArguments()[1]; - int newValue = unprocessed.addAndGet(-delta); - if (newValue < 0) { - throw new RuntimeException("Returned too many bytes"); - } - return null; + doAnswer((Answer) in -> unprocessed.get()).when(localFlow).unconsumedBytes(eq(stream)); + doAnswer((Answer) in -> { + int delta = (Integer) in.getArguments()[1]; + int newValue = unprocessed.addAndGet(-delta); + if (newValue < 0) { + throw new RuntimeException("Returned too many bytes"); } + return null; }).when(localFlow).consumeBytes(eq(stream), anyInt()); // When the listener callback is called, process a few bytes and then throw. - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock in) throws Throwable { - localFlow.consumeBytes(stream, 4); - throw new RuntimeException("Fake Exception"); - } + doAnswer((Answer) in -> { + localFlow.consumeBytes(stream, 4); + throw new RuntimeException("Fake Exception"); }).when(listener).onDataRead(eq(ctx), eq(STREAM_ID), any(ByteBuf.class), eq(10), eq(true)); try { decode().onDataRead(ctx, STREAM_ID, data, padding, true); @@ -759,12 +734,8 @@ public class DefaultHttp2ConnectionDecoderTest { } private void mockFlowControl(final int processedBytes) throws Http2Exception { - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - return processedBytes; - } - }).when(listener).onDataRead(any(ChannelHandlerContext.class), anyInt(), + doAnswer((Answer) invocation -> + processedBytes).when(listener).onDataRead(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean()); } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoderTest.java index 2cda78d8c2..0ff024461b 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoderTest.java @@ -127,82 +127,55 @@ public class DefaultHttp2ConnectionEncoderTest { when(channel.unsafe()).thenReturn(unsafe); ChannelConfig config = new DefaultChannelConfig(channel); when(channel.config()).thenReturn(config); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock in) { - return newPromise().setFailure((Throwable) in.getArgument(0)); - } - }).when(channel).newFailedFuture(any(Throwable.class)); + doAnswer(in -> newPromise() + .setFailure((Throwable) in.getArgument(0))).when(channel).newFailedFuture(any(Throwable.class)); when(writer.configuration()).thenReturn(writerConfig); when(writerConfig.frameSizePolicy()).thenReturn(frameSizePolicy); when(frameSizePolicy.maxFrameSize()).thenReturn(64); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock in) throws Throwable { - return ((ChannelPromise) in.getArguments()[2]).setSuccess(); - } - }).when(writer).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class)); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock in) throws Throwable { - ((ByteBuf) in.getArguments()[3]).release(); - return ((ChannelPromise) in.getArguments()[4]).setSuccess(); - } + doAnswer((Answer) in -> ((ChannelPromise) in.getArguments()[2]) + .setSuccess()).when(writer).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class)); + doAnswer((Answer) in -> { + ((ByteBuf) in.getArguments()[3]).release(); + return ((ChannelPromise) in.getArguments()[4]).setSuccess(); }).when(writer).writeGoAway(eq(ctx), anyInt(), anyInt(), any(ByteBuf.class), any(ChannelPromise.class)); writtenData = new ArrayList<>(); writtenPadding = new ArrayList<>(); when(writer.writeData(eq(ctx), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean(), - any(ChannelPromise.class))).then(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock in) throws Throwable { - // Make sure we only receive stream closure on the last frame and that void promises - // are used for all writes except the last one. - ChannelPromise promise = (ChannelPromise) in.getArguments()[5]; - if (streamClosed) { - fail("Stream already closed"); - } else { - streamClosed = (Boolean) in.getArguments()[4]; - } - writtenPadding.add((Integer) in.getArguments()[3]); - ByteBuf data = (ByteBuf) in.getArguments()[2]; - writtenData.add(data.toString(UTF_8)); - // Release the buffer just as DefaultHttp2FrameWriter does - data.release(); - // Let the promise succeed to trigger listeners. - return promise.setSuccess(); + any(ChannelPromise.class))).then((Answer) in -> { + // Make sure we only receive stream closure on the last frame and that void promises + // are used for all writes except the last one. + ChannelPromise promise = (ChannelPromise) in.getArguments()[5]; + if (streamClosed) { + fail("Stream already closed"); + } else { + streamClosed = (Boolean) in.getArguments()[4]; } + writtenPadding.add((Integer) in.getArguments()[3]); + ByteBuf data = (ByteBuf) in.getArguments()[2]; + writtenData.add(data.toString(UTF_8)); + // Release the buffer just as DefaultHttp2FrameWriter does + data.release(); + // Let the promise succeed to trigger listeners. + return promise.setSuccess(); }); when(writer.writeHeaders(eq(ctx), anyInt(), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(), any(ChannelPromise.class))) - .then(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable { - ChannelPromise promise = (ChannelPromise) invocationOnMock.getArguments()[8]; - if (streamClosed) { - fail("Stream already closed"); - } else { - streamClosed = (Boolean) invocationOnMock.getArguments()[5]; - } - return promise.setSuccess(); + .then((Answer) invocationOnMock -> { + ChannelPromise promise = (ChannelPromise) invocationOnMock.getArguments()[8]; + if (streamClosed) { + fail("Stream already closed"); + } else { + streamClosed = (Boolean) invocationOnMock.getArguments()[5]; } + return promise.setSuccess(); }); payloadCaptor = ArgumentCaptor.forClass(Http2RemoteFlowController.FlowControlled.class); doNothing().when(remoteFlow).addFlowControlled(any(Http2Stream.class), payloadCaptor.capture()); when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(ctx.channel()).thenReturn(channel); - doAnswer(new Answer() { - @Override - public ChannelPromise answer(InvocationOnMock in) throws Throwable { - return newPromise(); - } - }).when(ctx).newPromise(); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock in) throws Throwable { - return newSucceededFuture(); - } - }).when(ctx).newSucceededFuture(); + doAnswer((Answer) in -> newPromise()).when(ctx).newPromise(); + doAnswer((Answer) in -> newSucceededFuture()).when(ctx).newSucceededFuture(); when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden")); when(channel.alloc()).thenReturn(PooledByteBufAllocator.DEFAULT); @@ -337,13 +310,10 @@ public class DefaultHttp2ConnectionEncoderTest { final Throwable cause = new RuntimeException("fake exception"); when(writer.writeHeaders(eq(ctx), eq(STREAM_ID), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(), any(ChannelPromise.class))) - .then(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable { - ChannelPromise promise = invocationOnMock.getArgument(8); - assertFalse(promise.isVoid()); - return promise.setFailure(cause); - } + .then((Answer) invocationOnMock -> { + ChannelPromise promise = invocationOnMock.getArgument(8); + assertFalse(promise.isVoid()); + return promise.setFailure(cause); }); createStream(STREAM_ID, false); // END_STREAM flag, so that a listener is added to the future. @@ -754,12 +724,9 @@ public class DefaultHttp2ConnectionEncoderTest { // Fake an encoding error, like HPACK's HeaderListSizeException when(writer.writeHeaders(eq(ctx), eq(STREAM_ID), eq(EmptyHttp2Headers.INSTANCE), eq(0), eq(DEFAULT_PRIORITY_WEIGHT), eq(false), eq(0), eq(true), eq(promise))) - .thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocation) { - promise.setFailure(ex); - return promise; - } + .thenAnswer((Answer) invocation -> { + promise.setFailure(ex); + return promise; }); writeAllFlowControlledFrames(); @@ -781,12 +748,9 @@ public class DefaultHttp2ConnectionEncoderTest { // Fake an encoding error, like HPACK's HeaderListSizeException when(writer.writeHeaders(eq(ctx), eq(STREAM_ID), eq(EmptyHttp2Headers.INSTANCE), eq(0), eq(DEFAULT_PRIORITY_WEIGHT), eq(false), eq(0), eq(true), eq(promise))) - .thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocation) { - promise.setFailure(ex); - return promise; - } + .thenAnswer((Answer) invocation -> { + promise.setFailure(ex); + return promise; }); writeAllFlowControlledFrames(); @@ -873,14 +837,11 @@ public class DefaultHttp2ConnectionEncoderTest { } private void writeAllFlowControlledFrames() { - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - FlowControlled flowControlled = (FlowControlled) invocationOnMock.getArguments()[1]; - flowControlled.write(ctx, Integer.MAX_VALUE); - flowControlled.writeComplete(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + FlowControlled flowControlled = (FlowControlled) invocationOnMock.getArguments()[1]; + flowControlled.write(ctx, Integer.MAX_VALUE); + flowControlled.writeComplete(); + return null; }).when(remoteFlow).addFlowControlled(any(Http2Stream.class), payloadCaptor.capture()); } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java index f5eee1d166..2ba6951dc2 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java @@ -88,19 +88,13 @@ public class DefaultHttp2ConnectionTest { server = new DefaultHttp2Connection(true); client = new DefaultHttp2Connection(false); client.addListener(clientListener); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - assertNotNull(client.stream(((Http2Stream) invocation.getArgument(0)).id())); - return null; - } + doAnswer((Answer) invocation -> { + assertNotNull(client.stream(((Http2Stream) invocation.getArgument(0)).id())); + return null; }).when(clientListener).onStreamClosed(any(Http2Stream.class)); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - assertNull(client.stream(((Http2Stream) invocation.getArgument(0)).id())); - return null; - } + doAnswer((Answer) invocation -> { + assertNull(client.stream(((Http2Stream) invocation.getArgument(0)).id())); + return null; }).when(clientListener).onStreamRemoved(any(Http2Stream.class)); } @@ -141,13 +135,10 @@ public class DefaultHttp2ConnectionTest { public void removeIndividualStreamsWhileCloseDoesNotNPE() throws InterruptedException, Http2Exception { final Http2Stream streamA = client.local().createStream(3, false); final Http2Stream streamB = client.remote().createStream(2, false); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - streamA.close(); - streamB.close(); - return null; - } + doAnswer((Answer) invocation -> { + streamA.close(); + streamB.close(); + return null; }).when(clientListener2).onStreamClosed(any(Http2Stream.class)); try { client.addListener(clientListener2); @@ -167,18 +158,12 @@ public class DefaultHttp2ConnectionTest { } final Promise promise = group.next().newPromise(); final CountDownLatch latch = new CountDownLatch(client.numActiveStreams()); - client.forEachActiveStream(new Http2StreamVisitor() { - @Override - public boolean visit(Http2Stream stream) { - client.close(promise).addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - assertTrue(promise.isDone()); - latch.countDown(); - } - }); - return true; - } + client.forEachActiveStream(stream -> { + client.close(promise).addListener((FutureListener) future -> { + assertTrue(promise.isDone()); + latch.countDown(); + }); + return true; }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -195,23 +180,17 @@ public class DefaultHttp2ConnectionTest { final Promise promise = group.next().newPromise(); final CountDownLatch latch = new CountDownLatch(1); try { - client.forEachActiveStream(new Http2StreamVisitor() { - @Override - public boolean visit(Http2Stream stream) throws Http2Exception { - // This close call is basically a noop, because the following statement will throw an exception. - client.close(promise); - // Do an invalid operation while iterating. - remote.createStream(3, false); - return true; - } + client.forEachActiveStream(stream -> { + // This close call is basically a noop, because the following statement will throw an exception. + client.close(promise); + // Do an invalid operation while iterating. + remote.createStream(3, false); + return true; }); } catch (Http2Exception ignored) { - client.close(promise).addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - assertTrue(promise.isDone()); - latch.countDown(); - } + client.close(promise).addListener((FutureListener) future -> { + assertTrue(promise.isDone()); + latch.countDown(); }); } assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -590,12 +569,9 @@ public class DefaultHttp2ConnectionTest { private void testRemoveAllStreams() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final Promise promise = group.next().newPromise(); - client.close(promise).addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - assertTrue(promise.isDone()); - latch.countDown(); - } + client.close(promise).addListener((FutureListener) future -> { + assertTrue(promise.isDone()); + latch.countDown(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriterTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriterTest.java index 438097f3e3..08757e0c4f 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriterTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriterTest.java @@ -76,16 +76,13 @@ public class DefaultHttp2FrameWriterTest { http2HeadersEncoder = new DefaultHttp2HeadersEncoder(); - Answer answer = new Answer() { - @Override - public Object answer(InvocationOnMock var1) throws Throwable { - Object msg = var1.getArgument(0); - if (msg instanceof ByteBuf) { - outbound.writeBytes((ByteBuf) msg); - } - ReferenceCountUtil.release(msg); - return future; + Answer answer = var1 -> { + Object msg = var1.getArgument(0); + if (msg instanceof ByteBuf) { + outbound.writeBytes((ByteBuf) msg); } + ReferenceCountUtil.release(msg); + return future; }; when(ctx.write(any())).then(answer); when(ctx.write(any(), any(ChannelPromise.class))).then(answer); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowControllerTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowControllerTest.java index 5efddc94d0..6fa6d00bc2 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowControllerTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowControllerTest.java @@ -691,12 +691,9 @@ public abstract class DefaultHttp2RemoteFlowControllerTest { public void flowControlledWriteThrowsAnException() throws Exception { final Http2RemoteFlowController.FlowControlled flowControlled = mockedFlowControlledThatThrowsOnWrite(); final Http2Stream stream = stream(STREAM_A); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) { - stream.closeLocalSide(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + stream.closeLocalSide(); + return null; }).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); int windowBefore = window(STREAM_A); @@ -724,11 +721,8 @@ public abstract class DefaultHttp2RemoteFlowControllerTest { final Http2RemoteFlowController.FlowControlled flowControlled = mockedFlowControlledThatThrowsOnWrite(); final Http2Stream stream = stream(STREAM_A); final RuntimeException fakeException = new RuntimeException("error failed"); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) { - throw fakeException; - } + doAnswer((Answer) invocationOnMock -> { + throw fakeException; }).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); int windowBefore = window(STREAM_A); @@ -757,26 +751,15 @@ public abstract class DefaultHttp2RemoteFlowControllerTest { mock(Http2RemoteFlowController.FlowControlled.class); Http2Stream streamA = stream(STREAM_A); final AtomicInteger size = new AtomicInteger(150); - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { - return size.get(); - } - }).when(flowControlled).size(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - size.addAndGet(-50); - return null; - } + doAnswer((Answer) invocationOnMock -> size.get()).when(flowControlled).size(); + doAnswer((Answer) invocationOnMock -> { + size.addAndGet(-50); + return null; }).when(flowControlled).write(any(ChannelHandlerContext.class), anyInt()); final Http2Stream stream = stream(STREAM_A); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) { - throw new RuntimeException("writeComplete failed"); - } + doAnswer((Answer) invocationOnMock -> { + throw new RuntimeException("writeComplete failed"); }).when(flowControlled).writeComplete(); int windowBefore = window(STREAM_A); @@ -807,12 +790,9 @@ public abstract class DefaultHttp2RemoteFlowControllerTest { when(flowControlled.size()).thenReturn(100); doThrow(new RuntimeException("write failed")) .when(flowControlled).write(any(ChannelHandlerContext.class), anyInt()); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) { - stream.close(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + stream.close(); + return null; }).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); controller.addFlowControlled(stream, flowControlled); @@ -960,13 +940,10 @@ public abstract class DefaultHttp2RemoteFlowControllerTest { final Http2RemoteFlowController.FlowControlled flowControlled = mock(Http2RemoteFlowController.FlowControlled.class); when(flowControlled.size()).thenReturn(100); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock in) throws Throwable { - // Write most of the bytes and then fail - when(flowControlled.size()).thenReturn(10); - throw new RuntimeException("Write failed"); - } + doAnswer((Answer) in -> { + // Write most of the bytes and then fail + when(flowControlled.size()).thenReturn(10); + throw new RuntimeException("Write failed"); }).when(flowControlled).write(any(ChannelHandlerContext.class), anyInt()); return flowControlled; } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HashCollisionTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HashCollisionTest.java index 9cd8d9bd07..4bd7abaca1 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HashCollisionTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HashCollisionTest.java @@ -51,28 +51,20 @@ public final class HashCollisionTest { // More "english words" can be found here: // https://gist.github.com/Scottmitch/de2f03912778016ecee3c140478f07e0#file-englishwords-txt - Map> dups = calculateDuplicates(strings, new Function() { - @Override - public Integer apply(CharSequence string) { - int h = 0; - for (int i = 0; i < string.length(); ++i) { - // masking with 0x1F reduces the number of overall bits that impact the hash code but makes the hash - // code the same regardless of character case (upper case or lower case hash is the same). - h = h * 31 + (string.charAt(i) & 0x1F); - } - return h; + Map> dups = calculateDuplicates(strings, string -> { + int h = 0; + for (int i = 0; i < string.length(); ++i) { + // masking with 0x1F reduces the number of overall bits that impact the hash code but makes the hash + // code the same regardless of character case (upper case or lower case hash is the same). + h = h * 31 + (string.charAt(i) & 0x1F); } + return h; }); PrintStream writer = System.out; writer.println("==Old Duplicates=="); printResults(writer, dups); - dups = calculateDuplicates(strings, new Function() { - @Override - public Integer apply(CharSequence string) { - return PlatformDependent.hashCodeAscii(string); - } - }); + dups = calculateDuplicates(strings, PlatformDependent::hashCodeAscii); writer.println(); writer.println("==New Duplicates=="); printResults(writer, dups); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackTestCase.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackTestCase.java index a4dca23a09..c274f1b91b 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackTestCase.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackTestCase.java @@ -180,12 +180,7 @@ final class HpackTestCase { private static byte[] encode(HpackEncoder hpackEncoder, List headers, int maxHeaderTableSize, final boolean sensitive) throws Http2Exception { Http2Headers http2Headers = toHttp2Headers(headers); - Http2HeadersEncoder.SensitivityDetector sensitivityDetector = new Http2HeadersEncoder.SensitivityDetector() { - @Override - public boolean isSensitive(CharSequence name, CharSequence value) { - return sensitive; - } - }; + Http2HeadersEncoder.SensitivityDetector sensitivityDetector = (name, value) -> sensitive; ByteBuf buffer = Unpooled.buffer(); try { if (maxHeaderTableSize != -1) { diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionHandlerTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionHandlerTest.java index 9a37d81876..92eae740b9 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionHandlerTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionHandlerTest.java @@ -154,25 +154,19 @@ public class Http2ConnectionHandlerTest { when(encoder.frameWriter()).thenReturn(frameWriter); when(encoder.flowController()).thenReturn(remoteFlow); when(decoder.flowController()).thenReturn(localFlow); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocation) throws Throwable { - ByteBuf buf = invocation.getArgument(3); - goAwayDebugCap = buf.toString(UTF_8); - buf.release(); - return future; - } + doAnswer((Answer) invocation -> { + ByteBuf buf = invocation.getArgument(3); + goAwayDebugCap = buf.toString(UTF_8); + buf.release(); + return future; }).when(frameWriter).writeGoAway( any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), any(ChannelPromise.class)); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocation) throws Throwable { - Object o = invocation.getArguments()[0]; - if (o instanceof ChannelFutureListener) { - ((ChannelFutureListener) o).operationComplete(future); - } - return future; + doAnswer((Answer) invocation -> { + Object o = invocation.getArguments()[0]; + if (o instanceof ChannelFutureListener) { + ((ChannelFutureListener) o).operationComplete(future); } + return future; }).when(future).addListener(any(GenericFutureListener.class)); when(future.cause()).thenReturn(fakeException); when(future.channel()).thenReturn(channel); @@ -182,15 +176,12 @@ public class Http2ConnectionHandlerTest { when(remote.flowController()).thenReturn(remoteFlowController); when(connection.local()).thenReturn(local); when(local.flowController()).thenReturn(localFlowController); - doAnswer(new Answer() { - @Override - public Http2Stream answer(InvocationOnMock in) throws Throwable { - Http2StreamVisitor visitor = in.getArgument(0); - if (!visitor.visit(stream)) { - return stream; - } - return null; + doAnswer((Answer) in -> { + Http2StreamVisitor visitor = in.getArgument(0); + if (!visitor.visit(stream)) { + return stream; } + return null; }).when(connection).forEachActiveStream(any(Http2StreamVisitor.class)); when(connection.stream(NON_EXISTANT_STREAM_ID)).thenReturn(null); when(connection.numActiveStreams()).thenReturn(1); @@ -205,13 +196,10 @@ public class Http2ConnectionHandlerTest { when(ctx.voidPromise()).thenReturn(voidPromise); when(ctx.write(any())).thenReturn(future); when(ctx.executor()).thenReturn(executor); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock in) throws Throwable { - Object msg = in.getArgument(0); - ReferenceCountUtil.release(msg); - return null; - } + doAnswer(in -> { + Object msg = in.getArgument(0); + ReferenceCountUtil.release(msg); + return null; }).when(ctx).fireChannelRead(any()); } @@ -261,15 +249,12 @@ public class Http2ConnectionHandlerTest { Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE; final AtomicBoolean verified = new AtomicBoolean(false); - final Answer verifier = new Answer() { - @Override - public Object answer(final InvocationOnMock in) throws Throwable { - assertTrue(in.getArgument(0).equals(evt)); // sanity check... - verify(ctx).write(eq(connectionPrefaceBuf())); - verify(encoder).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class)); - verified.set(true); - return null; - } + final Answer verifier = in -> { + assertTrue(in.getArgument(0).equals(evt)); // sanity check... + verify(ctx).write(eq(connectionPrefaceBuf())); + verify(encoder).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class)); + verified.set(true); + return null; }; doAnswer(verifier).when(ctx).fireUserEventTriggered(evt); @@ -562,23 +547,16 @@ public class Http2ConnectionHandlerTest { handler = newHandler(); when(future.isDone()).thenReturn(true); when(future.isSuccess()).thenReturn(true); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - GenericFutureListener listener = (GenericFutureListener) args[0]; - // Simulate that all streams have become inactive by the time the future completes. - doAnswer(new Answer() { - @Override - public Http2Stream answer(InvocationOnMock in) throws Throwable { - return null; - } - }).when(connection).forEachActiveStream(any(Http2StreamVisitor.class)); - when(connection.numActiveStreams()).thenReturn(0); - // Simulate the future being completed. - listener.operationComplete(future); - return future; - } + doAnswer((Answer) invocation -> { + Object[] args = invocation.getArguments(); + GenericFutureListener listener = (GenericFutureListener) args[0]; + // Simulate that all streams have become inactive by the time the future completes. + doAnswer((Answer) in -> null).when(connection).forEachActiveStream( + any(Http2StreamVisitor.class)); + when(connection.numActiveStreams()).thenReturn(0); + // Simulate the future being completed. + listener.operationComplete(future); + return future; }).when(future).addListener(any(GenericFutureListener.class)); handler.close(ctx, promise); if (future.isDone()) { @@ -597,12 +575,9 @@ public class Http2ConnectionHandlerTest { long errorCode = Http2Error.INTERNAL_ERROR.code(); when(future.isDone()).thenReturn(true); when(future.isSuccess()).thenReturn(true); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - ((GenericFutureListener) invocation.getArgument(0)).operationComplete(future); - return null; - } + doAnswer((Answer) invocation -> { + ((GenericFutureListener) invocation.getArgument(0)).operationComplete(future); + return null; }).when(future).addListener(any(GenericFutureListener.class)); handler = newHandler(); handler.goAway(ctx, STREAM_ID, errorCode, data, promise); @@ -645,11 +620,8 @@ public class Http2ConnectionHandlerTest { when(connection.goAwaySent()).thenReturn(true); when(remote.lastStreamKnownByPeer()).thenReturn(STREAM_ID); - doAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocationOnMock) { - throw new IllegalStateException(); - } + doAnswer((Answer) invocationOnMock -> { + throw new IllegalStateException(); }).when(connection).goAwaySent(anyInt(), anyLong(), any(ByteBuf.class)); handler.goAway(ctx, STREAM_ID + 2, errorCode, data, promise); assertTrue(promise.isDone()); @@ -665,18 +637,15 @@ public class Http2ConnectionHandlerTest { long errorCode = Http2Error.INTERNAL_ERROR.code(); handler = newHandler(); final Throwable cause = new RuntimeException("fake exception"); - doAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocation) throws Throwable { - ChannelPromise promise = invocation.getArgument(4); - assertFalse(promise.isVoid()); - // This is what DefaultHttp2FrameWriter does... I hate mocking :-(. - SimpleChannelPromiseAggregator aggregatedPromise = - new SimpleChannelPromiseAggregator(promise, channel, ImmediateEventExecutor.INSTANCE); - aggregatedPromise.newPromise(); - aggregatedPromise.doneAllocatingPromises(); - return aggregatedPromise.setFailure(cause); - } + doAnswer((Answer) invocation -> { + ChannelPromise promise = invocation.getArgument(4); + assertFalse(promise.isVoid()); + // This is what DefaultHttp2FrameWriter does... I hate mocking :-(. + SimpleChannelPromiseAggregator aggregatedPromise = + new SimpleChannelPromiseAggregator(promise, channel, ImmediateEventExecutor.INSTANCE); + aggregatedPromise.newPromise(); + aggregatedPromise.doneAllocatingPromises(); + return aggregatedPromise.setFailure(cause); }).when(frameWriter).writeGoAway( any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), any(ChannelPromise.class)); handler.goAway(ctx, STREAM_ID, errorCode, data, newVoidPromise(channel)); @@ -742,13 +711,10 @@ public class Http2ConnectionHandlerTest { final Throwable cause = new RuntimeException("fake exception"); when(stream.id()).thenReturn(STREAM_ID); when(frameWriter.writeRstStream(eq(ctx), eq(streamId), anyLong(), any(ChannelPromise.class))) - .then(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable { - ChannelPromise promise = invocationOnMock.getArgument(3); - assertFalse(promise.isVoid()); - return promise.setFailure(cause); - } + .then((Answer) invocationOnMock -> { + ChannelPromise promise = invocationOnMock.getArgument(3); + assertFalse(promise.isVoid()); + return promise.setFailure(cause); }); handler.resetStream(ctx, streamId, STREAM_CLOSED.code(), newVoidPromise(channel)); verify(frameWriter).writeRstStream(eq(ctx), eq(streamId), anyLong(), any(ChannelPromise.class)); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionRoundtripTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionRoundtripTest.java index 8c0ebf281d..13d5c274fb 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionRoundtripTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ConnectionRoundtripTest.java @@ -148,50 +148,38 @@ public class Http2ConnectionRoundtripTest { public void inflightFrameAfterStreamResetShouldNotMakeConnectionUnusable() throws Exception { bootstrapEnv(1, 1, 2, 1); final CountDownLatch latch = new CountDownLatch(1); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - ChannelHandlerContext ctx = invocationOnMock.getArgument(0); - http2Server.encoder().writeHeaders(ctx, - (Integer) invocationOnMock.getArgument(1), - (Http2Headers) invocationOnMock.getArgument(2), - 0, - false, - ctx.newPromise()); - http2Server.flush(ctx); - return null; - } + doAnswer(invocationOnMock -> { + ChannelHandlerContext ctx = invocationOnMock.getArgument(0); + http2Server.encoder().writeHeaders(ctx, + (Integer) invocationOnMock.getArgument(1), + (Http2Headers) invocationOnMock.getArgument(2), + 0, + false, + ctx.newPromise()); + http2Server.flush(ctx); + return null; }).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean()); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - latch.countDown(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + latch.countDown(); + return null; }).when(clientListener).onHeadersRead(any(ChannelHandlerContext.class), eq(5), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean()); // Create a single stream by sending a HEADERS frame to the server. final short weight = 16; final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, false, newPromise()); - http2Client.flush(ctx()); - http2Client.encoder().writeRstStream(ctx(), 3, Http2Error.INTERNAL_ERROR.code(), newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, false, newPromise()); + http2Client.flush(ctx()); + http2Client.encoder().writeRstStream(ctx(), 3, Http2Error.INTERNAL_ERROR.code(), newPromise()); + http2Client.flush(ctx()); }); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, weight, false, 0, false, newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, weight, false, 0, false, newPromise()); + http2Client.flush(ctx()); }); assertTrue(latch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -204,13 +192,10 @@ public class Http2ConnectionRoundtripTest { // Create a single stream by sending a HEADERS frame to the server. final short weight = 16; final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, true, - newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, true, + newPromise()); + http2Client.flush(ctx()); }); assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -245,68 +230,45 @@ public class Http2ConnectionRoundtripTest { final Http2Headers headers = dummyHeaders(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - serverSettingsAckLatch1.countDown(); - serverSettingsAckLatch2.countDown(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + serverSettingsAckLatch1.countDown(); + serverSettingsAckLatch2.countDown(); + return null; }).when(serverListener).onSettingsAckRead(any(ChannelHandlerContext.class)); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - clientSettingsLatch1.countDown(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + clientSettingsLatch1.countDown(); + return null; }).when(clientListener).onSettingsRead(any(ChannelHandlerContext.class), any(Http2Settings.class)); // Manually add a listener for when we receive the expected headers on the server. - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - serverRevHeadersLatch.countDown(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + serverRevHeadersLatch.countDown(); + return null; }).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(5), eq(headers), anyInt(), anyShort(), anyBoolean(), eq(0), eq(true)); // Set the maxHeaderListSize to 100 so we may be able to write some headers, but not all. We want to verify // that we don't corrupt state if some can be written but not all. - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Server.encoder().writeSettings(serverCtx(), - new Http2Settings().copyFrom(http2Server.decoder().localSettings()) - .maxHeaderListSize(100), - serverNewPromise()); - http2Server.flush(serverCtx()); - } + runInChannel(serverConnectedChannel, () -> { + http2Server.encoder().writeSettings(serverCtx(), + new Http2Settings().copyFrom(http2Server.decoder().localSettings()) + .maxHeaderListSize(100), + serverNewPromise()); + http2Server.flush(serverCtx()); }); assertTrue(serverSettingsAckLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, false, newPromise()) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - clientHeadersWriteException.set(future.cause()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, false, newPromise()) + .addListener((ChannelFutureListener) future -> clientHeadersWriteException.set(future.cause())); + // It is expected that this write should fail locally and the remote peer will never see this. + http2Client.encoder().writeData(ctx(), 3, Unpooled.buffer(), 0, true, newPromise()) + .addListener((ChannelFutureListener) future -> { + clientDataWriteException.set(future.cause()); + clientDataWrite.countDown(); }); - // It is expected that this write should fail locally and the remote peer will never see this. - http2Client.encoder().writeData(ctx(), 3, Unpooled.buffer(), 0, true, newPromise()) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - clientDataWriteException.set(future.cause()); - clientDataWrite.countDown(); - } - }); - http2Client.flush(ctx()); - } + http2Client.flush(ctx()); }); assertTrue(clientDataWrite.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -314,33 +276,24 @@ public class Http2ConnectionRoundtripTest { assertNotNull("Data on closed stream should fail!", clientDataWriteException.get()); // Set the maxHeaderListSize to the max value so we can send the headers. - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Server.encoder().writeSettings(serverCtx(), - new Http2Settings().copyFrom(http2Server.decoder().localSettings()) - .maxHeaderListSize(Http2CodecUtil.MAX_HEADER_LIST_SIZE), - serverNewPromise()); - http2Server.flush(serverCtx()); - } + runInChannel(serverConnectedChannel, () -> { + http2Server.encoder().writeSettings(serverCtx(), + new Http2Settings().copyFrom(http2Server.decoder().localSettings()) + .maxHeaderListSize(Http2CodecUtil.MAX_HEADER_LIST_SIZE), + serverNewPromise()); + http2Server.flush(serverCtx()); }); assertTrue(clientSettingsLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); assertTrue(serverSettingsAckLatch2.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, true, - newPromise()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - clientHeadersWriteException2.set(future.cause()); - clientHeadersLatch.countDown(); - } - }); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, true, + newPromise()).addListener((ChannelFutureListener) future -> { + clientHeadersWriteException2.set(future.cause()); + clientHeadersLatch.countDown(); + }); + http2Client.flush(ctx()); }); assertTrue(clientHeadersLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -371,69 +324,54 @@ public class Http2ConnectionRoundtripTest { final byte[] data = new byte[] {1, 2, 3, 4, 5}; final ByteArrayOutputStream out = new ByteArrayOutputStream(data.length); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - serverSettingsAckLatch1.countDown(); - serverSettingsAckLatch2.countDown(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + serverSettingsAckLatch1.countDown(); + serverSettingsAckLatch2.countDown(); + return null; }).when(serverListener).onSettingsAckRead(any(ChannelHandlerContext.class)); - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock in) throws Throwable { - ByteBuf buf = (ByteBuf) in.getArguments()[2]; - int padding = (Integer) in.getArguments()[3]; - int processedBytes = buf.readableBytes() + padding; + doAnswer((Answer) in -> { + ByteBuf buf = (ByteBuf) in.getArguments()[2]; + int padding = (Integer) in.getArguments()[3]; + int processedBytes = buf.readableBytes() + padding; - buf.readBytes(out, buf.readableBytes()); - serverDataLatch.countDown(); - return processedBytes; - } + buf.readBytes(out, buf.readableBytes()); + serverDataLatch.countDown(); + return processedBytes; }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3), any(ByteBuf.class), eq(0), anyBoolean()); final Http2Headers headers = dummyHeaders(); // The server initially reduces the connection flow control window to 0. - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Server.encoder().writeSettings(serverCtx(), - new Http2Settings().copyFrom(http2Server.decoder().localSettings()) - .initialWindowSize(0), - serverNewPromise()); - http2Server.flush(serverCtx()); - } + runInChannel(serverConnectedChannel, () -> { + http2Server.encoder().writeSettings(serverCtx(), + new Http2Settings().copyFrom(http2Server.decoder().localSettings()) + .initialWindowSize(0), + serverNewPromise()); + http2Server.flush(serverCtx()); }); assertTrue(serverSettingsAckLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); // The client should now attempt to send data, but the window size is 0 so it will be queued in the flow // controller. - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, - newPromise()); - http2Client.encoder().writeData(ctx(), 3, Unpooled.wrappedBuffer(data), 0, true, newPromise()); - http2Client.flush(ctx()); - clientWriteDataLatch.countDown(); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, + newPromise()); + http2Client.encoder().writeData(ctx(), 3, Unpooled.wrappedBuffer(data), 0, true, newPromise()); + http2Client.flush(ctx()); + clientWriteDataLatch.countDown(); }); assertTrue(clientWriteDataLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); // Now the server opens up the connection window to allow the client to send the pending data. - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Server.encoder().writeSettings(serverCtx(), - new Http2Settings().copyFrom(http2Server.decoder().localSettings()) - .initialWindowSize(data.length), - serverNewPromise()); - http2Server.flush(serverCtx()); - } + runInChannel(serverConnectedChannel, () -> { + http2Server.encoder().writeSettings(serverCtx(), + new Http2Settings().copyFrom(http2Server.decoder().localSettings()) + .initialWindowSize(data.length), + serverNewPromise()); + http2Server.flush(serverCtx()); }); assertTrue(serverSettingsAckLatch2.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -454,14 +392,11 @@ public class Http2ConnectionRoundtripTest { bootstrapEnv(1, 1, 2, 0); final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writePriority(ctx(), 5, 3, (short) 14, false, newPromise()); - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, - newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writePriority(ctx(), 5, 3, (short) 14, false, newPromise()); + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, + newPromise()); + http2Client.flush(ctx()); }); assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -486,15 +421,12 @@ public class Http2ConnectionRoundtripTest { bootstrapEnv(1, 1, 1, 0); final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, false, - newPromise()); - http2Client.encoder().frameWriter().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, - newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, false, + newPromise()); + http2Client.encoder().frameWriter().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, + newPromise()); + http2Client.flush(ctx()); }); assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -525,24 +457,18 @@ public class Http2ConnectionRoundtripTest { final Http2Headers headers = dummyHeaders(); final int streamId = 3; - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), streamId, headers, CONNECTION_STREAM_ID, - DEFAULT_PRIORITY_WEIGHT, false, 0, false, newPromise()); - http2Client.encoder().writeRstStream(ctx(), streamId, Http2Error.CANCEL.code(), newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), streamId, headers, CONNECTION_STREAM_ID, + DEFAULT_PRIORITY_WEIGHT, false, 0, false, newPromise()); + http2Client.encoder().writeRstStream(ctx(), streamId, Http2Error.CANCEL.code(), newPromise()); + http2Client.flush(ctx()); }); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - if (streamId == (Integer) invocationOnMock.getArgument(1)) { - serverGotRstLatch.countDown(); - } - return null; + doAnswer((Answer) invocationOnMock -> { + if (streamId == (Integer) invocationOnMock.getArgument(1)) { + serverGotRstLatch.countDown(); } + return null; }).when(serverListener).onRstStreamRead(any(ChannelHandlerContext.class), eq(streamId), anyLong()); assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -552,19 +478,13 @@ public class Http2ConnectionRoundtripTest { anyShort(), anyBoolean(), anyInt(), eq(false)); // Now have the server attempt to send a headers frame simulating some asynchronous work. - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Server.encoder().writeHeaders(serverCtx(), streamId, headers, 0, true, serverNewPromise()) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - serverWriteHeadersCauseRef.set(future.cause()); - serverWriteHeadersLatch.countDown(); - } - }); - http2Server.flush(serverCtx()); - } + runInChannel(serverConnectedChannel, () -> { + http2Server.encoder().writeHeaders(serverCtx(), streamId, headers, 0, true, serverNewPromise()) + .addListener((ChannelFutureListener) future -> { + serverWriteHeadersCauseRef.set(future.cause()); + serverWriteHeadersLatch.countDown(); + }); + http2Server.flush(serverCtx()); }); assertTrue(serverWriteHeadersLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -586,22 +506,14 @@ public class Http2ConnectionRoundtripTest { // Create a latch to track when the close occurs. final CountDownLatch closeLatch = new CountDownLatch(1); - clientChannel.closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - closeLatch.countDown(); - } - }); + clientChannel.closeFuture().addListener((ChannelFutureListener) future -> closeLatch.countDown()); // Create a single stream by sending a HEADERS frame to the server. final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, - newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, + newPromise()); + http2Client.flush(ctx()); }); // Wait for the server to create the stream. @@ -632,21 +544,13 @@ public class Http2ConnectionRoundtripTest { // Create a latch to track when the close occurs. final CountDownLatch closeLatch = new CountDownLatch(1); - clientChannel.closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - closeLatch.countDown(); - } - }); + clientChannel.closeFuture().addListener((ChannelFutureListener) future -> closeLatch.countDown()); // Create a single stream by sending a HEADERS frame to the server. - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, - newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, + newPromise()); + http2Client.flush(ctx()); }); // Wait for the server to create the stream. @@ -690,37 +594,34 @@ public class Http2ConnectionRoundtripTest { bootstrapEnv(1, 1, 2, 1); final ChannelPromise emptyDataPromise = newPromise(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false, - newPromise()); - ByteBuf emptyBuf = Unpooled.buffer(); - emptyBuf.release(); - switch (mode) { - case SINGLE_END_OF_STREAM: - http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, true, emptyDataPromise); - break; - case SECOND_END_OF_STREAM: - http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise); - http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, true, newPromise()); - break; - case SINGLE_WITH_TRAILERS: - http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise); - http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, - (short) 16, false, 0, true, newPromise()); - break; - case SECOND_WITH_TRAILERS: - http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise); - http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, newPromise()); - http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, - (short) 16, false, 0, true, newPromise()); - break; - default: - throw new Error(); - } - http2Client.flush(ctx()); + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false, + newPromise()); + ByteBuf emptyBuf = Unpooled.buffer(); + emptyBuf.release(); + switch (mode) { + case SINGLE_END_OF_STREAM: + http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, true, emptyDataPromise); + break; + case SECOND_END_OF_STREAM: + http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise); + http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, true, newPromise()); + break; + case SINGLE_WITH_TRAILERS: + http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise); + http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, + (short) 16, false, 0, true, newPromise()); + break; + case SECOND_WITH_TRAILERS: + http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise); + http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, newPromise()); + http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, + (short) 16, false, 0, true, newPromise()); + break; + default: + throw new Error(); } + http2Client.flush(ctx()); }); try { @@ -739,38 +640,35 @@ public class Http2ConnectionRoundtripTest { final ChannelPromise dataPromise = newPromise(); final ChannelPromise assertPromise = newPromise(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false, - newPromise()); - clientChannel.pipeline().addFirst(new ChannelOutboundHandlerAdapter() { - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - ReferenceCountUtil.release(msg); + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false, + newPromise()); + clientChannel.pipeline().addFirst(new ChannelOutboundHandlerAdapter() { + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + ReferenceCountUtil.release(msg); - // Ensure we update the window size so we will try to write the rest of the frame while - // processing the flush. - http2Client.encoder().flowController().initialWindowSize(8); - promise.setFailure(new IllegalStateException()); - } - }); - - http2Client.encoder().flowController().initialWindowSize(4); - http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, dataPromise); - assertTrue(http2Client.encoder().flowController() - .hasFlowControlled(http2Client.connection().stream(3))); - - http2Client.flush(ctx()); - - try { - // The Frame should have been removed after the write failed. - assertFalse(http2Client.encoder().flowController() - .hasFlowControlled(http2Client.connection().stream(3))); - assertPromise.setSuccess(); - } catch (Throwable error) { - assertPromise.setFailure(error); + // Ensure we update the window size so we will try to write the rest of the frame while + // processing the flush. + http2Client.encoder().flowController().initialWindowSize(8); + promise.setFailure(new IllegalStateException()); } + }); + + http2Client.encoder().flowController().initialWindowSize(4); + http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, dataPromise); + assertTrue(http2Client.encoder().flowController() + .hasFlowControlled(http2Client.connection().stream(3))); + + http2Client.flush(ctx()); + + try { + // The Frame should have been removed after the write failed. + assertFalse(http2Client.encoder().flowController() + .hasFlowControlled(http2Client.connection().stream(3))); + assertPromise.setSuccess(); + } catch (Throwable error) { + assertPromise.setFailure(error); } }); @@ -790,22 +688,14 @@ public class Http2ConnectionRoundtripTest { // Create a latch to track when the close occurs. final CountDownLatch closeLatch = new CountDownLatch(1); - clientChannel.closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - closeLatch.countDown(); - } - }); + clientChannel.closeFuture().addListener((ChannelFutureListener) future -> closeLatch.countDown()); // Create a single stream by sending a HEADERS frame to the server. final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, - newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, + newPromise()); + http2Client.flush(ctx()); }); // Wait for the server to create the stream. @@ -837,24 +727,18 @@ public class Http2ConnectionRoundtripTest { // Create a single stream by sending a HEADERS frame to the server. final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, - true, newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, + true, newPromise()); + http2Client.flush(ctx()); }); assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), MAX_VALUE + 1, headers, 0, (short) 16, false, 0, - true, newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), MAX_VALUE + 1, headers, 0, (short) 16, false, 0, + true, newPromise()); + http2Client.flush(ctx()); }); assertTrue(goAwayLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -871,23 +755,17 @@ public class Http2ConnectionRoundtripTest { setServerGracefulShutdownTime(10000); final CountDownLatch clientGoAwayLatch = new CountDownLatch(1); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - clientGoAwayLatch.countDown(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + clientGoAwayLatch.countDown(); + return null; }).when(clientListener).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class)); // Create a single stream by sending a HEADERS frame to the server. final Http2Headers headers = dummyHeaders(); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, - false, newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, + false, newPromise()); + http2Client.flush(ctx()); }); assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -895,12 +773,9 @@ public class Http2ConnectionRoundtripTest { // Server has received the headers, so the stream is open assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); - runInChannel(serverChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise()); - http2Server.flush(serverCtx()); - } + runInChannel(serverChannel, () -> { + http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise()); + http2Server.flush(serverCtx()); }); // wait for the client to receive the GO_AWAY. @@ -910,20 +785,12 @@ public class Http2ConnectionRoundtripTest { final AtomicReference clientWriteAfterGoAwayFutureRef = new AtomicReference<>(); final CountDownLatch clientWriteAfterGoAwayLatch = new CountDownLatch(1); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, - true, newPromise()); - clientWriteAfterGoAwayFutureRef.set(f); - http2Client.flush(ctx()); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - clientWriteAfterGoAwayLatch.countDown(); - } - }); - } + runInChannel(clientChannel, () -> { + ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, + true, newPromise()); + clientWriteAfterGoAwayFutureRef.set(f); + http2Client.flush(ctx()); + f.addListener((ChannelFutureListener) future -> clientWriteAfterGoAwayLatch.countDown()); }); // Wait for the client's write operation to complete. @@ -950,12 +817,9 @@ public class Http2ConnectionRoundtripTest { bootstrapEnv(1, 1, 2, 1, 1); final CountDownLatch clientGoAwayLatch = new CountDownLatch(1); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - clientGoAwayLatch.countDown(); - return null; - } + doAnswer((Answer) invocationOnMock -> { + clientGoAwayLatch.countDown(); + return null; }).when(clientListener).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class)); // We want both sides to do graceful shutdown during the test. @@ -965,30 +829,19 @@ public class Http2ConnectionRoundtripTest { final Http2Headers headers = dummyHeaders(); final AtomicReference clientWriteAfterGoAwayFutureRef = new AtomicReference<>(); final CountDownLatch clientWriteAfterGoAwayLatch = new CountDownLatch(1); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, - true, newPromise()); - clientWriteAfterGoAwayFutureRef.set(f); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - clientWriteAfterGoAwayLatch.countDown(); - } - }); - http2Client.flush(ctx()); - return null; - } + doAnswer((Answer) invocationOnMock -> { + ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, + true, newPromise()); + clientWriteAfterGoAwayFutureRef.set(f); + f.addListener((ChannelFutureListener) future -> clientWriteAfterGoAwayLatch.countDown()); + http2Client.flush(ctx()); + return null; }).when(clientListener).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class)); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, - true, newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, + true, newPromise()); + http2Client.flush(ctx()); }); assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); @@ -996,12 +849,9 @@ public class Http2ConnectionRoundtripTest { // Server has received the headers, so the stream is open assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); - runInChannel(serverChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise()); - http2Server.flush(serverCtx()); - } + runInChannel(serverChannel, () -> { + http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise()); + http2Server.flush(serverCtx()); }); // Wait for the client's write operation to complete. @@ -1033,16 +883,13 @@ public class Http2ConnectionRoundtripTest { // Create a buffer filled with random bytes. final ByteBuf data = randomBytes(length); final ByteArrayOutputStream out = new ByteArrayOutputStream(length); - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock in) throws Throwable { - ByteBuf buf = (ByteBuf) in.getArguments()[2]; - int padding = (Integer) in.getArguments()[3]; - int processedBytes = buf.readableBytes() + padding; + doAnswer((Answer) in -> { + ByteBuf buf = (ByteBuf) in.getArguments()[2]; + int padding = (Integer) in.getArguments()[3]; + int processedBytes = buf.readableBytes() + padding; - buf.readBytes(out, buf.readableBytes()); - return processedBytes; - } + buf.readBytes(out, buf.readableBytes()); + return processedBytes; }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3), any(ByteBuf.class), eq(0), anyBoolean()); try { @@ -1050,18 +897,15 @@ public class Http2ConnectionRoundtripTest { bootstrapEnv(length, 1, 2, 1); // Create the stream and send all of the data at once. - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, - false, newPromise()); - http2Client.encoder().writeData(ctx(), 3, data.retainedDuplicate(), 0, false, newPromise()); + runInChannel(clientChannel, () -> { + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, + false, newPromise()); + http2Client.encoder().writeData(ctx(), 3, data.retainedDuplicate(), 0, false, newPromise()); - // Write trailers. - http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, - true, newPromise()); - http2Client.flush(ctx()); - } + // Write trailers. + http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, + true, newPromise()); + http2Client.flush(ctx()); }); // Wait for the trailers to be received. @@ -1110,44 +954,38 @@ public class Http2ConnectionRoundtripTest { // Collect all the data buffers as we receive them at the server. final StringBuilder[] receivedData = new StringBuilder[numStreams]; - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock in) throws Throwable { - int streamId = (Integer) in.getArguments()[1]; - ByteBuf buf = (ByteBuf) in.getArguments()[2]; - int padding = (Integer) in.getArguments()[3]; - int processedBytes = buf.readableBytes() + padding; + doAnswer((Answer) in -> { + int streamId = (Integer) in.getArguments()[1]; + ByteBuf buf = (ByteBuf) in.getArguments()[2]; + int padding = (Integer) in.getArguments()[3]; + int processedBytes = buf.readableBytes() + padding; - int streamIndex = (streamId - 3) / 2; - StringBuilder builder = receivedData[streamIndex]; - if (builder == null) { - builder = new StringBuilder(dataAsHex.length()); - receivedData[streamIndex] = builder; - } - builder.append(ByteBufUtil.hexDump(buf)); - return processedBytes; + int streamIndex = (streamId - 3) / 2; + StringBuilder builder = receivedData[streamIndex]; + if (builder == null) { + builder = new StringBuilder(dataAsHex.length()); + receivedData[streamIndex] = builder; } + builder.append(ByteBufUtil.hexDump(buf)); + return processedBytes; }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean()); try { bootstrapEnv(numStreams * length, 1, numStreams * 4, numStreams); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - int upperLimit = 3 + 2 * numStreams; - for (int streamId = 3; streamId < upperLimit; streamId += 2) { - // Send a bunch of data on each stream. - http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16, - false, 0, false, newPromise()); - http2Client.encoder().writePing(ctx(), false, pingData, - newPromise()); - http2Client.encoder().writeData(ctx(), streamId, data.retainedSlice(), 0, - false, newPromise()); - // Write trailers. - http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16, - false, 0, true, newPromise()); - http2Client.flush(ctx()); - } + runInChannel(clientChannel, () -> { + int upperLimit = 3 + 2 * numStreams; + for (int streamId = 3; streamId < upperLimit; streamId += 2) { + // Send a bunch of data on each stream. + http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16, + false, 0, false, newPromise()); + http2Client.encoder().writePing(ctx(), false, pingData, + newPromise()); + http2Client.encoder().writeData(ctx(), streamId, data.retainedSlice(), 0, + false, newPromise()); + // Write trailers. + http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16, + false, 0, true, newPromise()); + http2Client.flush(ctx()); } }); // Wait for all frames to be received. @@ -1270,15 +1108,11 @@ public class Http2ConnectionRoundtripTest { } private static void mockFlowControl(Http2FrameListener listener) throws Http2Exception { - doAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - ByteBuf buf = (ByteBuf) invocation.getArguments()[2]; - int padding = (Integer) invocation.getArguments()[3]; - int processedBytes = buf.readableBytes() + padding; - return processedBytes; - } - + doAnswer((Answer) invocation -> { + ByteBuf buf = (ByteBuf) invocation.getArguments()[2]; + int padding = (Integer) invocation.getArguments()[3]; + int processedBytes = buf.readableBytes() + padding; + return processedBytes; }).when(listener).onDataRead(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean()); } @@ -1294,12 +1128,9 @@ public class Http2ConnectionRoundtripTest { private static void setGracefulShutdownTime(Channel channel, final Http2ConnectionHandler handler, final long millis) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - runInChannel(channel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - handler.gracefulShutdownTimeoutMillis(millis); - latch.countDown(); - } + runInChannel(channel, () -> { + handler.gracefulShutdownTimeoutMillis(millis); + latch.countDown(); }); assertTrue(latch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameCodecTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameCodecTest.java index 8800368b67..6f43827a94 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameCodecTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameCodecTest.java @@ -573,15 +573,12 @@ public class Http2FrameCodecTest { final Promise listenerExecuted = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), false).stream(stream)) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - assertTrue(future.isSuccess()); - assertTrue(isStreamIdValid(stream.id())); - listenerExecuted.setSuccess(null); - } - } - ); + .addListener((ChannelFutureListener) future -> { + assertTrue(future.isSuccess()); + assertTrue(isStreamIdValid(stream.id())); + listenerExecuted.setSuccess(null); + } + ); ByteBuf data = Unpooled.buffer().writeZero(100); ChannelFuture f = channel.writeAndFlush(new DefaultHttp2DataFrame(data).stream(stream)); assertTrue(f.isSuccess()); @@ -735,12 +732,9 @@ public class Http2FrameCodecTest { Http2FrameStream idleStream = frameCodec.newStream(); final Set activeStreams = new HashSet<>(); - frameCodec.forEachActiveStream(new Http2FrameStreamVisitor() { - @Override - public boolean visit(Http2FrameStream stream) { - activeStreams.add(stream); - return true; - } + frameCodec.forEachActiveStream(stream -> { + activeStreams.add(stream); + return true; }); assertEquals(2, activeStreams.size()); @@ -758,13 +752,10 @@ public class Http2FrameCodecTest { final AtomicBoolean listenerExecuted = new AtomicBoolean(); channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()).stream(stream2)) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - assertTrue(future.isSuccess()); - assertEquals(State.OPEN, stream2.state()); - listenerExecuted.set(true); - } + .addListener((ChannelFutureListener) future -> { + assertTrue(future.isSuccess()); + assertEquals(State.OPEN, stream2.state()); + listenerExecuted.set(true); }); assertTrue(listenerExecuted.get()); @@ -795,15 +786,12 @@ public class Http2FrameCodecTest { // Simulate consuming the frame and update the flow-controller. Http2DataFrame data = (Http2DataFrame) msg; ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(data.initialFlowControlledBytes()) - .stream(data.stream())).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - Throwable cause = future.cause(); - if (cause != null) { - ctx.fireExceptionCaught(cause); - } - } - }); + .stream(data.stream())).addListener((ChannelFutureListener) future -> { + Throwable cause = future.cause(); + if (cause != null) { + ctx.fireExceptionCaught(cause); + } + }); } ReferenceCountUtil.release(msg); } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameRoundtripTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameRoundtripTest.java index dc7348004a..83e35d51a5 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameRoundtripTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2FrameRoundtripTest.java @@ -97,24 +97,10 @@ public class Http2FrameRoundtripTest { when(ctx.alloc()).thenReturn(alloc); when(ctx.executor()).thenReturn(executor); when(ctx.channel()).thenReturn(channel); - doAnswer(new Answer() { - @Override - public ByteBuf answer(InvocationOnMock in) throws Throwable { - return Unpooled.buffer(); - } - }).when(alloc).buffer(); - doAnswer(new Answer() { - @Override - public ByteBuf answer(InvocationOnMock in) throws Throwable { - return Unpooled.buffer((Integer) in.getArguments()[0]); - } - }).when(alloc).buffer(anyInt()); - doAnswer(new Answer() { - @Override - public ChannelPromise answer(InvocationOnMock invocation) throws Throwable { - return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE); - } - }).when(ctx).newPromise(); + doAnswer((Answer) in -> Unpooled.buffer()).when(alloc).buffer(); + doAnswer((Answer) in -> Unpooled.buffer((Integer) in.getArguments()[0])).when(alloc).buffer(anyInt()); + doAnswer((Answer) invocation -> + new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE)).when(ctx).newPromise(); writer = new DefaultHttp2FrameWriter(new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE, newTestEncoder())); reader = new DefaultHttp2FrameReader(new DefaultHttp2HeadersDecoder(false, newTestDecoder())); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java index 0cfbe4b889..f33b16abe1 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java @@ -245,12 +245,7 @@ public class Http2MultiplexCodecTest { frameInboundWriter.writeInboundData(channel.stream().id(), tenBytes, 0, true); // Verify we marked the bytes as consumed - verify(flowController).consumeBytes(argThat(new ArgumentMatcher() { - @Override - public boolean matches(Http2Stream http2Stream) { - return http2Stream.id() == channel.stream().id(); - } - }), eq(10)); + verify(flowController).consumeBytes(argThat(http2Stream -> http2Stream.id() == channel.stream().id()), eq(10)); // headers and data frame verifyFramesMultiplexedToCorrectChannel(channel, handler, 2); @@ -459,13 +454,9 @@ public class Http2MultiplexCodecTest { Http2Headers headers = new DefaultHttp2Headers(); when(frameWriter.writeHeaders(eqMultiplexCodecCtx(), anyInt(), eq(headers), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(), - any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(8)).setFailure( - new StreamException(childChannel.stream().id(), Http2Error.STREAM_CLOSED, "Stream Closed")); - } - }); + any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(8)).setFailure( + new StreamException(childChannel.stream().id(), Http2Error.STREAM_CLOSED, "Stream Closed"))); ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers())); parentChannel.flush(); @@ -521,13 +512,9 @@ public class Http2MultiplexCodecTest { Http2Headers headers = new DefaultHttp2Headers(); when(frameWriter.writeHeaders(eqMultiplexCodecCtx(), anyInt(), eq(headers), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(), - any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(8)).setFailure( - new Http2NoMoreStreamIdsException()); - } - }); + any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(8)).setFailure( + new Http2NoMoreStreamIdsException())); ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers)); parentChannel.flush(); @@ -554,12 +541,9 @@ public class Http2MultiplexCodecTest { // Create a promise before actually doing the close, because otherwise we would be adding a listener to a future // that is already completed because we are using EmbeddedChannel which executes code in the JUnit thread. ChannelPromise p = childChannel.newPromise(); - p.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - channelOpen.set(future.channel().isOpen()); - channelActive.set(future.channel().isActive()); - } + p.addListener((ChannelFutureListener) future -> { + channelOpen.set(future.channel().isOpen()); + channelActive.set(future.channel().isActive()); }); childChannel.close(p).syncUninterruptibly(); @@ -579,12 +563,9 @@ public class Http2MultiplexCodecTest { final AtomicBoolean channelOpen = new AtomicBoolean(true); final AtomicBoolean channelActive = new AtomicBoolean(true); - childChannel.closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - channelOpen.set(future.channel().isOpen()); - channelActive.set(future.channel().isActive()); - } + childChannel.closeFuture().addListener((ChannelFutureListener) future -> { + channelOpen.set(future.channel().isOpen()); + channelActive.set(future.channel().isActive()); }); childChannel.close().syncUninterruptibly(); @@ -609,23 +590,17 @@ public class Http2MultiplexCodecTest { Http2Headers headers = new DefaultHttp2Headers(); when(frameWriter.writeHeaders(eqMultiplexCodecCtx(), anyInt(), eq(headers), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(), - any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - ChannelPromise promise = invocationOnMock.getArgument(8); - writePromises.offer(promise); - return promise; - } - }); + any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> { + ChannelPromise promise = invocationOnMock.getArgument(8); + writePromises.offer(promise); + return promise; + }); ChannelFuture f = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers)); assertFalse(f.isDone()); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - channelOpen.set(future.channel().isOpen()); - channelActive.set(future.channel().isActive()); - } + f.addListener((ChannelFutureListener) future -> { + channelOpen.set(future.channel().isOpen()); + channelActive.set(future.channel().isActive()); }); ChannelPromise first = writePromises.poll(); @@ -794,12 +769,9 @@ public class Http2MultiplexCodecTest { public void endOfStreamDoesNotDiscardData() { AtomicInteger numReads = new AtomicInteger(1); final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean(); - Consumer ctxConsumer = new Consumer() { - @Override - public void accept(ChannelHandlerContext obj) { - if (shouldDisableAutoRead.get()) { - obj.channel().config().setAutoRead(false); - } + Consumer ctxConsumer = obj -> { + if (shouldDisableAutoRead.get()) { + obj.channel().config().setAutoRead(false); } }; LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer); @@ -859,13 +831,10 @@ public class Http2MultiplexCodecTest { AtomicInteger numReads = new AtomicInteger(1); final AtomicInteger channelReadCompleteCount = new AtomicInteger(0); final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean(); - Consumer ctxConsumer = new Consumer() { - @Override - public void accept(ChannelHandlerContext obj) { - channelReadCompleteCount.incrementAndGet(); - if (shouldDisableAutoRead.get()) { - obj.channel().config().setAutoRead(false); - } + Consumer ctxConsumer = obj -> { + channelReadCompleteCount.incrementAndGet(); + if (shouldDisableAutoRead.get()) { + obj.channel().config().setAutoRead(false); } }; LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer); @@ -922,13 +891,10 @@ public class Http2MultiplexCodecTest { final AtomicInteger numReads = new AtomicInteger(1); final AtomicInteger channelReadCompleteCount = new AtomicInteger(0); final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean(); - Consumer ctxConsumer = new Consumer() { - @Override - public void accept(ChannelHandlerContext obj) { - channelReadCompleteCount.incrementAndGet(); - if (shouldDisableAutoRead.get()) { - obj.channel().config().setAutoRead(false); - } + Consumer ctxConsumer = obj -> { + channelReadCompleteCount.incrementAndGet(); + if (shouldDisableAutoRead.get()) { + obj.channel().config().setAutoRead(false); } }; final LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java index 75ca0f4893..24427e6a9c 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java @@ -70,14 +70,11 @@ public final class Http2TestUtil { * Runs the given operation within the event loop thread of the given {@link Channel}. */ static void runInChannel(Channel channel, final Http2Runnable runnable) { - channel.eventLoop().execute(new Runnable() { - @Override - public void run() { - try { - runnable.run(); - } catch (Http2Exception e) { - throw new RuntimeException(e); - } + channel.eventLoop().execute(() -> { + try { + runnable.run(); + } catch (Http2Exception e) { + throw new RuntimeException(e); } }); } @@ -477,12 +474,9 @@ public final class Http2TestUtil { public ChannelPromise unvoid() { ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - channel().pipeline().fireExceptionCaught(future.cause()); - } + promise.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + channel().pipeline().fireExceptionCaught(future.cause()); } }); return promise; @@ -575,103 +569,63 @@ public final class Http2TestUtil { final ConcurrentLinkedQueue buffers = new ConcurrentLinkedQueue<>(); Http2FrameWriter frameWriter = Mockito.mock(Http2FrameWriter.class); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) { - for (;;) { - ByteBuf buf = buffers.poll(); - if (buf == null) { - break; - } - buf.release(); + doAnswer(invocationOnMock -> { + for (;;) { + ByteBuf buf = buffers.poll(); + if (buf == null) { + break; } - return null; + buf.release(); } + return null; }).when(frameWriter).close(); when(frameWriter.configuration()).thenReturn(configuration); when(frameWriter.writeSettings(any(ChannelHandlerContext.class), any(Http2Settings.class), - any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(2)).setSuccess(); - } - }); + any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(2)).setSuccess()); when(frameWriter.writeSettingsAck(any(ChannelHandlerContext.class), any(ChannelPromise.class))) - .thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(1)).setSuccess(); - } - }); + .thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(1)).setSuccess()); when(frameWriter.writeGoAway(any(ChannelHandlerContext.class), anyInt(), - anyLong(), any(ByteBuf.class), any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - buffers.offer((ByteBuf) invocationOnMock.getArgument(3)); - return ((ChannelPromise) invocationOnMock.getArgument(4)).setSuccess(); - } - }); + anyLong(), any(ByteBuf.class), any(ChannelPromise.class))).thenAnswer(invocationOnMock -> { + buffers.offer((ByteBuf) invocationOnMock.getArgument(3)); + return ((ChannelPromise) invocationOnMock.getArgument(4)).setSuccess(); + }); when(frameWriter.writeHeaders(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class), anyInt(), - anyBoolean(), any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess(); - } - }); + anyBoolean(), any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess()); when(frameWriter.writeHeaders(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(), - any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(8)).setSuccess(); - } - }); + any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(8)).setSuccess()); when(frameWriter.writeData(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(), - anyBoolean(), any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - buffers.offer((ByteBuf) invocationOnMock.getArgument(2)); - return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess(); - } - }); + anyBoolean(), any(ChannelPromise.class))).thenAnswer(invocationOnMock -> { + buffers.offer((ByteBuf) invocationOnMock.getArgument(2)); + return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess(); + }); when(frameWriter.writeRstStream(any(ChannelHandlerContext.class), anyInt(), - anyLong(), any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess(); - } - }); + anyLong(), any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess()); when(frameWriter.writeWindowUpdate(any(ChannelHandlerContext.class), anyInt(), anyInt(), - any(ChannelPromise.class))).then(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess(); - } - }); + any(ChannelPromise.class))).then((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess()); when(frameWriter.writePushPromise(any(ChannelHandlerContext.class), anyInt(), anyInt(), any(Http2Headers.class), - anyInt(), anyChannelPromise())).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess(); - } - }); + anyInt(), anyChannelPromise())).thenAnswer((Answer) invocationOnMock -> + ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess()); when(frameWriter.writeFrame(any(ChannelHandlerContext.class), anyByte(), anyInt(), any(Http2Flags.class), - any(ByteBuf.class), anyChannelPromise())).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - buffers.offer((ByteBuf) invocationOnMock.getArgument(4)); - return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess(); - } - }); + any(ByteBuf.class), anyChannelPromise())).thenAnswer(invocationOnMock -> { + buffers.offer((ByteBuf) invocationOnMock.getArgument(4)); + return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess(); + }); return frameWriter; } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpToHttp2ConnectionHandlerTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpToHttp2ConnectionHandlerTest.java index fa51734521..d19e720384 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpToHttp2ConnectionHandlerTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpToHttp2ConnectionHandlerTest.java @@ -337,12 +337,9 @@ public class HttpToHttp2ConnectionHandlerTest { public void testRequestWithBody() throws Exception { final String text = "foooooogoooo"; final List receivedBuffers = Collections.synchronizedList(new ArrayList<>()); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock in) throws Throwable { - receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8)); - return null; - } + doAnswer((Answer) in -> { + receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8)); + return null; }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3), any(ByteBuf.class), eq(0), eq(true)); bootstrapEnv(3, 1, 0); @@ -380,12 +377,9 @@ public class HttpToHttp2ConnectionHandlerTest { public void testRequestWithBodyAndTrailingHeaders() throws Exception { final String text = "foooooogoooo"; final List receivedBuffers = Collections.synchronizedList(new ArrayList<>()); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock in) throws Throwable { - receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8)); - return null; - } + doAnswer((Answer) in -> { + receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8)); + return null; }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3), any(ByteBuf.class), eq(0), eq(false)); bootstrapEnv(4, 1, 1); @@ -432,12 +426,9 @@ public class HttpToHttp2ConnectionHandlerTest { final String text = "foooooo"; final String text2 = "goooo"; final List receivedBuffers = Collections.synchronizedList(new ArrayList<>()); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock in) throws Throwable { - receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8)); - return null; - } + doAnswer((Answer) in -> { + receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8)); + return null; }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3), any(ByteBuf.class), eq(0), eq(false)); bootstrapEnv(4, 1, 1); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java index 8dcc8acc58..1b77fd686e 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java @@ -148,12 +148,9 @@ public class InboundHttp2ToHttpAdapterTest { final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")). scheme(new AsciiString("https")).authority(new AsciiString("example.org")) .path(new AsciiString("/some/path/resource2")); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -184,12 +181,9 @@ public class InboundHttp2ToHttpAdapterTest { .add(HttpHeaderNames.COOKIE, "a=b") .add(HttpHeaderNames.COOKIE, "c=d") .add(HttpHeaderNames.COOKIE, "e=f"); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -219,12 +213,9 @@ public class InboundHttp2ToHttpAdapterTest { .path(new AsciiString("/some/path/resource2")) .add(HttpHeaderNames.COOKIE, "a=b; c=d") .add(HttpHeaderNames.COOKIE, "e=f"); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -246,12 +237,9 @@ public class InboundHttp2ToHttpAdapterTest { .path(new AsciiString("/some/path/resource2")) .add(new AsciiString("çã".getBytes(CharsetUtil.UTF_8)), new AsciiString("Ãã".getBytes(CharsetUtil.UTF_8))); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitResponses(); assertTrue(isStreamError(clientException)); @@ -271,14 +259,11 @@ public class InboundHttp2ToHttpAdapterTest { httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16); final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path( new AsciiString("/some/path/resource2")); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); - clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true, - newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); + clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true, + newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -305,17 +290,14 @@ public class InboundHttp2ToHttpAdapterTest { final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path( new AsciiString("/some/path/resource2")); final int midPoint = text.length() / 2; - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); - clientHandler.encoder().writeData( - ctxClient(), 3, content.retainedSlice(0, midPoint), 0, false, newPromiseClient()); - clientHandler.encoder().writeData( - ctxClient(), 3, content.retainedSlice(midPoint, text.length() - midPoint), - 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); + clientHandler.encoder().writeData( + ctxClient(), 3, content.retainedSlice(0, midPoint), 0, false, newPromiseClient()); + clientHandler.encoder().writeData( + ctxClient(), 3, content.retainedSlice(midPoint, text.length() - midPoint), + 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -341,15 +323,12 @@ public class InboundHttp2ToHttpAdapterTest { httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16); final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path( new AsciiString("/some/path/resource2")); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); - clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient()); - clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient()); - clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); + clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient()); + clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient()); + clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -383,15 +362,12 @@ public class InboundHttp2ToHttpAdapterTest { .set(new AsciiString("foo"), new AsciiString("goo")) .set(new AsciiString("foo2"), new AsciiString("goo2")) .add(new AsciiString("foo2"), new AsciiString("goo3")); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); - clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, false, - newPromiseClient()); - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers2, 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); + clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, false, + newPromiseClient()); + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers2, 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -428,19 +404,16 @@ public class InboundHttp2ToHttpAdapterTest { new AsciiString("/some/path/resource")); final Http2Headers http2Headers2 = new DefaultHttp2Headers().method(new AsciiString("PUT")).path( new AsciiString("/some/path/resource2")); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); - clientHandler.encoder().writeHeaders(ctxClient(), 5, http2Headers2, 3, (short) 123, true, 0, - false, newPromiseClient()); - clientChannel.flush(); // Headers are queued in the flow controller and so flush them. - clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true, - newPromiseClient()); - clientHandler.encoder().writeData(ctxClient(), 5, content2.retainedDuplicate(), 0, true, - newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); + clientHandler.encoder().writeHeaders(ctxClient(), 5, http2Headers2, 3, (short) 123, true, 0, + false, newPromiseClient()); + clientChannel.flush(); // Headers are queued in the flow controller and so flush them. + clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true, + newPromiseClient()); + clientHandler.encoder().writeData(ctxClient(), 5, content2.retainedDuplicate(), 0, true, + newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor httpObjectCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -485,12 +458,9 @@ public class InboundHttp2ToHttpAdapterTest { httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16); final Http2Headers http2Headers3 = new DefaultHttp2Headers().method(new AsciiString("GET")) .path(new AsciiString("/push/test")); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers3, 0, true, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers3, 0, true, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -507,17 +477,14 @@ public class InboundHttp2ToHttpAdapterTest { final Http2Headers http2Headers2 = new DefaultHttp2Headers() .scheme(new AsciiString("https")) .authority(new AsciiString("example.org")); - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - serverHandler.encoder().writeHeaders(ctxServer(), 3, http2Headers, 0, false, newPromiseServer()); - serverHandler.encoder().writePushPromise(ctxServer(), 3, 2, http2Headers2, 0, newPromiseServer()); - serverHandler.encoder().writeData(ctxServer(), 3, content.retainedDuplicate(), 0, true, - newPromiseServer()); - serverHandler.encoder().writeData(ctxServer(), 5, content2.retainedDuplicate(), 0, true, - newPromiseServer()); - serverConnectedChannel.flush(); - } + runInChannel(serverConnectedChannel, () -> { + serverHandler.encoder().writeHeaders(ctxServer(), 3, http2Headers, 0, false, newPromiseServer()); + serverHandler.encoder().writePushPromise(ctxServer(), 3, 2, http2Headers2, 0, newPromiseServer()); + serverHandler.encoder().writeData(ctxServer(), 3, content.retainedDuplicate(), 0, true, + newPromiseServer()); + serverHandler.encoder().writeData(ctxServer(), 5, content2.retainedDuplicate(), 0, true, + newPromiseServer()); + serverConnectedChannel.flush(); }); awaitResponses(); ArgumentCaptor responseCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); @@ -553,12 +520,9 @@ public class InboundHttp2ToHttpAdapterTest { final FullHttpMessage response2 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); try { - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient()); + clientChannel.flush(); }); awaitRequests(); @@ -566,26 +530,20 @@ public class InboundHttp2ToHttpAdapterTest { httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0); final Http2Headers http2HeadersResponse = new DefaultHttp2Headers().status(new AsciiString("100")); - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse, 0, false, - newPromiseServer()); - serverConnectedChannel.flush(); - } + runInChannel(serverConnectedChannel, () -> { + serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse, 0, false, + newPromiseServer()); + serverConnectedChannel.flush(); }); awaitResponses(); httpHeaders = request2.headers(); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length()); httpHeaders.remove(HttpHeaderNames.EXPECT); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() { - clientHandler.encoder().writeData(ctxClient(), 3, payload.retainedDuplicate(), 0, true, - newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeData(ctxClient(), 3, payload.retainedDuplicate(), 0, true, + newPromiseClient()); + clientChannel.flush(); }); awaitRequests2(); @@ -595,13 +553,10 @@ public class InboundHttp2ToHttpAdapterTest { httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16); final Http2Headers http2HeadersResponse2 = new DefaultHttp2Headers().status(new AsciiString("200")); - runInChannel(serverConnectedChannel, new Http2Runnable() { - @Override - public void run() throws Http2Exception { - serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse2, 0, true, - newPromiseServer()); - serverConnectedChannel.flush(); - } + runInChannel(serverConnectedChannel, () -> { + serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse2, 0, true, + newPromiseServer()); + serverConnectedChannel.flush(); }); awaitResponses2(); @@ -633,12 +588,9 @@ public class InboundHttp2ToHttpAdapterTest { public void propagateSettings() throws Exception { boostrapEnv(1, 1, 2); final Http2Settings settings = new Http2Settings().pushEnabled(true); - runInChannel(clientChannel, new Http2Runnable() { - @Override - public void run() { - clientHandler.encoder().writeSettings(ctxClient(), settings, newPromiseClient()); - clientChannel.flush(); - } + runInChannel(clientChannel, () -> { + clientHandler.encoder().writeSettings(ctxClient(), settings, newPromiseClient()); + clientChannel.flush(); }); assertTrue(settingsLatch.await(5, SECONDS)); ArgumentCaptor settingsCaptor = ArgumentCaptor.forClass(Http2Settings.class); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/LastInboundHandler.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/LastInboundHandler.java index 120e171552..07cabd5041 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/LastInboundHandler.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/LastInboundHandler.java @@ -46,10 +46,7 @@ public class LastInboundHandler extends ChannelDuplexHandler { void accept(T obj); } - private static final Consumer NOOP_CONSUMER = new Consumer() { - @Override - public void accept(Object obj) { - } + private static final Consumer NOOP_CONSUMER = obj -> { }; @SuppressWarnings("unchecked") diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/StreamBufferingEncoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/StreamBufferingEncoderTest.java index 6a42e37d45..0e35555616 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/StreamBufferingEncoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/StreamBufferingEncoderTest.java @@ -130,12 +130,7 @@ public class StreamBufferingEncoderTest { when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(executor.inEventLoop()).thenReturn(true); - doAnswer(new Answer() { - @Override - public ChannelPromise answer(InvocationOnMock invocation) throws Throwable { - return newPromise(); - } - }).when(ctx).newPromise(); + doAnswer((Answer) invocation -> newPromise()).when(ctx).newPromise(); when(ctx.executor()).thenReturn(executor); when(channel.isActive()).thenReturn(false); when(channel.config()).thenReturn(config); @@ -519,17 +514,14 @@ public class StreamBufferingEncoderTest { } private Answer successAnswer() { - return new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocation) throws Throwable { - for (Object a : invocation.getArguments()) { - ReferenceCountUtil.safeRelease(a); - } - - ChannelPromise future = newPromise(); - future.setSuccess(); - return future; + return invocation -> { + for (Object a : invocation.getArguments()) { + ReferenceCountUtil.safeRelease(a); } + + ChannelPromise future = newPromise(); + future.setSuccess(); + return future; }; } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java index c804174b8b..6f81f832d7 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java @@ -83,17 +83,14 @@ public class UniformStreamByteDistributorTest { } private Answer writeAnswer() { - return new Answer() { - @Override - public Void answer(InvocationOnMock in) throws Throwable { - Http2Stream stream = in.getArgument(0); - int numBytes = in.getArgument(1); - TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); - state.pendingBytes -= numBytes; - state.hasFrame = state.pendingBytes > 0; - distributor.updateStreamableBytes(state); - return null; - } + return in -> { + Http2Stream stream = in.getArgument(0); + int numBytes = in.getArgument(1); + TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); + state.pendingBytes -= numBytes; + state.hasFrame = state.pendingBytes > 0; + distributor.updateStreamableBytes(state); + return null; }; } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorDependencyTreeTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorDependencyTreeTest.java index 5dd05d1823..747bba3e52 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorDependencyTreeTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorDependencyTreeTest.java @@ -79,13 +79,10 @@ public class WeightedFairQueueByteDistributorDependencyTreeTest extends final Http2Stream streamB = connection.local().createStream(5, false); final Http2Stream streamC = connection.local().createStream(7, false); setPriority(streamB.id(), streamA.id(), DEFAULT_PRIORITY_WEIGHT, false); - connection.forEachActiveStream(new Http2StreamVisitor() { - @Override - public boolean visit(Http2Stream stream) throws Http2Exception { - streamA.close(); - setPriority(streamB.id(), streamC.id(), DEFAULT_PRIORITY_WEIGHT, false); - return true; - } + connection.forEachActiveStream(stream -> { + streamA.close(); + setPriority(streamB.id(), streamC.id(), DEFAULT_PRIORITY_WEIGHT, false); + return true; }); } diff --git a/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/Socks5AddressEncoder.java b/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/Socks5AddressEncoder.java index 390622caba..215ad56b8d 100644 --- a/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/Socks5AddressEncoder.java +++ b/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/Socks5AddressEncoder.java @@ -29,33 +29,30 @@ import io.netty.util.NetUtil; */ public interface Socks5AddressEncoder { - Socks5AddressEncoder DEFAULT = new Socks5AddressEncoder() { - @Override - public void encodeAddress(Socks5AddressType addrType, String addrValue, ByteBuf out) throws Exception { - final byte typeVal = addrType.byteValue(); - if (typeVal == Socks5AddressType.IPv4.byteValue()) { - if (addrValue != null) { - out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue)); - } else { - out.writeInt(0); - } - } else if (typeVal == Socks5AddressType.DOMAIN.byteValue()) { - if (addrValue != null) { - out.writeByte(addrValue.length()); - out.writeCharSequence(addrValue, CharsetUtil.US_ASCII); - } else { - out.writeByte(0); - } - } else if (typeVal == Socks5AddressType.IPv6.byteValue()) { - if (addrValue != null) { - out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue)); - } else { - out.writeLong(0); - out.writeLong(0); - } + Socks5AddressEncoder DEFAULT = (addrType, addrValue, out) -> { + final byte typeVal = addrType.byteValue(); + if (typeVal == Socks5AddressType.IPv4.byteValue()) { + if (addrValue != null) { + out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue)); } else { - throw new EncoderException("unsupported addrType: " + (addrType.byteValue() & 0xFF)); + out.writeInt(0); } + } else if (typeVal == Socks5AddressType.DOMAIN.byteValue()) { + if (addrValue != null) { + out.writeByte(addrValue.length()); + out.writeCharSequence(addrValue, CharsetUtil.US_ASCII); + } else { + out.writeByte(0); + } + } else if (typeVal == Socks5AddressType.IPv6.byteValue()) { + if (addrValue != null) { + out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue)); + } else { + out.writeLong(0); + out.writeLong(0); + } + } else { + throw new EncoderException("unsupported addrType: " + (addrType.byteValue() & 0xFF)); } }; diff --git a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java index ddf3d9b14f..e34d41ae7d 100644 --- a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java @@ -72,31 +72,28 @@ public abstract class ByteToMessageDecoder extends ChannelInboundHandlerAdapter /** * Cumulate {@link ByteBuf}s by merge them into one {@link ByteBuf}'s, using memory copies. */ - public static final Cumulator MERGE_CUMULATOR = new Cumulator() { - @Override - public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { - try { - final ByteBuf buffer; - if (cumulation.writerIndex() > cumulation.maxCapacity() - in.readableBytes() - || cumulation.refCnt() > 1 || cumulation.isReadOnly()) { - // Expand cumulation (by replace it) when either there is not more room in the buffer - // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or - // duplicate().retain() or if its read-only. - // - // See: - // - https://github.com/netty/netty/issues/2327 - // - https://github.com/netty/netty/issues/1764 - buffer = expandCumulation(alloc, cumulation, in.readableBytes()); - } else { - buffer = cumulation; - } - buffer.writeBytes(in); - return buffer; - } finally { - // We must release in in all cases as otherwise it may produce a leak if writeBytes(...) throw - // for whatever release (for example because of OutOfMemoryError) - in.release(); + public static final Cumulator MERGE_CUMULATOR = (alloc, cumulation, in) -> { + try { + final ByteBuf buffer; + if (cumulation.writerIndex() > cumulation.maxCapacity() - in.readableBytes() + || cumulation.refCnt() > 1 || cumulation.isReadOnly()) { + // Expand cumulation (by replace it) when either there is not more room in the buffer + // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or + // duplicate().retain() or if its read-only. + // + // See: + // - https://github.com/netty/netty/issues/2327 + // - https://github.com/netty/netty/issues/1764 + buffer = expandCumulation(alloc, cumulation, in.readableBytes()); + } else { + buffer = cumulation; } + buffer.writeBytes(in); + return buffer; + } finally { + // We must release in in all cases as otherwise it may produce a leak if writeBytes(...) throw + // for whatever release (for example because of OutOfMemoryError) + in.release(); } }; @@ -105,39 +102,36 @@ public abstract class ByteToMessageDecoder extends ChannelInboundHandlerAdapter * Be aware that {@link CompositeByteBuf} use a more complex indexing implementation so depending on your use-case * and the decoder implementation this may be slower then just use the {@link #MERGE_CUMULATOR}. */ - public static final Cumulator COMPOSITE_CUMULATOR = new Cumulator() { - @Override - public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { - ByteBuf buffer; - try { - if (cumulation.refCnt() > 1) { - // Expand cumulation (by replace it) when the refCnt is greater then 1 which may happen when the - // user use slice().retain() or duplicate().retain(). - // - // See: - // - https://github.com/netty/netty/issues/2327 - // - https://github.com/netty/netty/issues/1764 - buffer = expandCumulation(alloc, cumulation, in.readableBytes()); - buffer.writeBytes(in); + public static final Cumulator COMPOSITE_CUMULATOR = (alloc, cumulation, in) -> { + ByteBuf buffer; + try { + if (cumulation.refCnt() > 1) { + // Expand cumulation (by replace it) when the refCnt is greater then 1 which may happen when the + // user use slice().retain() or duplicate().retain(). + // + // See: + // - https://github.com/netty/netty/issues/2327 + // - https://github.com/netty/netty/issues/1764 + buffer = expandCumulation(alloc, cumulation, in.readableBytes()); + buffer.writeBytes(in); + } else { + CompositeByteBuf composite; + if (cumulation instanceof CompositeByteBuf) { + composite = (CompositeByteBuf) cumulation; } else { - CompositeByteBuf composite; - if (cumulation instanceof CompositeByteBuf) { - composite = (CompositeByteBuf) cumulation; - } else { - composite = alloc.compositeBuffer(Integer.MAX_VALUE); - composite.addComponent(true, cumulation); - } - composite.addComponent(true, in); - in = null; - buffer = composite; - } - return buffer; - } finally { - if (in != null) { - // We must release if the ownership was not transferred as otherwise it may produce a leak if - // writeBytes(...) throw for whatever release (for example because of OutOfMemoryError). - in.release(); + composite = alloc.compositeBuffer(Integer.MAX_VALUE); + composite.addComponent(true, cumulation); } + composite.addComponent(true, in); + in = null; + buffer = composite; + } + return buffer; + } finally { + if (in != null) { + // We must release if the ownership was not transferred as otherwise it may produce a leak if + // writeBytes(...) throw for whatever release (for example because of OutOfMemoryError). + in.release(); } } }; diff --git a/codec/src/main/java/io/netty/handler/codec/CodecOutputList.java b/codec/src/main/java/io/netty/handler/codec/CodecOutputList.java index 5cf161fc69..8e3d976f48 100644 --- a/codec/src/main/java/io/netty/handler/codec/CodecOutputList.java +++ b/codec/src/main/java/io/netty/handler/codec/CodecOutputList.java @@ -28,11 +28,8 @@ import static io.netty.util.internal.ObjectUtil.checkNotNull; */ final class CodecOutputList extends AbstractList implements RandomAccess { - private static final CodecOutputListRecycler NOOP_RECYCLER = new CodecOutputListRecycler() { - @Override - public void recycle(CodecOutputList object) { - // drop on the floor and let the GC handle it. - } + private static final CodecOutputListRecycler NOOP_RECYCLER = object -> { + // drop on the floor and let the GC handle it. }; private static final FastThreadLocal CODEC_OUTPUT_LISTS_POOL = diff --git a/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java b/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java index 3fdc325bdf..e658c66966 100644 --- a/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java +++ b/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java @@ -64,12 +64,7 @@ public class DefaultHeaders> implements Headers void validateName(K name); @SuppressWarnings("rawtypes") - NameValidator NOT_NULL = new NameValidator() { - @Override - public void validateName(Object name) { - checkNotNull(name, "name"); - } - }; + NameValidator NOT_NULL = name -> checkNotNull(name, "name"); } @SuppressWarnings("unchecked") diff --git a/codec/src/main/java/io/netty/handler/codec/MessageAggregator.java b/codec/src/main/java/io/netty/handler/codec/MessageAggregator.java index 2cdb880c99..be26e9de28 100644 --- a/codec/src/main/java/io/netty/handler/codec/MessageAggregator.java +++ b/codec/src/main/java/io/netty/handler/codec/MessageAggregator.java @@ -210,12 +210,9 @@ public abstract class MessageAggregator { + if (!future.isSuccess()) { + ctx.fireExceptionCaught(future.cause()); } }; } diff --git a/codec/src/main/java/io/netty/handler/codec/compression/ByteBufChecksum.java b/codec/src/main/java/io/netty/handler/codec/compression/ByteBufChecksum.java index 3654126754..a4af6ca232 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/ByteBufChecksum.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/ByteBufChecksum.java @@ -42,12 +42,9 @@ abstract class ByteBufChecksum implements Checksum { CRC32_UPDATE_METHOD = updateByteBuffer(new CRC32()); } - private final ByteProcessor updateProcessor = new ByteProcessor() { - @Override - public boolean process(byte value) throws Exception { - update(value); - return true; - } + private final ByteProcessor updateProcessor = value -> { + update(value); + return true; }; private static Method updateByteBuffer(Checksum checksum) { diff --git a/codec/src/main/java/io/netty/handler/codec/compression/Bzip2BlockCompressor.java b/codec/src/main/java/io/netty/handler/codec/compression/Bzip2BlockCompressor.java index de6307f084..e301095bd3 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/Bzip2BlockCompressor.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/Bzip2BlockCompressor.java @@ -33,12 +33,7 @@ import static io.netty.handler.codec.compression.Bzip2Constants.*; * 7. Huffman encode and write data - {@link #close(ByteBuf)} (through {@link Bzip2HuffmanStageEncoder}) */ final class Bzip2BlockCompressor { - private final ByteProcessor writeProcessor = new ByteProcessor() { - @Override - public boolean process(byte value) throws Exception { - return write(value); - } - }; + private final ByteProcessor writeProcessor = this::write; /** * A writer that provides bit-level writes. diff --git a/codec/src/main/java/io/netty/handler/codec/compression/Bzip2Encoder.java b/codec/src/main/java/io/netty/handler/codec/compression/Bzip2Encoder.java index 1282ca295d..bafb3ca047 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/Bzip2Encoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/Bzip2Encoder.java @@ -184,12 +184,9 @@ public class Bzip2Encoder extends MessageToByteEncoder { if (executor.inEventLoop()) { return finishEncode(ctx, promise); } else { - executor.execute(new Runnable() { - @Override - public void run() { - ChannelFuture f = finishEncode(ctx(), promise); - f.addListener(new ChannelPromiseNotifier(promise)); - } + executor.execute(() -> { + ChannelFuture f = finishEncode(ctx(), promise); + f.addListener(new ChannelPromiseNotifier(promise)); }); return promise; } @@ -198,20 +195,12 @@ public class Bzip2Encoder extends MessageToByteEncoder { @Override public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception { ChannelFuture f = finishEncode(ctx, ctx.newPromise()); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture f) throws Exception { - ctx.close(promise); - } - }); + f.addListener((ChannelFutureListener) f1 -> ctx.close(promise)); if (!f.isDone()) { // Ensure the channel is closed even if the write operation completes in time. - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - ctx.close(promise); - } + ctx.executor().schedule(() -> { + ctx.close(promise); }, 10, TimeUnit.SECONDS); // FIXME: Magic number } } diff --git a/codec/src/main/java/io/netty/handler/codec/compression/JZlibEncoder.java b/codec/src/main/java/io/netty/handler/codec/compression/JZlibEncoder.java index 3868bfb868..b1f8c647c9 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/JZlibEncoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/JZlibEncoder.java @@ -252,12 +252,9 @@ public class JZlibEncoder extends ZlibEncoder { return finishEncode(ctx, promise); } else { final ChannelPromise p = ctx.newPromise(); - executor.execute(new Runnable() { - @Override - public void run() { - ChannelFuture f = finishEncode(ctx(), p); - f.addListener(new ChannelPromiseNotifier(promise)); - } + executor.execute(() -> { + ChannelFuture f = finishEncode(ctx(), p); + f.addListener(new ChannelPromiseNotifier(promise)); }); return p; } @@ -342,20 +339,12 @@ public class JZlibEncoder extends ZlibEncoder { final ChannelHandlerContext ctx, final ChannelPromise promise) { ChannelFuture f = finishEncode(ctx, ctx.newPromise()); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture f) throws Exception { - ctx.close(promise); - } - }); + f.addListener((ChannelFutureListener) f1 -> ctx.close(promise)); if (!f.isDone()) { // Ensure the channel is closed even if the write operation completes in time. - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - ctx.close(promise); - } + ctx.executor().schedule(() -> { + ctx.close(promise); }, 10, TimeUnit.SECONDS); // FIXME: Magic number } } diff --git a/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java index 276d7f86b0..38743f19ce 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java @@ -163,12 +163,9 @@ public class JdkZlibEncoder extends ZlibEncoder { return finishEncode(ctx, promise); } else { final ChannelPromise p = ctx.newPromise(); - executor.execute(new Runnable() { - @Override - public void run() { - ChannelFuture f = finishEncode(ctx(), p); - f.addListener(new ChannelPromiseNotifier(promise)); - } + executor.execute(() -> { + ChannelFuture f = finishEncode(ctx(), p); + f.addListener(new ChannelPromiseNotifier(promise)); }); return p; } @@ -262,20 +259,12 @@ public class JdkZlibEncoder extends ZlibEncoder { @Override public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception { ChannelFuture f = finishEncode(ctx, ctx.newPromise()); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture f) throws Exception { - ctx.close(promise); - } - }); + f.addListener((ChannelFutureListener) f1 -> ctx.close(promise)); if (!f.isDone()) { // Ensure the channel is closed even if the write operation completes in time. - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - ctx.close(promise); - } + ctx.executor().schedule(() -> { + ctx.close(promise); }, 10, TimeUnit.SECONDS); // FIXME: Magic number } } diff --git a/codec/src/main/java/io/netty/handler/codec/compression/Lz4FrameEncoder.java b/codec/src/main/java/io/netty/handler/codec/compression/Lz4FrameEncoder.java index b94c893cc6..6204c362e4 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/Lz4FrameEncoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/Lz4FrameEncoder.java @@ -364,12 +364,9 @@ public class Lz4FrameEncoder extends MessageToByteEncoder { if (executor.inEventLoop()) { return finishEncode(ctx, promise); } else { - executor.execute(new Runnable() { - @Override - public void run() { - ChannelFuture f = finishEncode(ctx(), promise); - f.addListener(new ChannelPromiseNotifier(promise)); - } + executor.execute(() -> { + ChannelFuture f = finishEncode(ctx(), promise); + f.addListener(new ChannelPromiseNotifier(promise)); }); return promise; } @@ -378,20 +375,12 @@ public class Lz4FrameEncoder extends MessageToByteEncoder { @Override public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception { ChannelFuture f = finishEncode(ctx, ctx.newPromise()); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture f) throws Exception { - ctx.close(promise); - } - }); + f.addListener((ChannelFutureListener) f1 -> ctx.close(promise)); if (!f.isDone()) { // Ensure the channel is closed even if the write operation completes in time. - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - ctx.close(promise); - } + ctx.executor().schedule(() -> { + ctx.close(promise); }, 10, TimeUnit.SECONDS); // FIXME: Magic number } } diff --git a/codec/src/test/java/io/netty/handler/codec/compression/Lz4FrameEncoderTest.java b/codec/src/test/java/io/netty/handler/codec/compression/Lz4FrameEncoderTest.java index 434a843115..76eaaacbea 100644 --- a/codec/src/test/java/io/netty/handler/codec/compression/Lz4FrameEncoderTest.java +++ b/codec/src/test/java/io/netty/handler/codec/compression/Lz4FrameEncoderTest.java @@ -270,24 +270,18 @@ public class Lz4FrameEncoderTest extends AbstractEncoderTest { clientChannel = bs.connect(serverChannel.localAddress()).syncUninterruptibly().channel(); final Channel finalClientChannel = clientChannel; - clientChannel.eventLoop().execute(new Runnable() { - @Override - public void run() { - finalClientChannel.close(); - final int size = 27; - ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(size, size); - finalClientChannel.writeAndFlush(buf.writerIndex(buf.writerIndex() + size)) - .addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { + clientChannel.eventLoop().execute(() -> { + finalClientChannel.close(); + final int size = 27; + ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(size, size); + finalClientChannel.writeAndFlush(buf.writerIndex(buf.writerIndex() + size)) + .addListener((ChannelFutureListener) future -> { try { writeFailCauseRef.set(future.cause()); } finally { latch.countDown(); } - } - }); - } + }); }); latch.await(); Throwable writeFailCause = writeFailCauseRef.get(); diff --git a/common/src/main/java/io/netty/util/BooleanSupplier.java b/common/src/main/java/io/netty/util/BooleanSupplier.java index 9f6a5ba62a..bc44931fc8 100644 --- a/common/src/main/java/io/netty/util/BooleanSupplier.java +++ b/common/src/main/java/io/netty/util/BooleanSupplier.java @@ -29,20 +29,10 @@ public interface BooleanSupplier { /** * A supplier which always returns {@code false} and never throws. */ - BooleanSupplier FALSE_SUPPLIER = new BooleanSupplier() { - @Override - public boolean get() { - return false; - } - }; + BooleanSupplier FALSE_SUPPLIER = () -> false; /** * A supplier which always returns {@code true} and never throws. */ - BooleanSupplier TRUE_SUPPLIER = new BooleanSupplier() { - @Override - public boolean get() { - return true; - } - }; + BooleanSupplier TRUE_SUPPLIER = () -> true; } diff --git a/common/src/main/java/io/netty/util/ByteProcessor.java b/common/src/main/java/io/netty/util/ByteProcessor.java index 31cd6ff824..3dcac9d59d 100644 --- a/common/src/main/java/io/netty/util/ByteProcessor.java +++ b/common/src/main/java/io/netty/util/ByteProcessor.java @@ -103,42 +103,22 @@ public interface ByteProcessor { /** * Aborts on a {@code CR ('\r')} or a {@code LF ('\n')}. */ - ByteProcessor FIND_CRLF = new ByteProcessor() { - @Override - public boolean process(byte value) { - return value != CARRIAGE_RETURN && value != LINE_FEED; - } - }; + ByteProcessor FIND_CRLF = value -> value != CARRIAGE_RETURN && value != LINE_FEED; /** * Aborts on a byte which is neither a {@code CR ('\r')} nor a {@code LF ('\n')}. */ - ByteProcessor FIND_NON_CRLF = new ByteProcessor() { - @Override - public boolean process(byte value) { - return value == CARRIAGE_RETURN || value == LINE_FEED; - } - }; + ByteProcessor FIND_NON_CRLF = value -> value == CARRIAGE_RETURN || value == LINE_FEED; /** * Aborts on a linear whitespace (a ({@code ' '} or a {@code '\t'}). */ - ByteProcessor FIND_LINEAR_WHITESPACE = new ByteProcessor() { - @Override - public boolean process(byte value) { - return value != SPACE && value != HTAB; - } - }; + ByteProcessor FIND_LINEAR_WHITESPACE = value -> value != SPACE && value != HTAB; /** * Aborts on a byte which is not a linear whitespace (neither {@code ' '} nor {@code '\t'}). */ - ByteProcessor FIND_NON_LINEAR_WHITESPACE = new ByteProcessor() { - @Override - public boolean process(byte value) { - return value == SPACE || value == HTAB; - } - }; + ByteProcessor FIND_NON_LINEAR_WHITESPACE = value -> value == SPACE || value == HTAB; /** * @return {@code true} if the processor wants to continue the loop and handle the next byte in the buffer. diff --git a/common/src/main/java/io/netty/util/NetUtil.java b/common/src/main/java/io/netty/util/NetUtil.java index ba25a78396..d17a605326 100644 --- a/common/src/main/java/io/netty/util/NetUtil.java +++ b/common/src/main/java/io/netty/util/NetUtil.java @@ -250,59 +250,56 @@ public final class NetUtil { // As a SecurityManager may prevent reading the somaxconn file we wrap this in a privileged block. // // See https://github.com/netty/netty/issues/3680 - SOMAXCONN = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Integer run() { - // Determine the default somaxconn (server socket backlog) value of the platform. - // The known defaults: - // - Windows NT Server 4.0+: 200 - // - Linux and Mac OS X: 128 - int somaxconn = PlatformDependent.isWindows() ? 200 : 128; - File file = new File("/proc/sys/net/core/somaxconn"); - BufferedReader in = null; - try { - // file.exists() may throw a SecurityException if a SecurityManager is used, so execute it in the - // try / catch block. - // See https://github.com/netty/netty/issues/4936 - if (file.exists()) { - in = new BufferedReader(new FileReader(file)); - somaxconn = Integer.parseInt(in.readLine()); - if (logger.isDebugEnabled()) { - logger.debug("{}: {}", file, somaxconn); - } - } else { - // Try to get from sysctl - Integer tmp = null; - if (SystemPropertyUtil.getBoolean("io.netty.net.somaxconn.trySysctl", false)) { - tmp = sysctlGetInt("kern.ipc.somaxconn"); - if (tmp == null) { - tmp = sysctlGetInt("kern.ipc.soacceptqueue"); - if (tmp != null) { - somaxconn = tmp; - } - } else { + SOMAXCONN = AccessController.doPrivileged((PrivilegedAction) () -> { + // Determine the default somaxconn (server socket backlog) value of the platform. + // The known defaults: + // - Windows NT Server 4.0+: 200 + // - Linux and Mac OS X: 128 + int somaxconn = PlatformDependent.isWindows() ? 200 : 128; + File file = new File("/proc/sys/net/core/somaxconn"); + BufferedReader in = null; + try { + // file.exists() may throw a SecurityException if a SecurityManager is used, so execute it in the + // try / catch block. + // See https://github.com/netty/netty/issues/4936 + if (file.exists()) { + in = new BufferedReader(new FileReader(file)); + somaxconn = Integer.parseInt(in.readLine()); + if (logger.isDebugEnabled()) { + logger.debug("{}: {}", file, somaxconn); + } + } else { + // Try to get from sysctl + Integer tmp = null; + if (SystemPropertyUtil.getBoolean("io.netty.net.somaxconn.trySysctl", false)) { + tmp = sysctlGetInt("kern.ipc.somaxconn"); + if (tmp == null) { + tmp = sysctlGetInt("kern.ipc.soacceptqueue"); + if (tmp != null) { somaxconn = tmp; } - } - - if (tmp == null) { - logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file, - somaxconn); + } else { + somaxconn = tmp; } } - } catch (Exception e) { - logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file, somaxconn, e); - } finally { - if (in != null) { - try { - in.close(); - } catch (Exception e) { - // Ignored. - } + + if (tmp == null) { + logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file, + somaxconn); + } + } + } catch (Exception e) { + logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file, somaxconn, e); + } finally { + if (in != null) { + try { + in.close(); + } catch (Exception e) { + // Ignored. } } - return somaxconn; } + return somaxconn; }); } diff --git a/common/src/main/java/io/netty/util/Recycler.java b/common/src/main/java/io/netty/util/Recycler.java index 2bf8642502..8e5f87dfe1 100644 --- a/common/src/main/java/io/netty/util/Recycler.java +++ b/common/src/main/java/io/netty/util/Recycler.java @@ -41,11 +41,8 @@ public abstract class Recycler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(Recycler.class); @SuppressWarnings("rawtypes") - private static final Handle NOOP_HANDLE = new Handle() { - @Override - public void recycle(Object object) { - // NOOP - } + private static final Handle NOOP_HANDLE = object -> { + // NOOP }; private static final AtomicInteger ID_GENERATOR = new AtomicInteger(Integer.MIN_VALUE); private static final int OWN_THREAD_ID = ID_GENERATOR.getAndIncrement(); diff --git a/common/src/main/java/io/netty/util/ResourceLeakDetectorFactory.java b/common/src/main/java/io/netty/util/ResourceLeakDetectorFactory.java index 2290477bdb..c69ac8f7dd 100644 --- a/common/src/main/java/io/netty/util/ResourceLeakDetectorFactory.java +++ b/common/src/main/java/io/netty/util/ResourceLeakDetectorFactory.java @@ -103,12 +103,8 @@ public abstract class ResourceLeakDetectorFactory { DefaultResourceLeakDetectorFactory() { String customLeakDetector; try { - customLeakDetector = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public String run() { - return SystemPropertyUtil.get("io.netty.customResourceLeakDetector"); - } - }); + customLeakDetector = AccessController.doPrivileged((PrivilegedAction) () -> + SystemPropertyUtil.get("io.netty.customResourceLeakDetector")); } catch (Throwable cause) { logger.error("Could not access System property: io.netty.customResourceLeakDetector", cause); customLeakDetector = null; diff --git a/common/src/main/java/io/netty/util/ThreadDeathWatcher.java b/common/src/main/java/io/netty/util/ThreadDeathWatcher.java index d0579715c0..1d09d35a63 100644 --- a/common/src/main/java/io/netty/util/ThreadDeathWatcher.java +++ b/common/src/main/java/io/netty/util/ThreadDeathWatcher.java @@ -114,12 +114,9 @@ public final class ThreadDeathWatcher { // See: // - https://github.com/netty/netty/issues/7290 // - https://bugs.openjdk.java.net/browse/JDK-7008595 - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - watcherThread.setContextClassLoader(null); - return null; - } + AccessController.doPrivileged((PrivilegedAction) () -> { + watcherThread.setContextClassLoader(null); + return null; }); watcherThread.start(); diff --git a/common/src/main/java/io/netty/util/UncheckedBooleanSupplier.java b/common/src/main/java/io/netty/util/UncheckedBooleanSupplier.java index 57be6de747..b768c3c405 100644 --- a/common/src/main/java/io/netty/util/UncheckedBooleanSupplier.java +++ b/common/src/main/java/io/netty/util/UncheckedBooleanSupplier.java @@ -29,20 +29,10 @@ public interface UncheckedBooleanSupplier extends BooleanSupplier { /** * A supplier which always returns {@code false} and never throws. */ - UncheckedBooleanSupplier FALSE_SUPPLIER = new UncheckedBooleanSupplier() { - @Override - public boolean get() { - return false; - } - }; + UncheckedBooleanSupplier FALSE_SUPPLIER = () -> false; /** * A supplier which always returns {@code true} and never throws. */ - UncheckedBooleanSupplier TRUE_SUPPLIER = new UncheckedBooleanSupplier() { - @Override - public boolean get() { - return true; - } - }; + UncheckedBooleanSupplier TRUE_SUPPLIER = () -> true; } diff --git a/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java index 90b118c6c9..dbb2b1e76f 100644 --- a/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java @@ -36,12 +36,7 @@ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecut static final long START_TIME = System.nanoTime(); private static final Comparator> SCHEDULED_FUTURE_TASK_COMPARATOR = - new Comparator>() { - @Override - public int compare(RunnableScheduledFutureNode o1, RunnableScheduledFutureNode o2) { - return o1.compareTo(o2); - } - }; + Comparable::compareTo; private PriorityQueue> scheduledTaskQueue; @@ -234,12 +229,7 @@ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecut if (inEventLoop()) { add0(task); } else { - execute(new Runnable() { - @Override - public void run() { - add0(task); - } - }); + execute(() -> add0(task)); } return task; } @@ -258,12 +248,7 @@ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecut if (inEventLoop()) { scheduledTaskQueue().removeTyped(task); } else { - execute(new Runnable() { - @Override - public void run() { - removeScheduled(task); - } - }); + execute(() -> removeScheduled(task)); } } diff --git a/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java b/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java index a910e408c1..9cfbc97629 100644 --- a/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java +++ b/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java @@ -429,12 +429,7 @@ public class DefaultPromise extends AbstractFuture implements Promise { } } - safeExecute(executor, new Runnable() { - @Override - public void run() { - notifyListenersNow(); - } - }); + safeExecute(executor, this::notifyListenersNow); } /** @@ -459,12 +454,7 @@ public class DefaultPromise extends AbstractFuture implements Promise { } } - safeExecute(executor, new Runnable() { - @Override - public void run() { - notifyListener0(future, listener); - } - }); + safeExecute(executor, () -> notifyListener0(future, listener)); } private void notifyListenersNow() { @@ -662,21 +652,11 @@ public class DefaultPromise extends AbstractFuture implements Promise { if (listeners instanceof GenericProgressiveFutureListener[]) { final GenericProgressiveFutureListener[] array = (GenericProgressiveFutureListener[]) listeners; - safeExecute(executor, new Runnable() { - @Override - public void run() { - notifyProgressiveListeners0(self, array, progress, total); - } - }); + safeExecute(executor, () -> notifyProgressiveListeners0(self, array, progress, total)); } else { final GenericProgressiveFutureListener> l = (GenericProgressiveFutureListener>) listeners; - safeExecute(executor, new Runnable() { - @Override - public void run() { - notifyProgressiveListener0(self, l, progress, total); - } - }); + safeExecute(executor, () -> notifyProgressiveListener0(self, l, progress, total)); } } } diff --git a/common/src/main/java/io/netty/util/concurrent/GlobalEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/GlobalEventExecutor.java index 3b29d80fc7..f8a2b13fa9 100644 --- a/common/src/main/java/io/netty/util/concurrent/GlobalEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/GlobalEventExecutor.java @@ -46,12 +46,9 @@ public final class GlobalEventExecutor extends AbstractScheduledEventExecutor { static { INSTANCE = new GlobalEventExecutor(); QUIET_PERIOD_TASK = new RunnableScheduledFutureAdapter<>( - INSTANCE, INSTANCE.newPromise(), Executors.callable(new Runnable() { - @Override - public void run() { - // NOOP - } - }, null), deadlineNanos(SCHEDULE_QUIET_PERIOD_INTERVAL), -SCHEDULE_QUIET_PERIOD_INTERVAL); + INSTANCE, INSTANCE.newPromise(), Executors.callable(() -> { + // NOOP + }, null), deadlineNanos(SCHEDULE_QUIET_PERIOD_INTERVAL), -SCHEDULE_QUIET_PERIOD_INTERVAL); INSTANCE.scheduledTaskQueue().add(QUIET_PERIOD_TASK); } @@ -228,12 +225,9 @@ public final class GlobalEventExecutor extends AbstractScheduledEventExecutor { // See: // - https://github.com/netty/netty/issues/7290 // - https://bugs.openjdk.java.net/browse/JDK-7008595 - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - t.setContextClassLoader(null); - return null; - } + AccessController.doPrivileged((PrivilegedAction) () -> { + t.setContextClassLoader(null); + return null; }); // Set the thread before starting it as otherwise inEventLoop() may return false and so produce diff --git a/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java b/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java index 0f9f4a985d..df689c1650 100644 --- a/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java +++ b/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java @@ -154,12 +154,9 @@ public class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup { } } - final FutureListener terminationListener = new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - if (terminatedChildren.incrementAndGet() == children.length) { - terminationFuture.setSuccess(null); - } + final FutureListener terminationListener = future -> { + if (terminatedChildren.incrementAndGet() == children.length) { + terminationFuture.setSuccess(null); } }; diff --git a/common/src/main/java/io/netty/util/concurrent/RejectedExecutionHandlers.java b/common/src/main/java/io/netty/util/concurrent/RejectedExecutionHandlers.java index 7338cdd22c..c072af3dbe 100644 --- a/common/src/main/java/io/netty/util/concurrent/RejectedExecutionHandlers.java +++ b/common/src/main/java/io/netty/util/concurrent/RejectedExecutionHandlers.java @@ -25,11 +25,8 @@ import java.util.concurrent.locks.LockSupport; * Expose helper methods which create different {@link RejectedExecutionHandler}s. */ public final class RejectedExecutionHandlers { - private static final RejectedExecutionHandler REJECT = new RejectedExecutionHandler() { - @Override - public void rejected(Runnable task, SingleThreadEventExecutor executor) { - throw new RejectedExecutionException(); - } + private static final RejectedExecutionHandler REJECT = (task, executor) -> { + throw new RejectedExecutionException(); }; private RejectedExecutionHandlers() { } @@ -49,24 +46,21 @@ public final class RejectedExecutionHandlers { public static RejectedExecutionHandler backoff(final int retries, long backoffAmount, TimeUnit unit) { ObjectUtil.checkPositive(retries, "retries"); final long backOffNanos = unit.toNanos(backoffAmount); - return new RejectedExecutionHandler() { - @Override - public void rejected(Runnable task, SingleThreadEventExecutor executor) { - if (!executor.inEventLoop()) { - for (int i = 0; i < retries; i++) { - // Try to wake up the executor so it will empty its task queue. - executor.wakeup(false); + return (task, executor) -> { + if (!executor.inEventLoop()) { + for (int i = 0; i < retries; i++) { + // Try to wake up the executor so it will empty its task queue. + executor.wakeup(false); - LockSupport.parkNanos(backOffNanos); - if (executor.offerTask(task)) { - return; - } + LockSupport.parkNanos(backOffNanos); + if (executor.offerTask(task)) { + return; } } - // Either we tried to add the task from within the EventLoop or we was not able to add it even with - // backoff. - throw new RejectedExecutionException(); } + // Either we tried to add the task from within the EventLoop or we was not able to add it even with + // backoff. + throw new RejectedExecutionException(); }; } } diff --git a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java index 2554b94685..870e771bac 100644 --- a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java @@ -59,17 +59,11 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im private static final int ST_SHUTDOWN = 4; private static final int ST_TERMINATED = 5; - private static final Runnable WAKEUP_TASK = new Runnable() { - @Override - public void run() { - // Do nothing. - } + private static final Runnable WAKEUP_TASK = () -> { + // Do nothing. }; - private static final Runnable NOOP_TASK = new Runnable() { - @Override - public void run() { - // Do nothing. - } + private static final Runnable NOOP_TASK = () -> { + // Do nothing. }; private static final AtomicIntegerFieldUpdater STATE_UPDATER = @@ -467,12 +461,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im if (inEventLoop()) { shutdownHooks.add(task); } else { - execute(new Runnable() { - @Override - public void run() { - shutdownHooks.add(task); - } - }); + execute(() -> shutdownHooks.add(task)); } } @@ -483,12 +472,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im if (inEventLoop()) { shutdownHooks.remove(task); } else { - execute(new Runnable() { - @Override - public void run() { - shutdownHooks.remove(task); - } - }); + execute(() -> shutdownHooks.remove(task)); } } @@ -854,66 +838,63 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im private void doStartThread() { assert thread == null; - executor.execute(new Runnable() { - @Override - public void run() { - thread = Thread.currentThread(); - if (interrupted) { - thread.interrupt(); + executor.execute(() -> { + thread = Thread.currentThread(); + if (interrupted) { + thread.interrupt(); + } + + boolean success = false; + updateLastExecutionTime(); + try { + SingleThreadEventExecutor.this.run(); + success = true; + } catch (Throwable t) { + logger.warn("Unexpected exception from an event executor: ", t); + } finally { + for (;;) { + int oldState = state; + if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet( + SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) { + break; + } + } + + // Check if confirmShutdown() was called at the end of the loop. + if (success && gracefulShutdownStartTime == 0) { + if (logger.isErrorEnabled()) { + logger.error("Buggy " + EventExecutor.class.getSimpleName() + " implementation; " + + SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must " + + "be called before run() implementation terminates."); + } } - boolean success = false; - updateLastExecutionTime(); try { - SingleThreadEventExecutor.this.run(); - success = true; - } catch (Throwable t) { - logger.warn("Unexpected exception from an event executor: ", t); - } finally { + // Run all remaining tasks and shutdown hooks. for (;;) { - int oldState = state; - if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet( - SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) { + if (confirmShutdown()) { break; } } - - // Check if confirmShutdown() was called at the end of the loop. - if (success && gracefulShutdownStartTime == 0) { - if (logger.isErrorEnabled()) { - logger.error("Buggy " + EventExecutor.class.getSimpleName() + " implementation; " + - SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must " + - "be called before run() implementation terminates."); - } - } - + } finally { try { - // Run all remaining tasks and shutdown hooks. - for (;;) { - if (confirmShutdown()) { - break; - } - } + cleanup(); } finally { - try { - cleanup(); - } finally { - // Lets remove all FastThreadLocals for the Thread as we are about to terminate and notify - // the future. The user may block on the future and once it unblocks the JVM may terminate - // and start unloading classes. - // See https://github.com/netty/netty/issues/6596. - FastThreadLocal.removeAll(); + // Lets remove all FastThreadLocals for the Thread as we are about to terminate and notify + // the future. The user may block on the future and once it unblocks the JVM may terminate + // and start unloading classes. + // See https://github.com/netty/netty/issues/6596. + FastThreadLocal.removeAll(); - STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED); - threadLock.release(); - if (!taskQueue.isEmpty()) { - if (logger.isWarnEnabled()) { - logger.warn("An event executor terminated with " + - "non-empty task queue (" + taskQueue.size() + ')'); - } + STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED); + threadLock.release(); + if (!taskQueue.isEmpty()) { + if (logger.isWarnEnabled()) { + logger.warn("An event executor terminated with " + + "non-empty task queue (" + taskQueue.size() + ')'); } - terminationFuture.setSuccess(null); } + terminationFuture.setSuccess(null); } } } diff --git a/common/src/main/java/io/netty/util/internal/CleanerJava6.java b/common/src/main/java/io/netty/util/internal/CleanerJava6.java index 3835823603..41bf58a99e 100644 --- a/common/src/main/java/io/netty/util/internal/CleanerJava6.java +++ b/common/src/main/java/io/netty/util/internal/CleanerJava6.java @@ -45,20 +45,17 @@ final class CleanerJava6 implements Cleaner { Throwable error = null; final ByteBuffer direct = ByteBuffer.allocateDirect(1); try { - Object mayBeCleanerField = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - Field cleanerField = direct.getClass().getDeclaredField("cleaner"); - if (!PlatformDependent.hasUnsafe()) { - // We need to make it accessible if we do not use Unsafe as we will access it via - // reflection. - cleanerField.setAccessible(true); - } - return cleanerField; - } catch (Throwable cause) { - return cause; + Object mayBeCleanerField = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + Field cleanerField1 = direct.getClass().getDeclaredField("cleaner"); + if (!PlatformDependent.hasUnsafe()) { + // We need to make it accessible if we do not use Unsafe as we will access it via + // reflection. + cleanerField1.setAccessible(true); } + return cleanerField1; + } catch (Throwable cause) { + return cause; } }); if (mayBeCleanerField instanceof Throwable) { @@ -119,15 +116,12 @@ final class CleanerJava6 implements Cleaner { } private static void freeDirectBufferPrivileged(final ByteBuffer buffer) { - Throwable cause = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Throwable run() { - try { - freeDirectBuffer0(buffer); - return null; - } catch (Throwable cause) { - return cause; - } + Throwable cause = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + freeDirectBuffer0(buffer); + return null; + } catch (Throwable cause1) { + return cause1; } }); if (cause != null) { diff --git a/common/src/main/java/io/netty/util/internal/CleanerJava9.java b/common/src/main/java/io/netty/util/internal/CleanerJava9.java index 12421b1576..3c4b5cd8b3 100644 --- a/common/src/main/java/io/netty/util/internal/CleanerJava9.java +++ b/common/src/main/java/io/netty/util/internal/CleanerJava9.java @@ -37,18 +37,15 @@ final class CleanerJava9 implements Cleaner { final Throwable error; if (PlatformDependent0.hasUnsafe()) { final ByteBuffer buffer = ByteBuffer.allocateDirect(1); - Object maybeInvokeMethod = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - // See https://bugs.openjdk.java.net/browse/JDK-8171377 - Method m = PlatformDependent0.UNSAFE.getClass().getDeclaredMethod( - "invokeCleaner", ByteBuffer.class); - m.invoke(PlatformDependent0.UNSAFE, buffer); - return m; - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - return e; - } + Object maybeInvokeMethod = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + // See https://bugs.openjdk.java.net/browse/JDK-8171377 + Method m = PlatformDependent0.UNSAFE.getClass().getDeclaredMethod( + "invokeCleaner", ByteBuffer.class); + m.invoke(PlatformDependent0.UNSAFE, buffer); + return m; + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + return e; } }); @@ -91,16 +88,13 @@ final class CleanerJava9 implements Cleaner { } private static void freeDirectBufferPrivileged(final ByteBuffer buffer) { - Exception error = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Exception run() { - try { - INVOKE_CLEANER.invoke(PlatformDependent0.UNSAFE, buffer); - } catch (InvocationTargetException | IllegalAccessException e) { - return e; - } - return null; + Exception error = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + INVOKE_CLEANER.invoke(PlatformDependent0.UNSAFE, buffer); + } catch (InvocationTargetException | IllegalAccessException e) { + return e; } + return null; }); if (error != null) { PlatformDependent0.throwException(error); diff --git a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java index 1d02d5c26d..0b3b29e17c 100644 --- a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java +++ b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java @@ -322,18 +322,15 @@ public final class NativeLibraryLoader { private static void loadLibraryByHelper(final Class helper, final String name, final boolean absolute) throws UnsatisfiedLinkError { - Object ret = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - // Invoke the helper to load the native library, if succeed, then the native - // library belong to the specified ClassLoader. - Method method = helper.getMethod("loadLibrary", String.class, boolean.class); - method.setAccessible(true); - return method.invoke(null, name, absolute); - } catch (Exception e) { - return e; - } + Object ret = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + // Invoke the helper to load the native library, if succeed, then the native + // library belong to the specified ClassLoader. + Method method = helper.getMethod("loadLibrary", String.class, boolean.class); + method.setAccessible(true); + return method.invoke(null, name, absolute); + } catch (Exception e) { + return e; } }); if (ret instanceof Throwable) { @@ -368,20 +365,17 @@ public final class NativeLibraryLoader { try { // The helper class is NOT found in target ClassLoader, we have to define the helper class. final byte[] classBinary = classToByteArray(helper); - return AccessController.doPrivileged(new PrivilegedAction>() { - @Override - public Class run() { - try { - // Define the helper class in the target ClassLoader, - // then we can call the helper to load the native library. - Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, - byte[].class, int.class, int.class); - defineClass.setAccessible(true); - return (Class) defineClass.invoke(loader, helper.getName(), classBinary, 0, - classBinary.length); - } catch (Exception e) { - throw new IllegalStateException("Define class failed!", e); - } + return AccessController.doPrivileged((PrivilegedAction>) () -> { + try { + // Define the helper class in the target ClassLoader, + // then we can call the helper to load the native library. + Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, + byte[].class, int.class, int.class); + defineClass.setAccessible(true); + return (Class) defineClass.invoke(loader, helper.getName(), classBinary, 0, + classBinary.length); + } catch (Exception e) { + throw new IllegalStateException("Define class failed!", e); } }); } catch (ClassNotFoundException | Error | RuntimeException e2) { diff --git a/common/src/main/java/io/netty/util/internal/ObjectCleaner.java b/common/src/main/java/io/netty/util/internal/ObjectCleaner.java index a4cbbfa7cb..96b606e8ec 100644 --- a/common/src/main/java/io/netty/util/internal/ObjectCleaner.java +++ b/common/src/main/java/io/netty/util/internal/ObjectCleaner.java @@ -42,47 +42,44 @@ public final class ObjectCleaner { private static final Set LIVE_SET = ConcurrentHashMap.newKeySet(); private static final ReferenceQueue REFERENCE_QUEUE = new ReferenceQueue<>(); private static final AtomicBoolean CLEANER_RUNNING = new AtomicBoolean(false); - private static final Runnable CLEANER_TASK = new Runnable() { - @Override - public void run() { - boolean interrupted = false; - for (;;) { - // Keep on processing as long as the LIVE_SET is not empty and once it becomes empty - // See if we can let this thread complete. - while (!LIVE_SET.isEmpty()) { - final AutomaticCleanerReference reference; + private static final Runnable CLEANER_TASK = () -> { + boolean interrupted = false; + for (;;) { + // Keep on processing as long as the LIVE_SET is not empty and once it becomes empty + // See if we can let this thread complete. + while (!LIVE_SET.isEmpty()) { + final AutomaticCleanerReference reference; + try { + reference = (AutomaticCleanerReference) REFERENCE_QUEUE.remove(REFERENCE_QUEUE_POLL_TIMEOUT_MS); + } catch (InterruptedException ex) { + // Just consume and move on + interrupted = true; + continue; + } + if (reference != null) { try { - reference = (AutomaticCleanerReference) REFERENCE_QUEUE.remove(REFERENCE_QUEUE_POLL_TIMEOUT_MS); - } catch (InterruptedException ex) { - // Just consume and move on - interrupted = true; - continue; - } - if (reference != null) { - try { - reference.cleanup(); - } catch (Throwable ignored) { - // ignore exceptions, and don't log in case the logger throws an exception, blocks, or has - // other unexpected side effects. - } - LIVE_SET.remove(reference); + reference.cleanup(); + } catch (Throwable ignored) { + // ignore exceptions, and don't log in case the logger throws an exception, blocks, or has + // other unexpected side effects. } + LIVE_SET.remove(reference); } - CLEANER_RUNNING.set(false); + } + CLEANER_RUNNING.set(false); - // Its important to first access the LIVE_SET and then CLEANER_RUNNING to ensure correct - // behavior in multi-threaded environments. - if (LIVE_SET.isEmpty() || !CLEANER_RUNNING.compareAndSet(false, true)) { - // There was nothing added after we set STARTED to false or some other cleanup Thread - // was started already so its safe to let this Thread complete now. - break; - } - } - if (interrupted) { - // As we caught the InterruptedException above we should mark the Thread as interrupted. - Thread.currentThread().interrupt(); + // Its important to first access the LIVE_SET and then CLEANER_RUNNING to ensure correct + // behavior in multi-threaded environments. + if (LIVE_SET.isEmpty() || !CLEANER_RUNNING.compareAndSet(false, true)) { + // There was nothing added after we set STARTED to false or some other cleanup Thread + // was started already so its safe to let this Thread complete now. + break; } } + if (interrupted) { + // As we caught the InterruptedException above we should mark the Thread as interrupted. + Thread.currentThread().interrupt(); + } }; /** @@ -108,12 +105,9 @@ public final class ObjectCleaner { // See: // - https://github.com/netty/netty/issues/7290 // - https://bugs.openjdk.java.net/browse/JDK-7008595 - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - cleanupThread.setContextClassLoader(null); - return null; - } + AccessController.doPrivileged((PrivilegedAction) () -> { + cleanupThread.setContextClassLoader(null); + return null; }); cleanupThread.setName(CLEANER_THREAD_NAME); diff --git a/common/src/main/java/io/netty/util/internal/PlatformDependent.java b/common/src/main/java/io/netty/util/internal/PlatformDependent.java index 0973c2095b..a63b250ec4 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent.java @@ -99,11 +99,8 @@ public final class PlatformDependent { public static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; - private static final Cleaner NOOP = new Cleaner() { - @Override - public void freeDirectBuffer(ByteBuffer buffer) { - // NOOP - } + private static final Cleaner NOOP = buffer -> { + // NOOP }; static { @@ -775,12 +772,9 @@ public final class PlatformDependent { // jctools goes through its own process of initializing unsafe; of // course, this requires permissions which might not be granted to calling code, so we // must mark this block as privileged too - unsafe = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - // force JCTools to initialize unsafe - return UnsafeAccess.UNSAFE; - } + unsafe = AccessController.doPrivileged((PrivilegedAction) () -> { + // force JCTools to initialize unsafe + return UnsafeAccess.UNSAFE; }); } diff --git a/common/src/main/java/io/netty/util/internal/PlatformDependent0.java b/common/src/main/java/io/netty/util/internal/PlatformDependent0.java index 059f5376cb..b90f47612f 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent0.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent0.java @@ -80,25 +80,22 @@ final class PlatformDependent0 { direct = ByteBuffer.allocateDirect(1); // attempt to access field Unsafe#theUnsafe - final Object maybeUnsafe = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe"); - // We always want to try using Unsafe as the access still works on java9 as well and - // we need it for out native-transports and many optimizations. - Throwable cause = ReflectionUtil.trySetAccessible(unsafeField, false); - if (cause != null) { - return cause; - } - // the unsafe instance - return unsafeField.get(null); - } catch (NoSuchFieldException | SecurityException - | IllegalAccessException | NoClassDefFoundError e) { - return e; - } // Also catch NoClassDefFoundError in case someone uses for example OSGI and it made - // Unsafe unloadable. - } + final Object maybeUnsafe = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe"); + // We always want to try using Unsafe as the access still works on java9 as well and + // we need it for out native-transports and many optimizations. + Throwable cause = ReflectionUtil.trySetAccessible(unsafeField, false); + if (cause != null) { + return cause; + } + // the unsafe instance + return unsafeField.get(null); + } catch (NoSuchFieldException | SecurityException + | IllegalAccessException | NoClassDefFoundError e) { + return e; + } // Also catch NoClassDefFoundError in case someone uses for example OSGI and it made + // Unsafe unloadable. }); // the conditional check here can not be replaced with checking that maybeUnsafe @@ -119,16 +116,13 @@ final class PlatformDependent0 { // http://www.mail-archive.com/jdk6-dev@openjdk.java.net/msg00698.html if (unsafe != null) { final Unsafe finalUnsafe = unsafe; - final Object maybeException = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - finalUnsafe.getClass().getDeclaredMethod( - "copyMemory", Object.class, long.class, Object.class, long.class, long.class); - return null; - } catch (NoSuchMethodException | SecurityException e) { - return e; - } + final Object maybeException = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + finalUnsafe.getClass().getDeclaredMethod( + "copyMemory", Object.class, long.class, Object.class, long.class, long.class); + return null; + } catch (NoSuchMethodException | SecurityException e) { + return e; } }); @@ -146,24 +140,21 @@ final class PlatformDependent0 { final Unsafe finalUnsafe = unsafe; // attempt to access field Buffer#address - final Object maybeAddressField = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - final Field field = Buffer.class.getDeclaredField("address"); - // Use Unsafe to read value of the address field. This way it will not fail on JDK9+ which - // will forbid changing the access level via reflection. - final long offset = finalUnsafe.objectFieldOffset(field); - final long address = finalUnsafe.getLong(direct, offset); + final Object maybeAddressField = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + final Field field = Buffer.class.getDeclaredField("address"); + // Use Unsafe to read value of the address field. This way it will not fail on JDK9+ which + // will forbid changing the access level via reflection. + final long offset = finalUnsafe.objectFieldOffset(field); + final long address = finalUnsafe.getLong(direct, offset); - // if direct really is a direct buffer, address will be non-zero - if (address == 0) { - return null; - } - return field; - } catch (NoSuchFieldException | SecurityException e) { - return e; + // if direct really is a direct buffer, address will be non-zero + if (address == 0) { + return null; } + return field; + } catch (NoSuchFieldException | SecurityException e) { + return e; } }); @@ -205,20 +196,17 @@ final class PlatformDependent0 { long address = -1; try { final Object maybeDirectBufferConstructor = - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - final Constructor constructor = - direct.getClass().getDeclaredConstructor(long.class, int.class); - Throwable cause = ReflectionUtil.trySetAccessible(constructor, true); - if (cause != null) { - return cause; - } - return constructor; - } catch (NoSuchMethodException | SecurityException e) { - return e; + AccessController.doPrivileged((PrivilegedAction) () -> { + try { + final Constructor constructor = + direct.getClass().getDeclaredConstructor(long.class, int.class); + Throwable cause = ReflectionUtil.trySetAccessible(constructor, true); + if (cause != null) { + return cause; } + return constructor; + } catch (NoSuchMethodException | SecurityException e) { + return e; } }); @@ -299,33 +287,27 @@ final class PlatformDependent0 { UNALIGNED = unaligned; if (javaVersion() >= 9) { - Object maybeException = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - // Java9 has jdk.internal.misc.Unsafe and not all methods are propagated to - // sun.misc.Unsafe - Class internalUnsafeClass = getClassLoader(PlatformDependent0.class) - .loadClass("jdk.internal.misc.Unsafe"); - Method method = internalUnsafeClass.getDeclaredMethod("getUnsafe"); - return method.invoke(null); - } catch (Throwable e) { - return e; - } + Object maybeException = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + // Java9 has jdk.internal.misc.Unsafe and not all methods are propagated to + // sun.misc.Unsafe + Class internalUnsafeClass = getClassLoader(PlatformDependent0.class) + .loadClass("jdk.internal.misc.Unsafe"); + Method method = internalUnsafeClass.getDeclaredMethod("getUnsafe"); + return method.invoke(null); + } catch (Throwable e) { + return e; } }); if (!(maybeException instanceof Throwable)) { internalUnsafe = maybeException; final Object finalInternalUnsafe = internalUnsafe; - maybeException = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - return finalInternalUnsafe.getClass().getDeclaredMethod( - "allocateUninitializedArray", Class.class, int.class); - } catch (NoSuchMethodException | SecurityException e) { - return e; - } + maybeException = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + return finalInternalUnsafe.getClass().getDeclaredMethod( + "allocateUninitializedArray", Class.class, int.class); + } catch (NoSuchMethodException | SecurityException e) { + return e; } }); @@ -746,12 +728,7 @@ final class PlatformDependent0 { if (System.getSecurityManager() == null) { return clazz.getClassLoader(); } else { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return clazz.getClassLoader(); - } - }); + return AccessController.doPrivileged((PrivilegedAction) clazz::getClassLoader); } } @@ -759,12 +736,8 @@ final class PlatformDependent0 { if (System.getSecurityManager() == null) { return Thread.currentThread().getContextClassLoader(); } else { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - }); + return AccessController.doPrivileged((PrivilegedAction) () -> + Thread.currentThread().getContextClassLoader()); } } @@ -772,12 +745,7 @@ final class PlatformDependent0 { if (System.getSecurityManager() == null) { return ClassLoader.getSystemClassLoader(); } else { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return ClassLoader.getSystemClassLoader(); - } - }); + return AccessController.doPrivileged((PrivilegedAction) ClassLoader::getSystemClassLoader); } } diff --git a/common/src/main/java/io/netty/util/internal/SocketUtils.java b/common/src/main/java/io/netty/util/internal/SocketUtils.java index add0f7e128..b1d3d2e1d5 100644 --- a/common/src/main/java/io/netty/util/internal/SocketUtils.java +++ b/common/src/main/java/io/netty/util/internal/SocketUtils.java @@ -48,12 +48,9 @@ public final class SocketUtils { public static void connect(final Socket socket, final SocketAddress remoteAddress, final int timeout) throws IOException { try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Void run() throws IOException { - socket.connect(remoteAddress, timeout); - return null; - } + AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + socket.connect(remoteAddress, timeout); + return null; }); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); @@ -62,12 +59,9 @@ public final class SocketUtils { public static void bind(final Socket socket, final SocketAddress bindpoint) throws IOException { try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Void run() throws IOException { - socket.bind(bindpoint); - return null; - } + AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + socket.bind(bindpoint); + return null; }); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); @@ -77,12 +71,8 @@ public final class SocketUtils { public static boolean connect(final SocketChannel socketChannel, final SocketAddress remoteAddress) throws IOException { try { - return AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Boolean run() throws IOException { - return socketChannel.connect(remoteAddress); - } - }); + return AccessController.doPrivileged((PrivilegedExceptionAction) () -> + socketChannel.connect(remoteAddress)); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } @@ -90,12 +80,9 @@ public final class SocketUtils { public static void bind(final SocketChannel socketChannel, final SocketAddress address) throws IOException { try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Void run() throws IOException { - socketChannel.bind(address); - return null; - } + AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + socketChannel.bind(address); + return null; }); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); @@ -104,12 +91,8 @@ public final class SocketUtils { public static SocketChannel accept(final ServerSocketChannel serverSocketChannel) throws IOException { try { - return AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public SocketChannel run() throws IOException { - return serverSocketChannel.accept(); - } - }); + return AccessController.doPrivileged( + (PrivilegedExceptionAction) serverSocketChannel::accept); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } @@ -117,12 +100,9 @@ public final class SocketUtils { public static void bind(final DatagramChannel networkChannel, final SocketAddress address) throws IOException { try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Void run() throws IOException { - networkChannel.bind(address); - return null; - } + AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + networkChannel.bind(address); + return null; }); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); @@ -130,22 +110,13 @@ public final class SocketUtils { } public static SocketAddress localSocketAddress(final ServerSocket socket) { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public SocketAddress run() { - return socket.getLocalSocketAddress(); - } - }); + return AccessController.doPrivileged((PrivilegedAction) socket::getLocalSocketAddress); } public static InetAddress addressByName(final String hostname) throws UnknownHostException { try { - return AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public InetAddress run() throws UnknownHostException { - return InetAddress.getByName(hostname); - } - }); + return AccessController.doPrivileged((PrivilegedExceptionAction) () -> + InetAddress.getByName(hostname)); } catch (PrivilegedActionException e) { throw (UnknownHostException) e.getCause(); } @@ -153,52 +124,29 @@ public final class SocketUtils { public static InetAddress[] allAddressesByName(final String hostname) throws UnknownHostException { try { - return AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public InetAddress[] run() throws UnknownHostException { - return InetAddress.getAllByName(hostname); - } - }); + return AccessController.doPrivileged((PrivilegedExceptionAction) () -> + InetAddress.getAllByName(hostname)); } catch (PrivilegedActionException e) { throw (UnknownHostException) e.getCause(); } } public static InetSocketAddress socketAddress(final String hostname, final int port) { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public InetSocketAddress run() { - return new InetSocketAddress(hostname, port); - } - }); + return AccessController.doPrivileged((PrivilegedAction) () -> + new InetSocketAddress(hostname, port)); } public static Enumeration addressesFromNetworkInterface(final NetworkInterface intf) { - return AccessController.doPrivileged(new PrivilegedAction>() { - @Override - public Enumeration run() { - return intf.getInetAddresses(); - } - }); + return AccessController.doPrivileged((PrivilegedAction>) intf::getInetAddresses); } public static InetAddress loopbackAddress() { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public InetAddress run() { - return InetAddress.getLoopbackAddress(); - } - }); + return AccessController.doPrivileged((PrivilegedAction) InetAddress::getLoopbackAddress); } public static byte[] hardwareAddressFromNetworkInterface(final NetworkInterface intf) throws SocketException { try { - return AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public byte[] run() throws SocketException { - return intf.getHardwareAddress(); - } - }); + return AccessController.doPrivileged((PrivilegedExceptionAction) intf::getHardwareAddress); } catch (PrivilegedActionException e) { throw (SocketException) e.getCause(); } diff --git a/common/src/main/java/io/netty/util/internal/SystemPropertyUtil.java b/common/src/main/java/io/netty/util/internal/SystemPropertyUtil.java index d13f3876df..0ecc7bb3b7 100644 --- a/common/src/main/java/io/netty/util/internal/SystemPropertyUtil.java +++ b/common/src/main/java/io/netty/util/internal/SystemPropertyUtil.java @@ -68,12 +68,7 @@ public final class SystemPropertyUtil { if (System.getSecurityManager() == null) { value = System.getProperty(key); } else { - value = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public String run() { - return System.getProperty(key); - } - }); + value = AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(key)); } } catch (SecurityException e) { logger.warn("Unable to retrieve a system property '{}'; default values will be used.", key, e); diff --git a/common/src/main/java/io/netty/util/internal/logging/Log4J2Logger.java b/common/src/main/java/io/netty/util/internal/logging/Log4J2Logger.java index 5c3593f203..f751780aef 100644 --- a/common/src/main/java/io/netty/util/internal/logging/Log4J2Logger.java +++ b/common/src/main/java/io/netty/util/internal/logging/Log4J2Logger.java @@ -35,19 +35,16 @@ class Log4J2Logger extends ExtendedLoggerWrapper implements InternalLogger { // Older Log4J2 versions have only log methods that takes the format + varargs. So we should not use // Log4J2 if the version is too old. // See https://github.com/netty/netty/issues/8217 - VARARGS_ONLY = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - try { - Logger.class.getMethod("debug", String.class, Object.class); - return false; - } catch (NoSuchMethodException ignore) { - // Log4J2 version too old. - return true; - } catch (SecurityException ignore) { - // We could not detect the version so we will use Log4J2 if its on the classpath. - return false; - } + VARARGS_ONLY = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + Logger.class.getMethod("debug", String.class, Object.class); + return false; + } catch (NoSuchMethodException ignore) { + // Log4J2 version too old. + return true; + } catch (SecurityException ignore) { + // We could not detect the version so we will use Log4J2 if its on the classpath. + return false; } }); } diff --git a/common/src/test/java/io/netty/util/AbstractReferenceCountedTest.java b/common/src/test/java/io/netty/util/AbstractReferenceCountedTest.java index 226177d60e..0d37150ed8 100644 --- a/common/src/test/java/io/netty/util/AbstractReferenceCountedTest.java +++ b/common/src/test/java/io/netty/util/AbstractReferenceCountedTest.java @@ -98,19 +98,16 @@ public class AbstractReferenceCountedTest { for (int a = 0; a < threads; a++) { final int retainCnt = ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE); - futures.add(service.submit(new Runnable() { - @Override - public void run() { + futures.add(service.submit(() -> { + try { + retainLatch.await(); try { - retainLatch.await(); - try { - referenceCounted.retain(retainCnt); - } catch (IllegalReferenceCountException e) { - refCountExceptions.incrementAndGet(); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + referenceCounted.retain(retainCnt); + } catch (IllegalReferenceCountException e) { + refCountExceptions.incrementAndGet(); } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } })); } @@ -147,21 +144,18 @@ public class AbstractReferenceCountedTest { for (int a = 0; a < threads; a++) { final AtomicInteger releaseCnt = new AtomicInteger(0); - futures.add(service.submit(new Runnable() { - @Override - public void run() { + futures.add(service.submit(() -> { + try { + releaseLatch.await(); try { - releaseLatch.await(); - try { - if (referenceCounted.release(releaseCnt.incrementAndGet())) { - releasedCount.incrementAndGet(); - } - } catch (IllegalReferenceCountException e) { - refCountExceptions.incrementAndGet(); + if (referenceCounted.release(releaseCnt.incrementAndGet())) { + releasedCount.incrementAndGet(); } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + } catch (IllegalReferenceCountException e) { + refCountExceptions.incrementAndGet(); } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } })); } diff --git a/common/src/test/java/io/netty/util/ConstantPoolTest.java b/common/src/test/java/io/netty/util/ConstantPoolTest.java index 41c9cb8f0e..00d5d0c868 100644 --- a/common/src/test/java/io/netty/util/ConstantPoolTest.java +++ b/common/src/test/java/io/netty/util/ConstantPoolTest.java @@ -79,12 +79,7 @@ public class ConstantPoolTest { assertThat(array.length, is(5)); // Sort by name - Arrays.sort(array, new Comparator() { - @Override - public int compare(TestConstant o1, TestConstant o2) { - return o1.name().compareTo(o2.name()); - } - }); + Arrays.sort(array, (o1, o2) -> o1.name().compareTo(o2.name())); assertThat(array[0], is(sameInstance(a))); assertThat(array[1], is(sameInstance(b))); diff --git a/common/src/test/java/io/netty/util/HashedWheelTimerTest.java b/common/src/test/java/io/netty/util/HashedWheelTimerTest.java index 76340a277f..5a8f7678dc 100644 --- a/common/src/test/java/io/netty/util/HashedWheelTimerTest.java +++ b/common/src/test/java/io/netty/util/HashedWheelTimerTest.java @@ -35,12 +35,9 @@ public class HashedWheelTimerTest { public void testScheduleTimeoutShouldNotRunBeforeDelay() throws InterruptedException { final Timer timer = new HashedWheelTimer(); final CountDownLatch barrier = new CountDownLatch(1); - final Timeout timeout = timer.newTimeout(new TimerTask() { - @Override - public void run(Timeout timeout) throws Exception { - fail("This should not have run"); - barrier.countDown(); - } + final Timeout timeout = timer.newTimeout(timeout1 -> { + fail("This should not have run"); + barrier.countDown(); }, 10, TimeUnit.SECONDS); assertFalse(barrier.await(3, TimeUnit.SECONDS)); assertFalse("timer should not expire", timeout.isExpired()); @@ -51,12 +48,7 @@ public class HashedWheelTimerTest { public void testScheduleTimeoutShouldRunAfterDelay() throws InterruptedException { final Timer timer = new HashedWheelTimer(); final CountDownLatch barrier = new CountDownLatch(1); - final Timeout timeout = timer.newTimeout(new TimerTask() { - @Override - public void run(Timeout timeout) throws Exception { - barrier.countDown(); - } - }, 2, TimeUnit.SECONDS); + final Timeout timeout = timer.newTimeout(timeout1 -> barrier.countDown(), 2, TimeUnit.SECONDS); assertTrue(barrier.await(3, TimeUnit.SECONDS)); assertTrue("timer should expire", timeout.isExpired()); timer.stop(); @@ -67,12 +59,7 @@ public class HashedWheelTimerTest { final CountDownLatch latch = new CountDownLatch(3); final Timer timerProcessed = new HashedWheelTimer(); for (int i = 0; i < 3; i ++) { - timerProcessed.newTimeout(new TimerTask() { - @Override - public void run(final Timeout timeout) throws Exception { - latch.countDown(); - } - }, 1, TimeUnit.MILLISECONDS); + timerProcessed.newTimeout(timeout -> latch.countDown(), 1, TimeUnit.MILLISECONDS); } latch.await(); @@ -80,10 +67,7 @@ public class HashedWheelTimerTest { final Timer timerUnprocessed = new HashedWheelTimer(); for (int i = 0; i < 5; i ++) { - timerUnprocessed.newTimeout(new TimerTask() { - @Override - public void run(Timeout timeout) throws Exception { - } + timerUnprocessed.newTimeout(timeout -> { }, 5, TimeUnit.SECONDS); } Thread.sleep(1000L); // sleep for a second @@ -95,12 +79,7 @@ public class HashedWheelTimerTest { final CountDownLatch latch = new CountDownLatch(3); final Timer timer = new HashedWheelTimer(); for (int i = 0; i < 3; i ++) { - timer.newTimeout(new TimerTask() { - @Override - public void run(Timeout timeout) throws Exception { - latch.countDown(); - } - }, 1, TimeUnit.MILLISECONDS); + timer.newTimeout(timeout -> latch.countDown(), 1, TimeUnit.MILLISECONDS); } latch.await(); @@ -143,12 +122,8 @@ public class HashedWheelTimerTest { int scheduledTasks = 100000; for (int i = 0; i < scheduledTasks; i++) { final long start = System.nanoTime(); - timer.newTimeout(new TimerTask() { - @Override - public void run(final Timeout timeout) throws Exception { - queue.add(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); - } - }, timeout, TimeUnit.MILLISECONDS); + timer.newTimeout(timeout1 -> queue.add( + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)), timeout, TimeUnit.MILLISECONDS); } for (int i = 0; i < scheduledTasks; i++) { @@ -234,31 +209,18 @@ public class HashedWheelTimerTest { public void testOverflow() throws InterruptedException { final HashedWheelTimer timer = new HashedWheelTimer(); final CountDownLatch latch = new CountDownLatch(1); - Timeout timeout = timer.newTimeout(new TimerTask() { - @Override - public void run(Timeout timeout) { - latch.countDown(); - } - }, Long.MAX_VALUE, TimeUnit.MILLISECONDS); + Timeout timeout = timer.newTimeout(timeout1 -> latch.countDown(), Long.MAX_VALUE, TimeUnit.MILLISECONDS); assertFalse(latch.await(1, TimeUnit.SECONDS)); timeout.cancel(); timer.stop(); } private static TimerTask createNoOpTimerTask() { - return new TimerTask() { - @Override - public void run(final Timeout timeout) throws Exception { - } + return timeout -> { }; } private static TimerTask createCountDownLatchTimerTask(final CountDownLatch latch) { - return new TimerTask() { - @Override - public void run(final Timeout timeout) throws Exception { - latch.countDown(); - } - }; + return timeout -> latch.countDown(); } } diff --git a/common/src/test/java/io/netty/util/NettyRuntimeTests.java b/common/src/test/java/io/netty/util/NettyRuntimeTests.java index b69c85bff7..8760a362d7 100644 --- a/common/src/test/java/io/netty/util/NettyRuntimeTests.java +++ b/common/src/test/java/io/netty/util/NettyRuntimeTests.java @@ -102,17 +102,14 @@ public class NettyRuntimeTests { final NettyRuntime.AvailableProcessorsHolder holder, final CyclicBarrier barrier, final AtomicReference reference) { - return new Runnable() { - @Override - public void run() { - await(barrier); - try { - holder.availableProcessors(); - } catch (final IllegalStateException e) { - reference.set(e); - } - await(barrier); + return () -> { + await(barrier); + try { + holder.availableProcessors(); + } catch (final IllegalStateException e) { + reference.set(e); } + await(barrier); }; } @@ -120,28 +117,22 @@ public class NettyRuntimeTests { public void testRacingGetAndSet() throws InterruptedException { final NettyRuntime.AvailableProcessorsHolder holder = new NettyRuntime.AvailableProcessorsHolder(); final CyclicBarrier barrier = new CyclicBarrier(3); - final Thread get = new Thread(new Runnable() { - @Override - public void run() { - await(barrier); - holder.availableProcessors(); - await(barrier); - } + final Thread get = new Thread(() -> { + await(barrier); + holder.availableProcessors(); + await(barrier); }); get.start(); final AtomicReference setException = new AtomicReference<>(); - final Thread set = new Thread(new Runnable() { - @Override - public void run() { - await(barrier); - try { - holder.setAvailableProcessors(2048); - } catch (final IllegalStateException e) { - setException.set(e); - } - await(barrier); + final Thread set = new Thread(() -> { + await(barrier); + try { + holder.setAvailableProcessors(2048); + } catch (final IllegalStateException e) { + setException.set(e); } + await(barrier); }); set.start(); diff --git a/common/src/test/java/io/netty/util/RecyclerTest.java b/common/src/test/java/io/netty/util/RecyclerTest.java index c54c8a7b76..91a46d105c 100644 --- a/common/src/test/java/io/netty/util/RecyclerTest.java +++ b/common/src/test/java/io/netty/util/RecyclerTest.java @@ -41,13 +41,10 @@ public class RecyclerTest { final Recycler recycler = newRecycler(1024); final AtomicBoolean collected = new AtomicBoolean(); final AtomicReference reference = new AtomicReference<>(); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - HandledObject object = recycler.get(); - // Store a reference to the HandledObject to ensure it is not collected when the run method finish. - reference.set(object); - } + Thread thread = new Thread(() -> { + HandledObject object = recycler.get(); + // Store a reference to the HandledObject to ensure it is not collected when the run method finish. + reference.set(object); }) { @Override protected void finalize() throws Throwable { @@ -86,23 +83,15 @@ public class RecyclerTest { Recycler recycler = newRecycler(1024); final HandledObject object = recycler.get(); final AtomicReference exceptionStore = new AtomicReference<>(); - final Thread thread1 = new Thread(new Runnable() { - @Override - public void run() { - object.recycle(); - } - }); + final Thread thread1 = new Thread(object::recycle); thread1.start(); thread1.join(); - final Thread thread2 = new Thread(new Runnable() { - @Override - public void run() { - try { - object.recycle(); - } catch (IllegalStateException e) { - exceptionStore.set(e); - } + final Thread thread2 = new Thread(() -> { + try { + object.recycle(); + } catch (IllegalStateException e) { + exceptionStore.set(e); } }); thread2.start(); diff --git a/common/src/test/java/io/netty/util/ThreadDeathWatcherTest.java b/common/src/test/java/io/netty/util/ThreadDeathWatcherTest.java index ba9c218eb4..ed69eab670 100644 --- a/common/src/test/java/io/netty/util/ThreadDeathWatcherTest.java +++ b/common/src/test/java/io/netty/util/ThreadDeathWatcherTest.java @@ -46,12 +46,9 @@ public class ThreadDeathWatcherTest { } }; - final Runnable task = new Runnable() { - @Override - public void run() { - if (!t.isAlive()) { - latch.countDown(); - } + final Runnable task = () -> { + if (!t.isAlive()) { + latch.countDown(); } }; @@ -91,12 +88,7 @@ public class ThreadDeathWatcherTest { } }; - final Runnable task = new Runnable() { - @Override - public void run() { - run.set(true); - } - }; + final Runnable task = () -> run.set(true); t.start(); @@ -121,16 +113,10 @@ public class ThreadDeathWatcherTest { public void testThreadGroup() throws InterruptedException { final ThreadGroup group = new ThreadGroup("group"); final AtomicReference capturedGroup = new AtomicReference<>(); - final Thread thread = new Thread(group, new Runnable() { - @Override - public void run() { - final Thread t = ThreadDeathWatcher.threadFactory.newThread(new Runnable() { - @Override - public void run() { - } - }); - capturedGroup.set(t.getThreadGroup()); - } + final Thread thread = new Thread(group, () -> { + final Thread t = ThreadDeathWatcher.threadFactory.newThread(() -> { + }); + capturedGroup.set(t.getThreadGroup()); }); thread.start(); thread.join(); diff --git a/common/src/test/java/io/netty/util/concurrent/AbstractScheduledEventExecutorTest.java b/common/src/test/java/io/netty/util/concurrent/AbstractScheduledEventExecutorTest.java index 8ce9190b6e..7d99d24984 100644 --- a/common/src/test/java/io/netty/util/concurrent/AbstractScheduledEventExecutorTest.java +++ b/common/src/test/java/io/netty/util/concurrent/AbstractScheduledEventExecutorTest.java @@ -27,11 +27,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class AbstractScheduledEventExecutorTest { - private static final Runnable TEST_RUNNABLE = new Runnable() { - - @Override - public void run() { - } + private static final Runnable TEST_RUNNABLE = () -> { }; private static final Callable TEST_CALLABLE = Executors.callable(TEST_RUNNABLE); diff --git a/common/src/test/java/io/netty/util/concurrent/DefaultPromiseTest.java b/common/src/test/java/io/netty/util/concurrent/DefaultPromiseTest.java index 67a7d423a9..4b4a3d3ec0 100644 --- a/common/src/test/java/io/netty/util/concurrent/DefaultPromiseTest.java +++ b/common/src/test/java/io/netty/util/concurrent/DefaultPromiseTest.java @@ -157,12 +157,7 @@ public class DefaultPromiseTest { } }; - GlobalEventExecutor.INSTANCE.execute(new Runnable() { - @Override - public void run() { - promise.setSuccess(null); - } - }); + GlobalEventExecutor.INSTANCE.execute(() -> promise.setSuccess(null)); promise.addListener(listener1).addListener(listener2).addListener(listener3); @@ -217,12 +212,7 @@ public class DefaultPromiseTest { final Map> promises = new HashMap<>(); for (int i = 0; i < numberOfAttempts; i++) { final DefaultPromise promise = new DefaultPromise<>(executor); - final Thread thread = new Thread(new Runnable() { - @Override - public void run() { - promise.setSuccess(null); - } - }); + final Thread thread = new Thread(() -> promise.setSuccess(null)); promises.put(thread, promise); } @@ -278,12 +268,7 @@ public class DefaultPromiseTest { final CountDownLatch latch = new CountDownLatch(promiseChainLength); if (runTestInExecutorThread) { - executor.execute(new Runnable() { - @Override - public void run() { - testStackOverFlowChainedFuturesA(executor, p, latch); - } - }); + executor.execute(() -> testStackOverFlowChainedFuturesA(executor, p, latch)); } else { testStackOverFlowChainedFuturesA(executor, p, latch); } @@ -299,14 +284,11 @@ public class DefaultPromiseTest { for (int i = 0; i < p.length; i ++) { final int finalI = i; p[i] = new DefaultPromise<>(executor); - p[i].addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - if (finalI + 1 < p.length) { - p[finalI + 1].setSuccess(null); - } - latch.countDown(); + p[i].addListener((FutureListener) future -> { + if (finalI + 1 < p.length) { + p[finalI + 1].setSuccess(null); } + latch.countDown(); }); } @@ -320,12 +302,7 @@ public class DefaultPromiseTest { final CountDownLatch latch = new CountDownLatch(promiseChainLength); if (runTestInExecutorThread) { - executor.execute(new Runnable() { - @Override - public void run() { - testStackOverFlowChainedFuturesA(executor, p, latch); - } - }); + executor.execute(() -> testStackOverFlowChainedFuturesA(executor, p, latch)); } else { testStackOverFlowChainedFuturesA(executor, p, latch); } @@ -341,20 +318,12 @@ public class DefaultPromiseTest { for (int i = 0; i < p.length; i ++) { final int finalI = i; p[i] = new DefaultPromise<>(executor); - p[i].addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - future.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - if (finalI + 1 < p.length) { - p[finalI + 1].setSuccess(null); - } - latch.countDown(); - } - }); + p[i].addListener((FutureListener) future -> future.addListener((FutureListener) future1 -> { + if (finalI + 1 < p.length) { + p[finalI + 1].setSuccess(null); } - }); + latch.countDown(); + })); } p[0].setSuccess(null); @@ -379,12 +348,7 @@ public class DefaultPromiseTest { final Promise promise = new DefaultPromise<>(executor); // Add a listener before completion so "lateListener" is used next time we add a listener. - promise.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - assertTrue(state.compareAndSet(0, 1)); - } - }); + promise.addListener((FutureListener) future -> assertTrue(state.compareAndSet(0, 1))); // Simulate write operation completing, which will execute listeners in another thread. if (cause == null) { @@ -394,12 +358,9 @@ public class DefaultPromiseTest { } // Add a "late listener" - promise.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - assertTrue(state.compareAndSet(1, 2)); - latch1.countDown(); - } + promise.addListener((FutureListener) future -> { + assertTrue(state.compareAndSet(1, 2)); + latch1.countDown(); }); // Wait for the listeners and late listeners to be completed. @@ -408,27 +369,16 @@ public class DefaultPromiseTest { // This is the important listener. A late listener that is added after all late listeners // have completed, and needs to update state before a read operation (on the same executor). - executor.execute(new Runnable() { - @Override - public void run() { - promise.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - assertTrue(state.compareAndSet(2, 3)); - latch2.countDown(); - } - }); - } - }); + executor.execute(() -> promise.addListener((FutureListener) future -> { + assertTrue(state.compareAndSet(2, 3)); + latch2.countDown(); + })); // Simulate a read operation being queued up in the executor. - executor.execute(new Runnable() { - @Override - public void run() { - // This is the key, we depend upon the state being set in the next listener. - assertEquals(3, state.get()); - latch2.countDown(); - } + executor.execute(() -> { + // This is the key, we depend upon the state being set in the next listener. + assertEquals(3, state.get()); + latch2.countDown(); }); latch2.await(); @@ -440,17 +390,8 @@ public class DefaultPromiseTest { private static void testPromiseListenerAddWhenComplete(Throwable cause) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final Promise promise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); - promise.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - promise.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - latch.countDown(); - } - }); - } - }); + promise.addListener((FutureListener) future -> + promise.addListener((FutureListener) future1 -> latch.countDown())); if (cause == null) { promise.setSuccess(null); } else { @@ -463,29 +404,16 @@ public class DefaultPromiseTest { EventExecutor executor = new TestEventExecutor(); int expectedCount = numListenersBefore + 2; final CountDownLatch latch = new CountDownLatch(expectedCount); - final FutureListener listener = new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - latch.countDown(); - } - }; + final FutureListener listener = future -> latch.countDown(); final Promise promise = new DefaultPromise<>(executor); - executor.execute(new Runnable() { - @Override - public void run() { - for (int i = 0; i < numListenersBefore; i++) { - promise.addListener(listener); - } - promise.setSuccess(null); - - GlobalEventExecutor.INSTANCE.execute(new Runnable() { - @Override - public void run() { - promise.addListener(listener); - } - }); + executor.execute(() -> { + for (int i = 0; i < numListenersBefore; i++) { promise.addListener(listener); } + promise.setSuccess(null); + + GlobalEventExecutor.INSTANCE.execute(() -> promise.addListener(listener)); + promise.addListener(listener); }); assertTrue("Should have notified " + expectedCount + " listeners", diff --git a/common/src/test/java/io/netty/util/concurrent/DefaultThreadFactoryTest.java b/common/src/test/java/io/netty/util/concurrent/DefaultThreadFactoryTest.java index 85d12d17cd..926ebb2a3d 100644 --- a/common/src/test/java/io/netty/util/concurrent/DefaultThreadFactoryTest.java +++ b/common/src/test/java/io/netty/util/concurrent/DefaultThreadFactoryTest.java @@ -55,30 +55,22 @@ public class DefaultThreadFactoryTest { // holder for the thread factory, plays the role of a global singleton final AtomicReference factory = new AtomicReference<>(); final AtomicInteger counter = new AtomicInteger(); - final Runnable task = new Runnable() { - @Override - public void run() { - counter.incrementAndGet(); - } - }; + final Runnable task = counter::incrementAndGet; final AtomicReference interrupted = new AtomicReference<>(); // create the thread factory, since we are running the thread group brother, the thread // factory will now forever be tied to that group // we then create a thread from the factory to run a "task" for us - final Thread first = new Thread(new ThreadGroup("brother"), new Runnable() { - @Override - public void run() { - factory.set(new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, null)); - final Thread t = factory.get().newThread(task); - t.start(); - try { - t.join(); - } catch (InterruptedException e) { - interrupted.set(e); - Thread.currentThread().interrupt(); - } + final Thread first = new Thread(new ThreadGroup("brother"), () -> { + factory.set(new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, null)); + final Thread t = factory.get().newThread(task); + t.start(); + try { + t.join(); + } catch (InterruptedException e) { + interrupted.set(e); + Thread.currentThread().interrupt(); } }); first.start(); @@ -89,17 +81,14 @@ public class DefaultThreadFactoryTest { // now we will use factory again, this time from a sibling thread group sister // if DefaultThreadFactory is "sticky" about thread groups, a security manager // that forbids sibling thread groups from messing with each other will strike this down - final Thread second = new Thread(new ThreadGroup("sister"), new Runnable() { - @Override - public void run() { - final Thread t = factory.get().newThread(task); - t.start(); - try { - t.join(); - } catch (InterruptedException e) { - interrupted.set(e); - Thread.currentThread().interrupt(); - } + final Thread second = new Thread(new ThreadGroup("sister"), () -> { + final Thread t = factory.get().newThread(task); + t.start(); + try { + t.join(); + } catch (InterruptedException e) { + interrupted.set(e); + Thread.currentThread().interrupt(); } }); second.start(); @@ -119,12 +108,7 @@ public class DefaultThreadFactoryTest { public void testDefaultThreadFactoryStickyThreadGroupConstructor() throws InterruptedException { final ThreadGroup sticky = new ThreadGroup("sticky"); runStickyThreadGroupTest( - new Callable() { - @Override - public DefaultThreadFactory call() throws Exception { - return new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, sticky); - } - }, + () -> new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, sticky), sticky); } @@ -135,21 +119,13 @@ public class DefaultThreadFactoryTest { final ThreadGroup sticky = new ThreadGroup("sticky"); runStickyThreadGroupTest( - new Callable() { - @Override - public DefaultThreadFactory call() throws Exception { - final AtomicReference factory = - new AtomicReference<>(); - final Thread thread = new Thread(sticky, new Runnable() { - @Override - public void run() { - factory.set(new DefaultThreadFactory("test")); - } - }); - thread.start(); - thread.join(); - return factory.get(); - } + () -> { + final AtomicReference factory = + new AtomicReference<>(); + final Thread thread = new Thread(sticky, () -> factory.set(new DefaultThreadFactory("test"))); + thread.start(); + thread.join(); + return factory.get(); }, sticky); } @@ -174,12 +150,7 @@ public class DefaultThreadFactoryTest { } }); runStickyThreadGroupTest( - new Callable() { - @Override - public DefaultThreadFactory call() throws Exception { - return new DefaultThreadFactory("test"); - } - }, + () -> new DefaultThreadFactory("test"), sticky); } finally { System.setSecurityManager(current); @@ -192,23 +163,17 @@ public class DefaultThreadFactoryTest { final AtomicReference captured = new AtomicReference<>(); final AtomicReference exception = new AtomicReference<>(); - final Thread first = new Thread(new ThreadGroup("wrong"), new Runnable() { - @Override - public void run() { - final DefaultThreadFactory factory; - try { - factory = callable.call(); - } catch (Exception e) { - exception.set(e); - throw new RuntimeException(e); - } - final Thread t = factory.newThread(new Runnable() { - @Override - public void run() { - } - }); - captured.set(t.getThreadGroup()); + final Thread first = new Thread(new ThreadGroup("wrong"), () -> { + final DefaultThreadFactory factory; + try { + factory = callable.call(); + } catch (Exception e) { + exception.set(e); + throw new RuntimeException(e); } + final Thread t = factory.newThread(() -> { + }); + captured.set(t.getThreadGroup()); }); first.start(); first.join(); @@ -227,17 +192,11 @@ public class DefaultThreadFactoryTest { final AtomicReference firstCaptured = new AtomicReference<>(); final ThreadGroup firstGroup = new ThreadGroup("first"); - final Thread first = new Thread(firstGroup, new Runnable() { - @Override - public void run() { - factory.set(new DefaultThreadFactory("sticky", false, Thread.NORM_PRIORITY, null)); - final Thread t = factory.get().newThread(new Runnable() { - @Override - public void run() { - } - }); - firstCaptured.set(t.getThreadGroup()); - } + final Thread first = new Thread(firstGroup, () -> { + factory.set(new DefaultThreadFactory("sticky", false, Thread.NORM_PRIORITY, null)); + final Thread t = factory.get().newThread(() -> { + }); + firstCaptured.set(t.getThreadGroup()); }); first.start(); first.join(); @@ -247,16 +206,10 @@ public class DefaultThreadFactoryTest { final AtomicReference secondCaptured = new AtomicReference<>(); final ThreadGroup secondGroup = new ThreadGroup("second"); - final Thread second = new Thread(secondGroup, new Runnable() { - @Override - public void run() { - final Thread t = factory.get().newThread(new Runnable() { - @Override - public void run() { - } - }); - secondCaptured.set(t.getThreadGroup()); - } + final Thread second = new Thread(secondGroup, () -> { + final Thread t = factory.get().newThread(() -> { + }); + secondCaptured.set(t.getThreadGroup()); }); second.start(); second.join(); diff --git a/common/src/test/java/io/netty/util/concurrent/FastThreadLocalTest.java b/common/src/test/java/io/netty/util/concurrent/FastThreadLocalTest.java index 270d7624c4..77b1568ea6 100644 --- a/common/src/test/java/io/netty/util/concurrent/FastThreadLocalTest.java +++ b/common/src/test/java/io/netty/util/concurrent/FastThreadLocalTest.java @@ -82,14 +82,11 @@ public class FastThreadLocalTest { @Test public void testMultipleSetRemove() throws Exception { final FastThreadLocal threadLocal = new FastThreadLocal<>(); - final Runnable runnable = new Runnable() { - @Override - public void run() { - threadLocal.set("1"); - threadLocal.remove(); - threadLocal.set("2"); - threadLocal.remove(); - } + final Runnable runnable = () -> { + threadLocal.set("1"); + threadLocal.remove(); + threadLocal.set("2"); + threadLocal.remove(); }; final int sizeWhenStart = ObjectCleaner.getLiveSetCount(); @@ -110,18 +107,15 @@ public class FastThreadLocalTest { public void testMultipleSetRemove_multipleThreadLocal() throws Exception { final FastThreadLocal threadLocal = new FastThreadLocal<>(); final FastThreadLocal threadLocal2 = new FastThreadLocal<>(); - final Runnable runnable = new Runnable() { - @Override - public void run() { - threadLocal.set("1"); - threadLocal.remove(); - threadLocal.set("2"); - threadLocal.remove(); - threadLocal2.set("1"); - threadLocal2.remove(); - threadLocal2.set("2"); - threadLocal2.remove(); - } + final Runnable runnable = () -> { + threadLocal.set("1"); + threadLocal.remove(); + threadLocal.set("2"); + threadLocal.remove(); + threadLocal2.set("1"); + threadLocal2.remove(); + threadLocal2.set("2"); + threadLocal2.remove(); }; final int sizeWhenStart = ObjectCleaner.getLiveSetCount(); @@ -165,16 +159,13 @@ public class FastThreadLocalTest { final TestFastThreadLocal threadLocal = new TestFastThreadLocal(); final TestFastThreadLocal threadLocal2 = new TestFastThreadLocal(); - Runnable runnable = new Runnable() { - @Override - public void run() { - if (callGet) { - assertEquals(Thread.currentThread().getName(), threadLocal.get()); - assertEquals(Thread.currentThread().getName(), threadLocal2.get()); - } else { - threadLocal.set(Thread.currentThread().getName()); - threadLocal2.set(Thread.currentThread().getName()); - } + Runnable runnable = () -> { + if (callGet) { + assertEquals(Thread.currentThread().getName(), threadLocal.get()); + assertEquals(Thread.currentThread().getName(), threadLocal2.get()); + } else { + threadLocal.set(Thread.currentThread().getName()); + threadLocal2.set(Thread.currentThread().getName()); } }; Thread thread = fastThreadLocal ? new FastThreadLocalThread(runnable) : new Thread(runnable); diff --git a/common/src/test/java/io/netty/util/concurrent/GlobalEventExecutorTest.java b/common/src/test/java/io/netty/util/concurrent/GlobalEventExecutorTest.java index 14eba7bcde..be91399c22 100644 --- a/common/src/test/java/io/netty/util/concurrent/GlobalEventExecutorTest.java +++ b/common/src/test/java/io/netty/util/concurrent/GlobalEventExecutorTest.java @@ -99,16 +99,10 @@ public class GlobalEventExecutorTest { public void testThreadGroup() throws InterruptedException { final ThreadGroup group = new ThreadGroup("group"); final AtomicReference capturedGroup = new AtomicReference<>(); - final Thread thread = new Thread(group, new Runnable() { - @Override - public void run() { - final Thread t = e.threadFactory.newThread(new Runnable() { - @Override - public void run() { - } - }); - capturedGroup.set(t.getThreadGroup()); - } + final Thread thread = new Thread(group, () -> { + final Thread t = e.threadFactory.newThread(() -> { + }); + capturedGroup.set(t.getThreadGroup()); }); thread.start(); thread.join(); diff --git a/common/src/test/java/io/netty/util/concurrent/NonStickyEventExecutorGroupTest.java b/common/src/test/java/io/netty/util/concurrent/NonStickyEventExecutorGroupTest.java index d72a698166..27ecd9dd67 100644 --- a/common/src/test/java/io/netty/util/concurrent/NonStickyEventExecutorGroupTest.java +++ b/common/src/test/java/io/netty/util/concurrent/NonStickyEventExecutorGroupTest.java @@ -68,14 +68,11 @@ public class NonStickyEventExecutorGroupTest { final AtomicReference error = new AtomicReference<>(); List threadList = new ArrayList<>(threads); for (int i = 0 ; i < threads; i++) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - execute(nonStickyGroup, startLatch); - } catch (Throwable cause) { - error.compareAndSet(null, cause); - } + Thread thread = new Thread(() -> { + try { + execute(nonStickyGroup, startLatch); + } catch (Throwable cause) { + error.compareAndSet(null, cause); } }); threadList.add(thread); @@ -106,12 +103,9 @@ public class NonStickyEventExecutorGroupTest { final CountDownLatch firstCompleted = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(2); for (int i = 0; i < 2; i++) { - executor.execute(new Runnable() { - @Override - public void run() { - firstCompleted.countDown(); - latch.countDown(); - } + executor.execute(() -> { + firstCompleted.countDown(); + latch.countDown(); }); Assert.assertTrue(firstCompleted.await(1, TimeUnit.SECONDS)); } @@ -135,23 +129,20 @@ public class NonStickyEventExecutorGroupTest { for (int i = 1 ; i <= tasks; i++) { final int id = i; - futures.add(executor.submit(new Runnable() { - @Override - public void run() { - try { - if (cause.get() == null) { - int lastId = last.get(); - if (lastId >= id) { - cause.compareAndSet(null, new AssertionError( - "Out of order execution id(" + id + ") >= lastId(" + lastId + ')')); - } - if (!last.compareAndSet(lastId, id)) { - cause.compareAndSet(null, new AssertionError("Concurrent execution of tasks")); - } + futures.add(executor.submit(() -> { + try { + if (cause.get() == null) { + int lastId = last.get(); + if (lastId >= id) { + cause.compareAndSet(null, new AssertionError( + "Out of order execution id(" + id + ") >= lastId(" + lastId + ')')); + } + if (!last.compareAndSet(lastId, id)) { + cause.compareAndSet(null, new AssertionError("Concurrent execution of tasks")); } - } finally { - latch.countDown(); } + } finally { + latch.countDown(); } })); } diff --git a/common/src/test/java/io/netty/util/concurrent/PromiseCombinerTest.java b/common/src/test/java/io/netty/util/concurrent/PromiseCombinerTest.java index b46fa41024..1625a7f3b3 100644 --- a/common/src/test/java/io/netty/util/concurrent/PromiseCombinerTest.java +++ b/common/src/test/java/io/netty/util/concurrent/PromiseCombinerTest.java @@ -178,13 +178,9 @@ public class PromiseCombinerTest { @SuppressWarnings("unchecked") private static void mockListener(final Promise p, final GenericFutureListenerConsumer consumer) { - doAnswer(new Answer>() { - @SuppressWarnings({ "unchecked", "raw-types" }) - @Override - public Promise answer(InvocationOnMock invocation) throws Throwable { - consumer.accept((GenericFutureListener) invocation.getArgument(0)); - return p; - } + doAnswer(invocation -> { + consumer.accept((GenericFutureListener) invocation.getArgument(0)); + return p; }).when(p).addListener(any(GenericFutureListener.class)); } diff --git a/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java b/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java index f01b86ac6c..1549163f77 100644 --- a/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java +++ b/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java @@ -60,11 +60,8 @@ public class SingleThreadEventExecutorTest { private static void executeShouldFail(Executor executor) { try { - executor.execute(new Runnable() { - @Override - public void run() { - // Noop. - } + executor.execute(() -> { + // Noop. }); Assert.fail(); } catch (RejectedExecutionException expected) { @@ -133,34 +130,28 @@ public class SingleThreadEventExecutorTest { }; try { final Promise promise = executor.newPromise(); - executor.execute(new Runnable() { - @Override - public void run() { - try { - Set> set = Collections.singleton(new Callable() { - @Override - public Boolean call() throws Exception { - promise.setFailure(new AssertionError("Should never execute the Callable")); - return Boolean.TRUE; - } - }); - if (any) { - if (timeout) { - executor.invokeAny(set, 10, TimeUnit.SECONDS); - } else { - executor.invokeAny(set); - } + executor.execute(() -> { + try { + Set> set = Collections.singleton(() -> { + promise.setFailure(new AssertionError("Should never execute the Callable")); + return Boolean.TRUE; + }); + if (any) { + if (timeout) { + executor.invokeAny(set, 10, TimeUnit.SECONDS); } else { - if (timeout) { - executor.invokeAll(set, 10, TimeUnit.SECONDS); - } else { - executor.invokeAll(set); - } + executor.invokeAny(set); + } + } else { + if (timeout) { + executor.invokeAll(set, 10, TimeUnit.SECONDS); + } else { + executor.invokeAll(set); } - promise.setFailure(new AssertionError("Should never reach here")); - } catch (Throwable cause) { - promise.setFailure(cause); } + promise.setFailure(new AssertionError("Should never reach here")); + } catch (Throwable cause) { + promise.setFailure(cause); } }); promise.syncUninterruptibly(); diff --git a/common/src/test/java/io/netty/util/concurrent/UnorderedThreadPoolEventExecutorTest.java b/common/src/test/java/io/netty/util/concurrent/UnorderedThreadPoolEventExecutorTest.java index d96db3fcb0..32c26490fe 100644 --- a/common/src/test/java/io/netty/util/concurrent/UnorderedThreadPoolEventExecutorTest.java +++ b/common/src/test/java/io/netty/util/concurrent/UnorderedThreadPoolEventExecutorTest.java @@ -29,19 +29,9 @@ public class UnorderedThreadPoolEventExecutorTest { try { final CountDownLatch latch = new CountDownLatch(3); - Runnable task = new Runnable() { - @Override - public void run() { - latch.countDown(); - } - }; + Runnable task = latch::countDown; executor.execute(task); - Future future = executor.submit(task).addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - latch.countDown(); - } - }); + Future future = executor.submit(task).addListener((FutureListener) future1 -> latch.countDown()); latch.await(); future.syncUninterruptibly(); diff --git a/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java b/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java index 7e75504021..2471bb6a5c 100644 --- a/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java +++ b/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java @@ -35,23 +35,15 @@ public class ObjectCleanerTest { public void testCleanup() throws Exception { final AtomicBoolean freeCalled = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); - temporaryThread = new Thread(new Runnable() { - @Override - public void run() { - try { - latch.await(); - } catch (InterruptedException ignore) { - // just ignore - } + temporaryThread = new Thread(() -> { + try { + latch.await(); + } catch (InterruptedException ignore) { + // just ignore } }); temporaryThread.start(); - ObjectCleaner.register(temporaryThread, new Runnable() { - @Override - public void run() { - freeCalled.set(true); - } - }); + ObjectCleaner.register(temporaryThread, () -> freeCalled.set(true)); latch.countDown(); temporaryThread.join(); @@ -71,31 +63,22 @@ public class ObjectCleanerTest { public void testCleanupContinuesDespiteThrowing() throws InterruptedException { final AtomicInteger freeCalledCount = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(1); - temporaryThread = new Thread(new Runnable() { - @Override - public void run() { - try { - latch.await(); - } catch (InterruptedException ignore) { - // just ignore - } + temporaryThread = new Thread(() -> { + try { + latch.await(); + } catch (InterruptedException ignore) { + // just ignore } }); temporaryThread.start(); temporaryObject = new Object(); - ObjectCleaner.register(temporaryThread, new Runnable() { - @Override - public void run() { - freeCalledCount.incrementAndGet(); - throw new RuntimeException("expected"); - } + ObjectCleaner.register(temporaryThread, () -> { + freeCalledCount.incrementAndGet(); + throw new RuntimeException("expected"); }); - ObjectCleaner.register(temporaryObject, new Runnable() { - @Override - public void run() { - freeCalledCount.incrementAndGet(); - throw new RuntimeException("expected"); - } + ObjectCleaner.register(temporaryObject, () -> { + freeCalledCount.incrementAndGet(); + throw new RuntimeException("expected"); }); latch.countDown(); @@ -116,11 +99,8 @@ public class ObjectCleanerTest { @Test(timeout = 5000) public void testCleanerThreadIsDaemon() throws Exception { temporaryObject = new Object(); - ObjectCleaner.register(temporaryObject, new Runnable() { - @Override - public void run() { - // NOOP - } + ObjectCleaner.register(temporaryObject, () -> { + // NOOP }); Thread cleanerThread = null; diff --git a/common/src/test/java/io/netty/util/internal/PlatformDependentTest.java b/common/src/test/java/io/netty/util/internal/PlatformDependentTest.java index 295fe30a14..6a6f836cc5 100644 --- a/common/src/test/java/io/netty/util/internal/PlatformDependentTest.java +++ b/common/src/test/java/io/netty/util/internal/PlatformDependentTest.java @@ -29,22 +29,13 @@ public class PlatformDependentTest { private static final Random r = new Random(); @Test public void testEqualsConsistentTime() { - testEquals(new EqualityChecker() { - @Override - public boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) { - return PlatformDependent.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length) != 0; - } - }); + testEquals((bytes1, startPos1, bytes2, startPos2, length) -> + PlatformDependent.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length) != 0); } @Test public void testEquals() { - testEquals(new EqualityChecker() { - @Override - public boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) { - return PlatformDependent.equals(bytes1, startPos1, bytes2, startPos2, length); - } - }); + testEquals(PlatformDependent::equals); } @Test diff --git a/example/src/main/java/io/netty/example/discard/DiscardClientHandler.java b/example/src/main/java/io/netty/example/discard/DiscardClientHandler.java index c20f1daff4..0867c18c78 100644 --- a/example/src/main/java/io/netty/example/discard/DiscardClientHandler.java +++ b/example/src/main/java/io/netty/example/discard/DiscardClientHandler.java @@ -65,15 +65,12 @@ public class DiscardClientHandler extends SimpleChannelInboundHandler { ctx.writeAndFlush(content.retainedDuplicate()).addListener(trafficGenerator); } - private final ChannelFutureListener trafficGenerator = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (future.isSuccess()) { - generateTraffic(); - } else { - future.cause().printStackTrace(); - future.channel().close(); - } + private final ChannelFutureListener trafficGenerator = future -> { + if (future.isSuccess()) { + generateTraffic(); + } else { + future.cause().printStackTrace(); + future.channel().close(); } }; } diff --git a/example/src/main/java/io/netty/example/factorial/FactorialClientHandler.java b/example/src/main/java/io/netty/example/factorial/FactorialClientHandler.java index e7037b3d68..23fb772819 100644 --- a/example/src/main/java/io/netty/example/factorial/FactorialClientHandler.java +++ b/example/src/main/java/io/netty/example/factorial/FactorialClientHandler.java @@ -66,12 +66,9 @@ public class FactorialClientHandler extends SimpleChannelInboundHandler { + boolean offered = answer.offer(msg); + assert offered; }); } } @@ -96,15 +93,12 @@ public class FactorialClientHandler extends SimpleChannelInboundHandler { + if (future.isSuccess()) { + sendNumbers(); + } else { + future.cause().printStackTrace(); + future.channel().close(); } }; } diff --git a/example/src/main/java/io/netty/example/http2/helloworld/frame/server/Http2ServerInitializer.java b/example/src/main/java/io/netty/example/http2/helloworld/frame/server/Http2ServerInitializer.java index b2bb856f49..af42a8e688 100644 --- a/example/src/main/java/io/netty/example/http2/helloworld/frame/server/Http2ServerInitializer.java +++ b/example/src/main/java/io/netty/example/http2/helloworld/frame/server/Http2ServerInitializer.java @@ -42,15 +42,12 @@ import io.netty.util.ReferenceCountUtil; */ public class Http2ServerInitializer extends ChannelInitializer { - private static final UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() { - @Override - public UpgradeCodec newUpgradeCodec(CharSequence protocol) { - if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { - return new Http2ServerUpgradeCodec( - Http2FrameCodecBuilder.forServer().build(), new HelloWorldHttp2Handler()); - } else { - return null; - } + private static final UpgradeCodecFactory upgradeCodecFactory = protocol -> { + if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { + return new Http2ServerUpgradeCodec( + Http2FrameCodecBuilder.forServer().build(), new HelloWorldHttp2Handler()); + } else { + return null; } }; diff --git a/example/src/main/java/io/netty/example/http2/helloworld/multiplex/server/Http2ServerInitializer.java b/example/src/main/java/io/netty/example/http2/helloworld/multiplex/server/Http2ServerInitializer.java index 891becc432..a1c3ea607f 100644 --- a/example/src/main/java/io/netty/example/http2/helloworld/multiplex/server/Http2ServerInitializer.java +++ b/example/src/main/java/io/netty/example/http2/helloworld/multiplex/server/Http2ServerInitializer.java @@ -42,15 +42,12 @@ import io.netty.util.ReferenceCountUtil; */ public class Http2ServerInitializer extends ChannelInitializer { - private static final UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() { - @Override - public UpgradeCodec newUpgradeCodec(CharSequence protocol) { - if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { - return new Http2ServerUpgradeCodec( - Http2MultiplexCodecBuilder.forServer(new HelloWorldHttp2Handler()).build()); - } else { - return null; - } + private static final UpgradeCodecFactory upgradeCodecFactory = protocol -> { + if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { + return new Http2ServerUpgradeCodec( + Http2MultiplexCodecBuilder.forServer(new HelloWorldHttp2Handler()).build()); + } else { + return null; } }; diff --git a/example/src/main/java/io/netty/example/http2/helloworld/server/Http2ServerInitializer.java b/example/src/main/java/io/netty/example/http2/helloworld/server/Http2ServerInitializer.java index b5dff01e30..911dc23d8c 100644 --- a/example/src/main/java/io/netty/example/http2/helloworld/server/Http2ServerInitializer.java +++ b/example/src/main/java/io/netty/example/http2/helloworld/server/Http2ServerInitializer.java @@ -41,14 +41,11 @@ import io.netty.util.ReferenceCountUtil; */ public class Http2ServerInitializer extends ChannelInitializer { - private static final UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() { - @Override - public UpgradeCodec newUpgradeCodec(CharSequence protocol) { - if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { - return new Http2ServerUpgradeCodec(new HelloWorldHttp2HandlerBuilder().build()); - } else { - return null; - } + private static final UpgradeCodecFactory upgradeCodecFactory = protocol -> { + if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { + return new Http2ServerUpgradeCodec(new HelloWorldHttp2HandlerBuilder().build()); + } else { + return null; } }; diff --git a/example/src/main/java/io/netty/example/http2/tiles/Http1RequestHandler.java b/example/src/main/java/io/netty/example/http2/tiles/Http1RequestHandler.java index 49590f8eea..5f46e896ce 100644 --- a/example/src/main/java/io/netty/example/http2/tiles/Http1RequestHandler.java +++ b/example/src/main/java/io/netty/example/http2/tiles/Http1RequestHandler.java @@ -47,15 +47,12 @@ public final class Http1RequestHandler extends Http2RequestHandler { protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency, final FullHttpResponse response, final FullHttpRequest request) { HttpUtil.setContentLength(response, response.content().readableBytes()); - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - if (isKeepAlive(request)) { - response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); - ctx.writeAndFlush(response); - } else { - ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); - } + ctx.executor().schedule(() -> { + if (isKeepAlive(request)) { + response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); + ctx.writeAndFlush(response); + } else { + ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } }, latency, TimeUnit.MILLISECONDS); } diff --git a/example/src/main/java/io/netty/example/http2/tiles/Http2RequestHandler.java b/example/src/main/java/io/netty/example/http2/tiles/Http2RequestHandler.java index 07af263dda..72e35e8ac8 100644 --- a/example/src/main/java/io/netty/example/http2/tiles/Http2RequestHandler.java +++ b/example/src/main/java/io/netty/example/http2/tiles/Http2RequestHandler.java @@ -98,11 +98,8 @@ public class Http2RequestHandler extends SimpleChannelInboundHandler { + ctx.writeAndFlush(response); }, latency, TimeUnit.MILLISECONDS); } diff --git a/example/src/main/java/io/netty/example/proxy/HexDumpProxyBackendHandler.java b/example/src/main/java/io/netty/example/proxy/HexDumpProxyBackendHandler.java index 10a97f8128..0b8aa42bad 100644 --- a/example/src/main/java/io/netty/example/proxy/HexDumpProxyBackendHandler.java +++ b/example/src/main/java/io/netty/example/proxy/HexDumpProxyBackendHandler.java @@ -36,14 +36,11 @@ public class HexDumpProxyBackendHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { - inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (future.isSuccess()) { - ctx.channel().read(); - } else { - future.channel().close(); - } + inboundChannel.writeAndFlush(msg).addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + ctx.channel().read(); + } else { + future.channel().close(); } }); } diff --git a/example/src/main/java/io/netty/example/proxy/HexDumpProxyFrontendHandler.java b/example/src/main/java/io/netty/example/proxy/HexDumpProxyFrontendHandler.java index e6919d9dfa..601005b2c5 100644 --- a/example/src/main/java/io/netty/example/proxy/HexDumpProxyFrontendHandler.java +++ b/example/src/main/java/io/netty/example/proxy/HexDumpProxyFrontendHandler.java @@ -50,16 +50,13 @@ public class HexDumpProxyFrontendHandler extends ChannelInboundHandlerAdapter { .option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel(); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (future.isSuccess()) { - // connection complete start to read first data - inboundChannel.read(); - } else { - // Close the connection if the connection attempt has failed. - inboundChannel.close(); - } + f.addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + // connection complete start to read first data + inboundChannel.read(); + } else { + // Close the connection if the connection attempt has failed. + inboundChannel.close(); } }); } @@ -67,15 +64,12 @@ public class HexDumpProxyFrontendHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (outboundChannel.isActive()) { - outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (future.isSuccess()) { - // was able to flush out data, start to read the next chunk - ctx.channel().read(); - } else { - future.channel().close(); - } + outboundChannel.writeAndFlush(msg).addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + // was able to flush out data, start to read the next chunk + ctx.channel().read(); + } else { + future.channel().close(); } }); } diff --git a/example/src/main/java/io/netty/example/redis/RedisClient.java b/example/src/main/java/io/netty/example/redis/RedisClient.java index 640f2b8242..65fb9b5517 100644 --- a/example/src/main/java/io/netty/example/redis/RedisClient.java +++ b/example/src/main/java/io/netty/example/redis/RedisClient.java @@ -77,13 +77,10 @@ public class RedisClient { } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line); - lastWriteFuture.addListener(new GenericFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - System.err.print("write failed: "); - future.cause().printStackTrace(System.err); - } + lastWriteFuture.addListener((GenericFutureListener) future -> { + if (!future.isSuccess()) { + System.err.print("write failed: "); + future.cause().printStackTrace(System.err); } }); } diff --git a/example/src/main/java/io/netty/example/securechat/SecureChatServerHandler.java b/example/src/main/java/io/netty/example/securechat/SecureChatServerHandler.java index a40e1644f7..7e60b4b2f8 100644 --- a/example/src/main/java/io/netty/example/securechat/SecureChatServerHandler.java +++ b/example/src/main/java/io/netty/example/securechat/SecureChatServerHandler.java @@ -39,19 +39,16 @@ public class SecureChatServerHandler extends SimpleChannelInboundHandler // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener( - new GenericFutureListener>() { - @Override - public void operationComplete(Future future) throws Exception { - ctx.writeAndFlush( - "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); - ctx.writeAndFlush( - "Your session is protected by " + - ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + - " cipher suite.\n"); + (GenericFutureListener>) future -> { + ctx.writeAndFlush( + "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); + ctx.writeAndFlush( + "Your session is protected by " + + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + + " cipher suite.\n"); - channels.add(ctx.channel()); - } - }); + channels.add(ctx.channel()); + }); } @Override diff --git a/example/src/main/java/io/netty/example/socksproxy/SocksServerConnectHandler.java b/example/src/main/java/io/netty/example/socksproxy/SocksServerConnectHandler.java index 890e8c08fa..01fa62536a 100644 --- a/example/src/main/java/io/netty/example/socksproxy/SocksServerConnectHandler.java +++ b/example/src/main/java/io/netty/example/socksproxy/SocksServerConnectHandler.java @@ -46,27 +46,21 @@ public final class SocksServerConnectHandler extends SimpleChannelInboundHandler final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise promise = ctx.executor().newPromise(); promise.addListener( - new FutureListener() { - @Override - public void operationComplete(final Future future) throws Exception { - final Channel outboundChannel = future.getNow(); - if (future.isSuccess()) { - ChannelFuture responseFuture = ctx.channel().writeAndFlush( - new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); + (FutureListener) future -> { + final Channel outboundChannel = future.getNow(); + if (future.isSuccess()) { + ChannelFuture responseFuture = ctx.channel().writeAndFlush( + new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); - responseFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture channelFuture) { - ctx.pipeline().remove(SocksServerConnectHandler.this); - outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); - ctx.pipeline().addLast(new RelayHandler(outboundChannel)); - } - }); - } else { - ctx.channel().writeAndFlush( - new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); - SocksServerUtils.closeOnFlush(ctx.channel()); - } + responseFuture.addListener((ChannelFutureListener) channelFuture -> { + ctx.pipeline().remove(SocksServerConnectHandler.this); + outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); + ctx.pipeline().addLast(new RelayHandler(outboundChannel)); + }); + } else { + ctx.channel().writeAndFlush( + new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); + SocksServerUtils.closeOnFlush(ctx.channel()); } }); @@ -77,49 +71,40 @@ public final class SocksServerConnectHandler extends SimpleChannelInboundHandler .option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); - b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isSuccess()) { - // Connection established use handler provided results - } else { - // Close the connection if the connection attempt has failed. - ctx.channel().writeAndFlush( - new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED) - ); - SocksServerUtils.closeOnFlush(ctx.channel()); - } + b.connect(request.dstAddr(), request.dstPort()).addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + // Connection established use handler provided results + } else { + // Close the connection if the connection attempt has failed. + ctx.channel().writeAndFlush( + new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED) + ); + SocksServerUtils.closeOnFlush(ctx.channel()); } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise promise = ctx.executor().newPromise(); promise.addListener( - new FutureListener() { - @Override - public void operationComplete(final Future future) throws Exception { - final Channel outboundChannel = future.getNow(); - if (future.isSuccess()) { - ChannelFuture responseFuture = - ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( - Socks5CommandStatus.SUCCESS, - request.dstAddrType(), - request.dstAddr(), - request.dstPort())); + (FutureListener) future -> { + final Channel outboundChannel = future.getNow(); + if (future.isSuccess()) { + ChannelFuture responseFuture = + ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( + Socks5CommandStatus.SUCCESS, + request.dstAddrType(), + request.dstAddr(), + request.dstPort())); - responseFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture channelFuture) { - ctx.pipeline().remove(SocksServerConnectHandler.this); - outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); - ctx.pipeline().addLast(new RelayHandler(outboundChannel)); - } - }); - } else { - ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( - Socks5CommandStatus.FAILURE, request.dstAddrType())); - SocksServerUtils.closeOnFlush(ctx.channel()); - } + responseFuture.addListener((ChannelFutureListener) channelFuture -> { + ctx.pipeline().remove(SocksServerConnectHandler.this); + outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); + ctx.pipeline().addLast(new RelayHandler(outboundChannel)); + }); + } else { + ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( + Socks5CommandStatus.FAILURE, request.dstAddrType())); + SocksServerUtils.closeOnFlush(ctx.channel()); } }); @@ -130,17 +115,14 @@ public final class SocksServerConnectHandler extends SimpleChannelInboundHandler .option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); - b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isSuccess()) { - // Connection established use handler provided results - } else { - // Close the connection if the connection attempt has failed. - ctx.channel().writeAndFlush( - new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); - SocksServerUtils.closeOnFlush(ctx.channel()); - } + b.connect(request.dstAddr(), request.dstPort()).addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + // Connection established use handler provided results + } else { + // Close the connection if the connection attempt has failed. + ctx.channel().writeAndFlush( + new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); + SocksServerUtils.closeOnFlush(ctx.channel()); } }); } else { diff --git a/example/src/main/java/io/netty/example/uptime/UptimeClient.java b/example/src/main/java/io/netty/example/uptime/UptimeClient.java index 3ea3f4f2c8..5d804aa89e 100644 --- a/example/src/main/java/io/netty/example/uptime/UptimeClient.java +++ b/example/src/main/java/io/netty/example/uptime/UptimeClient.java @@ -59,13 +59,10 @@ public final class UptimeClient { } static void connect() { - bs.connect().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.cause() != null) { - handler.startTime = -1; - handler.println("Failed to connect: " + future.cause()); - } + bs.connect().addListener((ChannelFutureListener) future -> { + if (future.cause() != null) { + handler.startTime = -1; + handler.println("Failed to connect: " + future.cause()); } }); } diff --git a/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java b/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java index 3ad89bd7ce..40b18ec2f3 100644 --- a/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java +++ b/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java @@ -68,12 +68,9 @@ public class UptimeClientHandler extends SimpleChannelInboundHandler { public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception { println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + 's'); - ctx.channel().eventLoop().schedule(new Runnable() { - @Override - public void run() { - println("Reconnecting to: " + UptimeClient.HOST + ':' + UptimeClient.PORT); - UptimeClient.connect(); - } + ctx.channel().eventLoop().schedule(() -> { + println("Reconnecting to: " + UptimeClient.HOST + ':' + UptimeClient.PORT); + UptimeClient.connect(); }, UptimeClient.RECONNECT_DELAY, TimeUnit.SECONDS); } diff --git a/handler-proxy/src/main/java/io/netty/handler/proxy/ProxyHandler.java b/handler-proxy/src/main/java/io/netty/handler/proxy/ProxyHandler.java index 8d3271ea7f..27baca0c45 100644 --- a/handler-proxy/src/main/java/io/netty/handler/proxy/ProxyHandler.java +++ b/handler-proxy/src/main/java/io/netty/handler/proxy/ProxyHandler.java @@ -60,12 +60,9 @@ public abstract class ProxyHandler extends ChannelDuplexHandler { private boolean flushedPrematurely; private final LazyChannelPromise connectPromise = new LazyChannelPromise(); private ScheduledFuture connectTimeoutFuture; - private final ChannelFutureListener writeListener = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - setConnectFailure(future.cause()); - } + private final ChannelFutureListener writeListener = future -> { + if (!future.isSuccess()) { + setConnectFailure(future.cause()); } }; @@ -194,12 +191,9 @@ public abstract class ProxyHandler extends ChannelDuplexHandler { private void sendInitialMessage(final ChannelHandlerContext ctx) throws Exception { final long connectTimeoutMillis = this.connectTimeoutMillis; if (connectTimeoutMillis > 0) { - connectTimeoutFuture = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - if (!connectPromise.isDone()) { - setConnectFailure(new ProxyConnectException(exceptionMessage("timeout"))); - } + connectTimeoutFuture = ctx.executor().schedule(() -> { + if (!connectPromise.isDone()) { + setConnectFailure(new ProxyConnectException(exceptionMessage("timeout"))); } }, connectTimeoutMillis, TimeUnit.MILLISECONDS); } diff --git a/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyHandlerTest.java b/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyHandlerTest.java index f1ee543561..0dd3a0cf17 100644 --- a/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyHandlerTest.java +++ b/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyHandlerTest.java @@ -521,14 +521,11 @@ public class ProxyHandlerTest { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer("A\n", CharsetUtil.US_ASCII)).addListener( - new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - latch.countDown(); - if (!(future.cause() instanceof ProxyConnectException)) { - exceptions.add(new AssertionError( - "Unexpected failure cause for initial write: " + future.cause())); - } + (ChannelFutureListener) future -> { + latch.countDown(); + if (!(future.cause() instanceof ProxyConnectException)) { + exceptions.add(new AssertionError( + "Unexpected failure cause for initial write: " + future.cause())); } }); } diff --git a/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyServer.java b/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyServer.java index e305b9d0f3..c2122684a1 100644 --- a/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyServer.java +++ b/handler-proxy/src/test/java/io/netty/handler/proxy/ProxyServer.java @@ -169,16 +169,13 @@ abstract class ProxyServer { if (finished) { this.finished = true; ChannelFuture f = connectToDestination(ctx.channel().eventLoop(), new BackendHandler(ctx)); - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - recordException(future.cause()); - ctx.close(); - } else { - backend = future.channel(); - flush(); - } + f.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + recordException(future.cause()); + ctx.close(); + } else { + backend = future.channel(); + flush(); } }); } diff --git a/handler/src/main/java/io/netty/handler/flush/FlushConsolidationHandler.java b/handler/src/main/java/io/netty/handler/flush/FlushConsolidationHandler.java index 472a83bffc..54c59c19bf 100644 --- a/handler/src/main/java/io/netty/handler/flush/FlushConsolidationHandler.java +++ b/handler/src/main/java/io/netty/handler/flush/FlushConsolidationHandler.java @@ -102,15 +102,12 @@ public class FlushConsolidationHandler extends ChannelDuplexHandler { this.explicitFlushAfterFlushes = explicitFlushAfterFlushes; this.consolidateWhenNoReadInProgress = consolidateWhenNoReadInProgress; flushTask = consolidateWhenNoReadInProgress ? - new Runnable() { - @Override - public void run() { - if (flushPendingCount > 0 && !readInProgress) { - flushPendingCount = 0; - ctx.flush(); - nextScheduledFlush = null; - } // else we'll flush when the read completes - } + () -> { + if (flushPendingCount > 0 && !readInProgress) { + flushPendingCount = 0; + ctx.flush(); + nextScheduledFlush = null; + } // else we'll flush when the read completes } : null; } diff --git a/handler/src/main/java/io/netty/handler/ipfilter/UniqueIpFilter.java b/handler/src/main/java/io/netty/handler/ipfilter/UniqueIpFilter.java index fcd6b08a87..92e1a54ea2 100644 --- a/handler/src/main/java/io/netty/handler/ipfilter/UniqueIpFilter.java +++ b/handler/src/main/java/io/netty/handler/ipfilter/UniqueIpFilter.java @@ -41,12 +41,7 @@ public class UniqueIpFilter extends AbstractRemoteAddressFilter connected.remove(remoteIp)); return true; } } diff --git a/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java b/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java index 71e529a3c3..7b16535dcb 100644 --- a/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java @@ -229,26 +229,23 @@ public abstract class AbstractSniHandler extends ByteToMessageDecoder impleme onLookupComplete(ctx, hostname, future); } else { suppressRead = true; - future.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { + future.addListener((FutureListener) future1 -> { + try { + suppressRead = false; try { - suppressRead = false; - try { - fireSniCompletionEvent(ctx, hostname, future); - onLookupComplete(ctx, hostname, future); - } catch (DecoderException err) { - ctx.fireExceptionCaught(err); - } catch (Exception cause) { - ctx.fireExceptionCaught(new DecoderException(cause)); - } catch (Throwable cause) { - ctx.fireExceptionCaught(cause); - } - } finally { - if (readPending) { - readPending = false; - ctx.read(); - } + fireSniCompletionEvent(ctx, hostname, future1); + onLookupComplete(ctx, hostname, future1); + } catch (DecoderException err) { + ctx.fireExceptionCaught(err); + } catch (Exception cause) { + ctx.fireExceptionCaught(new DecoderException(cause)); + } catch (Throwable cause) { + ctx.fireExceptionCaught(cause); + } + } finally { + if (readPending) { + readPending = false; + ctx.read(); } } }); diff --git a/handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java b/handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java index 2fd3bbcd64..288dd7adfd 100644 --- a/handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java +++ b/handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java @@ -49,50 +49,26 @@ final class Java9SslUtils { SSLContext context = SSLContext.getInstance(JdkSslContext.PROTOCOL); context.init(null, null, null); SSLEngine engine = context.createSSLEngine(); - getHandshakeApplicationProtocol = AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Method run() throws Exception { - return SSLEngine.class.getMethod("getHandshakeApplicationProtocol"); - } - }); + getHandshakeApplicationProtocol = AccessController.doPrivileged((PrivilegedExceptionAction) () -> + SSLEngine.class.getMethod("getHandshakeApplicationProtocol")); getHandshakeApplicationProtocol.invoke(engine); - getApplicationProtocol = AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Method run() throws Exception { - return SSLEngine.class.getMethod("getApplicationProtocol"); - } - }); + getApplicationProtocol = AccessController.doPrivileged((PrivilegedExceptionAction) () -> + SSLEngine.class.getMethod("getApplicationProtocol")); getApplicationProtocol.invoke(engine); - setApplicationProtocols = AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Method run() throws Exception { - return SSLParameters.class.getMethod("setApplicationProtocols", String[].class); - } - }); + setApplicationProtocols = AccessController.doPrivileged((PrivilegedExceptionAction) () -> + SSLParameters.class.getMethod("setApplicationProtocols", String[].class)); setApplicationProtocols.invoke(engine.getSSLParameters(), new Object[]{EmptyArrays.EMPTY_STRINGS}); setHandshakeApplicationProtocolSelector = - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Method run() throws Exception { - return SSLEngine.class.getMethod("setHandshakeApplicationProtocolSelector", BiFunction.class); - } - }); - setHandshakeApplicationProtocolSelector.invoke(engine, new BiFunction, String>() { - @Override - public String apply(SSLEngine sslEngine, List strings) { - return null; - } - }); + AccessController.doPrivileged((PrivilegedExceptionAction) () -> + SSLEngine.class.getMethod("setHandshakeApplicationProtocolSelector", BiFunction.class)); + setHandshakeApplicationProtocolSelector.invoke(engine, + (BiFunction, String>) (sslEngine, strings) -> null); getHandshakeApplicationProtocolSelector = - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Method run() throws Exception { - return SSLEngine.class.getMethod("getHandshakeApplicationProtocolSelector"); - } - }); + AccessController.doPrivileged((PrivilegedExceptionAction) () -> + SSLEngine.class.getMethod("getHandshakeApplicationProtocolSelector")); getHandshakeApplicationProtocolSelector.invoke(engine); } catch (Throwable t) { logger.error("Unable to initialize Java9SslUtils, but the detected javaVersion was: {}", diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java b/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java index 068c494601..4f302ad54f 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java +++ b/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java @@ -96,35 +96,17 @@ class JdkBaseApplicationProtocolNegotiator implements JdkApplicationProtocolNego return wrapperFactory; } - static final ProtocolSelectorFactory FAIL_SELECTOR_FACTORY = new ProtocolSelectorFactory() { - @Override - public ProtocolSelector newSelector(SSLEngine engine, Set supportedProtocols) { - return new FailProtocolSelector((JdkSslEngine) engine, supportedProtocols); - } - }; + static final ProtocolSelectorFactory FAIL_SELECTOR_FACTORY = (engine, supportedProtocols) -> + new FailProtocolSelector((JdkSslEngine) engine, supportedProtocols); - static final ProtocolSelectorFactory NO_FAIL_SELECTOR_FACTORY = new ProtocolSelectorFactory() { - @Override - public ProtocolSelector newSelector(SSLEngine engine, Set supportedProtocols) { - return new NoFailProtocolSelector((JdkSslEngine) engine, supportedProtocols); - } - }; + static final ProtocolSelectorFactory NO_FAIL_SELECTOR_FACTORY = (engine, supportedProtocols) -> + new NoFailProtocolSelector((JdkSslEngine) engine, supportedProtocols); - static final ProtocolSelectionListenerFactory FAIL_SELECTION_LISTENER_FACTORY = - new ProtocolSelectionListenerFactory() { - @Override - public ProtocolSelectionListener newListener(SSLEngine engine, List supportedProtocols) { - return new FailProtocolSelectionListener((JdkSslEngine) engine, supportedProtocols); - } - }; + static final ProtocolSelectionListenerFactory FAIL_SELECTION_LISTENER_FACTORY = (engine, supportedProtocols) -> + new FailProtocolSelectionListener((JdkSslEngine) engine, supportedProtocols); - static final ProtocolSelectionListenerFactory NO_FAIL_SELECTION_LISTENER_FACTORY = - new ProtocolSelectionListenerFactory() { - @Override - public ProtocolSelectionListener newListener(SSLEngine engine, List supportedProtocols) { - return new NoFailProtocolSelectionListener((JdkSslEngine) engine, supportedProtocols); - } - }; + static final ProtocolSelectionListenerFactory NO_FAIL_SELECTION_LISTENER_FACTORY = (engine, supportedProtocols) -> + new NoFailProtocolSelectionListener((JdkSslEngine) engine, supportedProtocols); static class NoFailProtocolSelector implements ProtocolSelector { private final JdkSslEngine engineWrapper; diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkDefaultApplicationProtocolNegotiator.java b/handler/src/main/java/io/netty/handler/ssl/JdkDefaultApplicationProtocolNegotiator.java index c380185631..83bb8cae36 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JdkDefaultApplicationProtocolNegotiator.java +++ b/handler/src/main/java/io/netty/handler/ssl/JdkDefaultApplicationProtocolNegotiator.java @@ -27,13 +27,8 @@ import javax.net.ssl.SSLEngine; final class JdkDefaultApplicationProtocolNegotiator implements JdkApplicationProtocolNegotiator { public static final JdkDefaultApplicationProtocolNegotiator INSTANCE = new JdkDefaultApplicationProtocolNegotiator(); - private static final SslEngineWrapperFactory DEFAULT_SSL_ENGINE_WRAPPER_FACTORY = new SslEngineWrapperFactory() { - @Override - public SSLEngine wrapSslEngine(SSLEngine engine, - JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) { - return engine; - } - }; + private static final SslEngineWrapperFactory DEFAULT_SSL_ENGINE_WRAPPER_FACTORY = + (engine, applicationNegotiator, isServer) -> engine; private JdkDefaultApplicationProtocolNegotiator() { } diff --git a/handler/src/main/java/io/netty/handler/ssl/OpenSsl.java b/handler/src/main/java/io/netty/handler/ssl/OpenSsl.java index fa7f33a4b8..3effdb6c25 100644 --- a/handler/src/main/java/io/netty/handler/ssl/OpenSsl.java +++ b/handler/src/main/java/io/netty/handler/ssl/OpenSsl.java @@ -200,13 +200,9 @@ public final class OpenSsl { SSL.setCertificateChainBio(ssl, certBio, false); supportsKeyManagerFactory = true; try { - useKeyManagerFactory = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - return SystemPropertyUtil.getBoolean( - "io.netty.handler.ssl.openssl.useKeyManagerFactory", true); - } - }); + useKeyManagerFactory = AccessController.doPrivileged((PrivilegedAction) () -> + SystemPropertyUtil.getBoolean( + "io.netty.handler.ssl.openssl.useKeyManagerFactory", true)); } catch (Throwable ignore) { logger.debug("Failed to get useKeyManagerFactory system property."); } diff --git a/handler/src/main/java/io/netty/handler/ssl/OpenSslX509TrustManagerWrapper.java b/handler/src/main/java/io/netty/handler/ssl/OpenSslX509TrustManagerWrapper.java index 6261c1801d..c888e73c8c 100644 --- a/handler/src/main/java/io/netty/handler/ssl/OpenSslX509TrustManagerWrapper.java +++ b/handler/src/main/java/io/netty/handler/ssl/OpenSslX509TrustManagerWrapper.java @@ -46,12 +46,7 @@ final class OpenSslX509TrustManagerWrapper { static { // By default we will not do any wrapping but just return the passed in manager. - TrustManagerWrapper wrapper = new TrustManagerWrapper() { - @Override - public X509TrustManager wrapIfNeeded(X509TrustManager manager) { - return manager; - } - }; + TrustManagerWrapper wrapper = manager -> manager; Throwable cause = null; Throwable unsafeCause = PlatformDependent.getUnsafeUnavailabilityCause(); @@ -92,36 +87,33 @@ final class OpenSslX509TrustManagerWrapper { LOGGER.debug("Unable to access wrapped TrustManager", cause); } else { final SSLContext finalContext = context; - Object maybeWrapper = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - try { - Field contextSpiField = SSLContext.class.getDeclaredField("contextSpi"); - final long spiOffset = PlatformDependent.objectFieldOffset(contextSpiField); - Object spi = PlatformDependent.getObject(finalContext, spiOffset); - if (spi != null) { - Class clazz = spi.getClass(); + Object maybeWrapper = AccessController.doPrivileged((PrivilegedAction) () -> { + try { + Field contextSpiField = SSLContext.class.getDeclaredField("contextSpi"); + final long spiOffset = PlatformDependent.objectFieldOffset(contextSpiField); + Object spi = PlatformDependent.getObject(finalContext, spiOffset); + if (spi != null) { + Class clazz = spi.getClass(); - // Let's cycle through the whole hierarchy until we find what we are looking for or - // there is nothing left in which case we will not wrap at all. - do { - try { - Field trustManagerField = clazz.getDeclaredField("trustManager"); - final long tmOffset = PlatformDependent.objectFieldOffset(trustManagerField); - Object trustManager = PlatformDependent.getObject(spi, tmOffset); - if (trustManager instanceof X509ExtendedTrustManager) { - return new UnsafeTrustManagerWrapper(spiOffset, tmOffset); - } - } catch (NoSuchFieldException ignore) { - // try next + // Let's cycle through the whole hierarchy until we find what we are looking for or + // there is nothing left in which case we will not wrap at all. + do { + try { + Field trustManagerField = clazz.getDeclaredField("trustManager"); + final long tmOffset = PlatformDependent.objectFieldOffset(trustManagerField); + Object trustManager = PlatformDependent.getObject(spi, tmOffset); + if (trustManager instanceof X509ExtendedTrustManager) { + return new UnsafeTrustManagerWrapper(spiOffset, tmOffset); } - clazz = clazz.getSuperclass(); - } while (clazz != null); - } - throw new NoSuchFieldException(); - } catch (NoSuchFieldException | SecurityException e) { - return e; + } catch (NoSuchFieldException ignore) { + // try next + } + clazz = clazz.getSuperclass(); + } while (clazz != null); } + throw new NoSuchFieldException(); + } catch (NoSuchFieldException | SecurityException e) { + return e; } }); if (maybeWrapper instanceof Throwable) { diff --git a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java index d6354841a6..2bc714c81a 100644 --- a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java +++ b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java @@ -77,14 +77,9 @@ public abstract class ReferenceCountedOpenSslContext extends SslContext implemen InternalLoggerFactory.getInstance(ReferenceCountedOpenSslContext.class); private static final int DEFAULT_BIO_NON_APPLICATION_BUFFER_SIZE = - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Integer run() { - return Math.max(1, - SystemPropertyUtil.getInt("io.netty.handler.ssl.openssl.bioNonApplicationBufferSize", - 2048)); - } - }); + AccessController.doPrivileged((PrivilegedAction) () -> Math.max(1, + SystemPropertyUtil.getInt("io.netty.handler.ssl.openssl.bioNonApplicationBufferSize", + 2048))); private static final Integer DH_KEY_LENGTH; private static final ResourceLeakDetector leakDetector = @@ -164,12 +159,8 @@ public abstract class ReferenceCountedOpenSslContext extends SslContext implemen Integer dhLen = null; try { - String dhKeySize = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public String run() { - return SystemPropertyUtil.get("jdk.tls.ephemeralDHKeySize"); - } - }); + String dhKeySize = AccessController.doPrivileged((PrivilegedAction) () -> + SystemPropertyUtil.get("jdk.tls.ephemeralDHKeySize")); if (dhKeySize != null) { try { dhLen = Integer.valueOf(dhKeySize); diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index 305298aded..4f1de233c7 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -659,12 +659,7 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH if (ctx.executor().inEventLoop()) { closeOutbound0(promise); } else { - ctx.executor().execute(new Runnable() { - @Override - public void run() { - closeOutbound0(promise); - } - }); + ctx.executor().execute(() -> closeOutbound0(promise)); } return promise; } @@ -1483,18 +1478,15 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH } final CountDownLatch latch = new CountDownLatch(1); - delegatedTaskExecutor.execute(new Runnable() { - @Override - public void run() { - try { - for (Runnable task: tasks) { - task.run(); - } - } catch (Exception e) { - ctx.fireExceptionCaught(e); - } finally { - latch.countDown(); + delegatedTaskExecutor.execute(() -> { + try { + for (Runnable task: tasks) { + task.run(); } + } catch (Exception e) { + ctx.fireExceptionCaught(e); + } finally { + latch.countDown(); } }); @@ -1640,12 +1632,7 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH new ChannelPromiseNotifier(false, promise))); } else { /// We already handling the close_notify so just attach the promise to the sslClosePromise. - sslClosePromise.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) { - promise.setSuccess(); - } - }); + sslClosePromise.addListener((FutureListener) future -> promise.setSuccess()); } } } @@ -1709,12 +1696,7 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH EventExecutor executor = ctx.executor(); if (!executor.inEventLoop()) { - executor.execute(new Runnable() { - @Override - public void run() { - renegotiateOnEventLoop(promise); - } - }); + executor.execute(() -> renegotiateOnEventLoop(promise)); return promise; } @@ -1775,29 +1757,21 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH return; } - final ScheduledFuture timeoutFuture = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - if (localHandshakePromise.isDone()) { - return; - } - try { - if (localHandshakePromise.tryFailure(HANDSHAKE_TIMED_OUT)) { - SslUtils.handleHandshakeFailure(ctx, HANDSHAKE_TIMED_OUT, true); - } - } finally { - releaseAndFailAll(HANDSHAKE_TIMED_OUT); + final ScheduledFuture timeoutFuture = ctx.executor().schedule(() -> { + if (localHandshakePromise.isDone()) { + return; + } + try { + if (localHandshakePromise.tryFailure(HANDSHAKE_TIMED_OUT)) { + SslUtils.handleHandshakeFailure(ctx, HANDSHAKE_TIMED_OUT, true); } + } finally { + releaseAndFailAll(HANDSHAKE_TIMED_OUT); } }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS); // Cancel the handshake timeout when handshake is finished. - localHandshakePromise.addListener(new FutureListener() { - @Override - public void operationComplete(Future f) throws Exception { - timeoutFuture.cancel(false); - } - }); + localHandshakePromise.addListener((FutureListener) f -> timeoutFuture.cancel(false)); } private void forceFlush(ChannelHandlerContext ctx) { @@ -1829,15 +1803,12 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH long closeNotifyTimeout = closeNotifyFlushTimeoutMillis; if (closeNotifyTimeout > 0) { // Force-close the connection if close_notify is not fully sent in time. - timeoutFuture = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - // May be done in the meantime as cancel(...) is only best effort. - if (!flushFuture.isDone()) { - logger.warn("{} Last write attempt timed out; force-closing the connection.", - ctx.channel()); - addCloseListener(ctx.close(ctx.newPromise()), promise); - } + timeoutFuture = ctx.executor().schedule(() -> { + // May be done in the meantime as cancel(...) is only best effort. + if (!flushFuture.isDone()) { + logger.warn("{} Last write attempt timed out; force-closing the connection.", + ctx.channel()); + addCloseListener(ctx.close(ctx.newPromise()), promise); } }, closeNotifyTimeout, TimeUnit.MILLISECONDS); } else { @@ -1848,50 +1819,40 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH } // Close the connection if close_notify is sent in time. - flushFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture f) - throws Exception { - if (timeoutFuture != null) { - timeoutFuture.cancel(false); - } - final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis; - if (closeNotifyReadTimeout <= 0) { - // Trigger the close in all cases to make sure the promise is notified - // See https://github.com/netty/netty/issues/2358 - addCloseListener(ctx.close(ctx.newPromise()), promise); - } else { - final ScheduledFuture closeNotifyReadTimeoutFuture; + flushFuture.addListener((ChannelFutureListener) f -> { + if (timeoutFuture != null) { + timeoutFuture.cancel(false); + } + final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis; + if (closeNotifyReadTimeout <= 0) { + // Trigger the close in all cases to make sure the promise is notified + // See https://github.com/netty/netty/issues/2358 + addCloseListener(ctx.close(ctx.newPromise()), promise); + } else { + final ScheduledFuture closeNotifyReadTimeoutFuture; - if (!sslClosePromise.isDone()) { - closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - if (!sslClosePromise.isDone()) { - logger.debug( - "{} did not receive close_notify in {}ms; force-closing the connection.", - ctx.channel(), closeNotifyReadTimeout); + if (!sslClosePromise.isDone()) { + closeNotifyReadTimeoutFuture = ctx.executor().schedule(() -> { + if (!sslClosePromise.isDone()) { + logger.debug( + "{} did not receive close_notify in {}ms; force-closing the connection.", + ctx.channel(), closeNotifyReadTimeout); - // Do the close now... - addCloseListener(ctx.close(ctx.newPromise()), promise); - } - } - }, closeNotifyReadTimeout, TimeUnit.MILLISECONDS); - } else { - closeNotifyReadTimeoutFuture = null; - } - - // Do the close once the we received the close_notify. - sslClosePromise.addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - if (closeNotifyReadTimeoutFuture != null) { - closeNotifyReadTimeoutFuture.cancel(false); - } + // Do the close now... addCloseListener(ctx.close(ctx.newPromise()), promise); } - }); + }, closeNotifyReadTimeout, TimeUnit.MILLISECONDS); + } else { + closeNotifyReadTimeoutFuture = null; } + + // Do the close once the we received the close_notify. + sslClosePromise.addListener((FutureListener) future -> { + if (closeNotifyReadTimeoutFuture != null) { + closeNotifyReadTimeoutFuture.cancel(false); + } + addCloseListener(ctx.close(ctx.newPromise()), promise); + }); } }); } diff --git a/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java b/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java index 47569e1b14..9bf44f556f 100644 --- a/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java +++ b/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java @@ -105,13 +105,7 @@ public class ChunkedWriteHandler extends ChannelDuplexHandler { resumeTransfer0(ctx); } else { // let the transfer resume on the next event loop round - ctx.executor().execute(new Runnable() { - - @Override - public void run() { - resumeTransfer0(ctx); - } - }); + ctx.executor().execute(() -> resumeTransfer0(ctx)); } } @@ -276,42 +270,33 @@ public class ChunkedWriteHandler extends ChannelDuplexHandler { // be closed before its not written. // // See https://github.com/netty/netty/issues/303 - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - closeInput(chunks); - currentWrite.fail(future.cause()); - } else { - currentWrite.progress(chunks.progress(), chunks.length()); - currentWrite.success(chunks.length()); - } + f.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + closeInput(chunks); + currentWrite.fail(future.cause()); + } else { + currentWrite.progress(chunks.progress(), chunks.length()); + currentWrite.success(chunks.length()); } }); } else if (channel.isWritable()) { - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - closeInput((ChunkedInput) pendingMessage); - currentWrite.fail(future.cause()); - } else { - currentWrite.progress(chunks.progress(), chunks.length()); - } + f.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + closeInput((ChunkedInput) pendingMessage); + currentWrite.fail(future.cause()); + } else { + currentWrite.progress(chunks.progress(), chunks.length()); } }); } else { - f.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - closeInput((ChunkedInput) pendingMessage); - currentWrite.fail(future.cause()); - } else { - currentWrite.progress(chunks.progress(), chunks.length()); - if (channel.isWritable()) { - resumeTransfer(); - } + f.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + closeInput((ChunkedInput) pendingMessage); + currentWrite.fail(future.cause()); + } else { + currentWrite.progress(chunks.progress(), chunks.length()); + if (channel.isWritable()) { + resumeTransfer(); } } }); diff --git a/handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java b/handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java index bdf7aee9a2..617b0457cd 100644 --- a/handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java +++ b/handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java @@ -192,12 +192,7 @@ public class ChannelTrafficShapingHandler extends AbstractTrafficShapingHandler checkWriteSuspend(ctx, delay, queueSize); } final long futureNow = newToSend.relativeTimeAction; - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - sendAllValid(ctx, futureNow); - } - }, delay, TimeUnit.MILLISECONDS); + ctx.executor().schedule(() -> sendAllValid(ctx, futureNow), delay, TimeUnit.MILLISECONDS); } private void sendAllValid(final ChannelHandlerContext ctx, final long now) { diff --git a/handler/src/main/java/io/netty/handler/traffic/GlobalChannelTrafficShapingHandler.java b/handler/src/main/java/io/netty/handler/traffic/GlobalChannelTrafficShapingHandler.java index f426be8197..d4a921f095 100644 --- a/handler/src/main/java/io/netty/handler/traffic/GlobalChannelTrafficShapingHandler.java +++ b/handler/src/main/java/io/netty/handler/traffic/GlobalChannelTrafficShapingHandler.java @@ -734,12 +734,7 @@ public class GlobalChannelTrafficShapingHandler extends AbstractTrafficShapingHa } final long futureNow = newToSend.relativeTimeAction; final PerChannel forSchedule = perChannel; - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - sendAllValid(ctx, forSchedule, futureNow); - } - }, delay, TimeUnit.MILLISECONDS); + ctx.executor().schedule(() -> sendAllValid(ctx, forSchedule, futureNow), delay, TimeUnit.MILLISECONDS); } private void sendAllValid(final ChannelHandlerContext ctx, final PerChannel perChannel, final long now) { diff --git a/handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java b/handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java index 7a7638d5ce..29b72bc22d 100644 --- a/handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java +++ b/handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java @@ -365,12 +365,7 @@ public class GlobalTrafficShapingHandler extends AbstractTrafficShapingHandler { } final long futureNow = newToSend.relativeTimeAction; final PerChannel forSchedule = perChannel; - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - sendAllValid(ctx, forSchedule, futureNow); - } - }, delay, TimeUnit.MILLISECONDS); + ctx.executor().schedule(() -> sendAllValid(ctx, forSchedule, futureNow), delay, TimeUnit.MILLISECONDS); } private void sendAllValid(final ChannelHandlerContext ctx, final PerChannel perChannel, final long now) { diff --git a/handler/src/test/java/io/netty/handler/ipfilter/UniqueIpFilterTest.java b/handler/src/test/java/io/netty/handler/ipfilter/UniqueIpFilterTest.java index 6e9eb66f3e..bbd4a703e0 100644 --- a/handler/src/test/java/io/netty/handler/ipfilter/UniqueIpFilterTest.java +++ b/handler/src/test/java/io/netty/handler/ipfilter/UniqueIpFilterTest.java @@ -57,17 +57,14 @@ public class UniqueIpFilterTest { private static Future newChannelAsync(final CyclicBarrier barrier, ExecutorService executorService, final ChannelHandler... handler) { - return executorService.submit(new Callable() { - @Override - public EmbeddedChannel call() throws Exception { - barrier.await(); - return new EmbeddedChannel(handler) { - @Override - protected SocketAddress remoteAddress0() { - return isActive() ? SocketUtils.socketAddress("91.92.93.1", 5421) : null; - } - }; - } + return executorService.submit(() -> { + barrier.await(); + return new EmbeddedChannel(handler) { + @Override + protected SocketAddress remoteAddress0() { + return isActive() ? SocketUtils.socketAddress("91.92.93.1", 5421) : null; + } + }; }); } diff --git a/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java b/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java index 58408650c6..ad2ca68b35 100644 --- a/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java @@ -215,21 +215,16 @@ public class JdkSslEngineTest extends SSLEngineTest { JdkApplicationProtocolNegotiator clientApn = new JdkAlpnApplicationProtocolNegotiator(true, true, PREFERRED_APPLICATION_LEVEL_PROTOCOL); JdkApplicationProtocolNegotiator serverApn = new JdkAlpnApplicationProtocolNegotiator( - new ProtocolSelectorFactory() { - @Override - public ProtocolSelector newSelector(SSLEngine engine, Set supportedProtocols) { - return new ProtocolSelector() { - @Override - public void unsupported() { - } + (engine, supportedProtocols) -> new ProtocolSelector() { + @Override + public void unsupported() { + } - @Override - public String select(List protocols) { - return APPLICATION_LEVEL_PROTOCOL_NOT_COMPATIBLE; - } - }; - } - }, JdkBaseApplicationProtocolNegotiator.FAIL_SELECTION_LISTENER_FACTORY, + @Override + public String select(List protocols) { + return APPLICATION_LEVEL_PROTOCOL_NOT_COMPATIBLE; + } + }, JdkBaseApplicationProtocolNegotiator.FAIL_SELECTION_LISTENER_FACTORY, APPLICATION_LEVEL_PROTOCOL_NOT_COMPATIBLE); SslContext serverSslCtx = new JdkSslServerContext(providerType.provider(), diff --git a/handler/src/test/java/io/netty/handler/ssl/ParameterizedSslHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/ParameterizedSslHandlerTest.java index 799941850f..fdd7e1002d 100644 --- a/handler/src/test/java/io/netty/handler/ssl/ParameterizedSslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/ParameterizedSslHandlerTest.java @@ -169,13 +169,10 @@ public class ParameterizedSslHandlerTest { buf.writerIndex(buf.writerIndex() + singleComponentSize); content.addComponent(true, buf); } - ctx.writeAndFlush(content).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - writeCause = future.cause(); - if (writeCause == null) { - sentData = true; - } + ctx.writeAndFlush(content).addListener((ChannelFutureListener) future -> { + writeCause = future.cause(); + if (writeCause == null) { + sentData = true; } }); } else { @@ -415,13 +412,10 @@ public class ParameterizedSslHandlerTest { handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout); handler.sslCloseFuture().addListener( new PromiseNotifier<>(serverPromise)); - handler.handshakeFuture().addListener(new FutureListener() { - @Override - public void operationComplete(Future future) { - if (!future.isSuccess()) { - // Something bad happened during handshake fail the promise! - serverPromise.tryFailure(future.cause()); - } + handler.handshakeFuture().addListener((FutureListener) future -> { + if (!future.isSuccess()) { + // Something bad happened during handshake fail the promise! + serverPromise.tryFailure(future.cause()); } }); ch.pipeline().addLast(handler); @@ -454,16 +448,13 @@ public class ParameterizedSslHandlerTest { handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout); handler.sslCloseFuture().addListener( new PromiseNotifier<>(clientPromise)); - handler.handshakeFuture().addListener(new FutureListener() { - @Override - public void operationComplete(Future future) { - if (future.isSuccess()) { - closeSent.compareAndSet(false, true); - future.getNow().close(); - } else { - // Something bad happened during handshake fail the promise! - clientPromise.tryFailure(future.cause()); - } + handler.handshakeFuture().addListener((FutureListener) future -> { + if (future.isSuccess()) { + closeSent.compareAndSet(false, true); + future.getNow().close(); + } else { + // Something bad happened during handshake fail the promise! + clientPromise.tryFailure(future.cause()); } }); ch.pipeline().addLast(handler); diff --git a/handler/src/test/java/io/netty/handler/ssl/RenegotiateTest.java b/handler/src/test/java/io/netty/handler/ssl/RenegotiateTest.java index 6917ce2dab..40fde94558 100644 --- a/handler/src/test/java/io/netty/handler/ssl/RenegotiateTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/RenegotiateTest.java @@ -72,14 +72,11 @@ public abstract class RenegotiateTest { final SslHandler handler = ctx.pipeline().get(SslHandler.class); renegotiate = true; - handler.renegotiate().addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - if (!future.isSuccess()) { - error.compareAndSet(null, future.cause()); - latch.countDown(); - ctx.close(); - } + handler.renegotiate().addListener((FutureListener) future -> { + if (!future.isSuccess()) { + error.compareAndSet(null, future.cause()); + latch.countDown(); + ctx.close(); } }); } else { diff --git a/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java b/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java index f255b66bcd..e17f3e30df 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java @@ -1280,11 +1280,8 @@ public abstract class SSLEngineTest { // The server then attempts to trigger a flush operation once the application data is // received from the client. The flush will encrypt all data and should not result in // deadlock. - ctx.channel().eventLoop().schedule(new Runnable() { - @Override - public void run() { - ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(101)); - } + ctx.channel().eventLoop().schedule(() -> { + ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(101)); }, 500, TimeUnit.MILLISECONDS); } diff --git a/handler/src/test/java/io/netty/handler/ssl/SniClientTest.java b/handler/src/test/java/io/netty/handler/ssl/SniClientTest.java index 3dfb17b675..11b58d8cd9 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SniClientTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SniClientTest.java @@ -120,12 +120,9 @@ public class SniClientTest { sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { - ch.pipeline().addFirst(new SniHandler(new Mapping() { - @Override - public SslContext map(String input) { - promise.setSuccess(input); - return finalContext; - } + ch.pipeline().addFirst(new SniHandler(input -> { + promise.setSuccess(input); + return finalContext; })); } }).bind(address).syncUninterruptibly().channel(); diff --git a/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java index ff8b7dc150..16364aa078 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java @@ -432,12 +432,7 @@ public class SniHandlerTest { .sslProvider(provider) .build(); - final Mapping mapping = new Mapping() { - @Override - public SslContext map(String input) { - return sslServerContext; - } - }; + final Mapping mapping = input -> sslServerContext; final Promise releasePromise = group.next().newPromise(); diff --git a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java index ecbbeca9f5..521e2e7374 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java @@ -364,19 +364,11 @@ public class SslHandlerTest { final SslHandler sslHandler = sslCtx.newHandler(ch.alloc()); sslHandler.setHandshakeTimeoutMillis(1000); ch.pipeline().addFirst(sslHandler); - sslHandler.handshakeFuture().addListener(new FutureListener() { - @Override - public void operationComplete(final Future future) { - ch.pipeline().remove(sslHandler); + sslHandler.handshakeFuture().addListener((FutureListener) future -> { + ch.pipeline().remove(sslHandler); - // Schedule the close so removal has time to propagate exception if any. - ch.eventLoop().execute(new Runnable() { - @Override - public void run() { - ch.close(); - } - }); - } + // Schedule the close so removal has time to propagate exception if any. + ch.eventLoop().execute(ch::close); }); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @@ -466,12 +458,9 @@ public class SslHandlerTest { public void channelActive(ChannelHandlerContext ctx) { ByteBuf buf = ctx.alloc().buffer(10); buf.writeZero(buf.capacity()); - ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - events.add(future); - latch.countDown(); - } + ctx.writeAndFlush(buf).addListener((ChannelFutureListener) future -> { + events.add(future); + latch.countDown(); }); } @@ -723,12 +712,9 @@ public class SslHandlerTest { } }); } - }).connect(sc.localAddress()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - // Write something to trigger the handshake before fireChannelActive is called. - future.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); - } + }).connect(sc.localAddress()).addListener((ChannelFutureListener) future -> { + // Write something to trigger the handshake before fireChannelActive is called. + future.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); }).syncUninterruptibly().channel(); // Ensure there is no AssertionError thrown by having the handshake failed by the writeAndFlush(...) before @@ -801,12 +787,9 @@ public class SslHandlerTest { } }).connect(sc.localAddress()); if (!startTls) { - future.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - // Write something to trigger the handshake before fireChannelActive is called. - future.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); - } + future.addListener((ChannelFutureListener) future1 -> { + // Write something to trigger the handshake before fireChannelActive is called. + future1.channel().writeAndFlush(wrappedBuffer(new byte [] { 1, 2, 3, 4 })); }); } cc = future.syncUninterruptibly().channel(); diff --git a/handler/src/test/java/io/netty/handler/ssl/ocsp/OcspTest.java b/handler/src/test/java/io/netty/handler/ssl/ocsp/OcspTest.java index 1cc78db85b..e53cba0ea4 100644 --- a/handler/src/test/java/io/netty/handler/ssl/ocsp/OcspTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/ocsp/OcspTest.java @@ -315,11 +315,8 @@ public class OcspTest { final OcspTestException clientException = new OcspTestException("testClientException"); byte[] response = newOcspResponse(); - OcspClientCallback callback = new OcspClientCallback() { - @Override - public boolean verify(byte[] response) throws Exception { - throw clientException; - } + OcspClientCallback callback = response1 -> { + throw clientException; }; handshake(sslProvider, latch, null, response, clientHandler, callback); diff --git a/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java b/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java index 010ac0ecc7..d512083e99 100644 --- a/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java @@ -154,13 +154,7 @@ public class ChunkedWriteHandlerTest { }; final AtomicBoolean listenerNotified = new AtomicBoolean(false); - final ChannelFutureListener listener = new ChannelFutureListener() { - - @Override - public void operationComplete(ChannelFuture future) throws Exception { - listenerNotified.set(true); - } - }; + final ChannelFutureListener listener = future -> listenerNotified.set(true); EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler()); ch.writeAndFlush(input).addListener(listener).syncUninterruptibly(); diff --git a/handler/src/test/java/io/netty/handler/timeout/IdleStateHandlerTest.java b/handler/src/test/java/io/netty/handler/timeout/IdleStateHandlerTest.java index 5a54ec623d..7181b71282 100644 --- a/handler/src/test/java/io/netty/handler/timeout/IdleStateHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/timeout/IdleStateHandlerTest.java @@ -105,12 +105,7 @@ public class IdleStateHandlerTest { TestableIdleStateHandler idleStateHandler = new TestableIdleStateHandler( false, 1L, 0L, 0L, TimeUnit.SECONDS); - Action action = new Action() { - @Override - public void run(EmbeddedChannel channel) throws Exception { - channel.writeInbound("Hello, World!"); - } - }; + Action action = channel -> channel.writeInbound("Hello, World!"); anyNotIdle(idleStateHandler, action, IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT); } @@ -120,12 +115,7 @@ public class IdleStateHandlerTest { TestableIdleStateHandler idleStateHandler = new TestableIdleStateHandler( false, 0L, 1L, 0L, TimeUnit.SECONDS); - Action action = new Action() { - @Override - public void run(EmbeddedChannel channel) throws Exception { - channel.writeAndFlush("Hello, World!"); - } - }; + Action action = channel -> channel.writeAndFlush("Hello, World!"); anyNotIdle(idleStateHandler, action, IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT); } @@ -136,12 +126,7 @@ public class IdleStateHandlerTest { TestableIdleStateHandler idleStateHandler = new TestableIdleStateHandler( false, 0L, 0L, 1L, TimeUnit.SECONDS); - Action reader = new Action() { - @Override - public void run(EmbeddedChannel channel) throws Exception { - channel.writeInbound("Hello, World!"); - } - }; + Action reader = channel -> channel.writeInbound("Hello, World!"); anyNotIdle(idleStateHandler, reader, IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT); @@ -149,12 +134,7 @@ public class IdleStateHandlerTest { idleStateHandler = new TestableIdleStateHandler( false, 0L, 0L, 1L, TimeUnit.SECONDS); - Action writer = new Action() { - @Override - public void run(EmbeddedChannel channel) throws Exception { - channel.writeAndFlush("Hello, World!"); - } - }; + Action writer = channel -> channel.writeAndFlush("Hello, World!"); anyNotIdle(idleStateHandler, writer, IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT); } diff --git a/microbench/src/main/java/io/netty/buffer/CompositeByteBufSequentialBenchmark.java b/microbench/src/main/java/io/netty/buffer/CompositeByteBufSequentialBenchmark.java index d8c009c00b..7a4ce31d68 100644 --- a/microbench/src/main/java/io/netty/buffer/CompositeByteBufSequentialBenchmark.java +++ b/microbench/src/main/java/io/netty/buffer/CompositeByteBufSequentialBenchmark.java @@ -70,11 +70,8 @@ public class CompositeByteBufSequentialBenchmark extends AbstractMicrobenchmark buffer.release(); } - private static final ByteProcessor TEST_PROCESSOR = new ByteProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == 'b'; // false - } + private static final ByteProcessor TEST_PROCESSOR = value -> { + return value == 'b'; // false }; @Benchmark diff --git a/microbench/src/main/java/io/netty/microbench/channel/epoll/EpollSocketChannelBenchmark.java b/microbench/src/main/java/io/netty/microbench/channel/epoll/EpollSocketChannelBenchmark.java index a13dca9153..48439d29a6 100644 --- a/microbench/src/main/java/io/netty/microbench/channel/epoll/EpollSocketChannelBenchmark.java +++ b/microbench/src/main/java/io/netty/microbench/channel/epoll/EpollSocketChannelBenchmark.java @@ -48,11 +48,8 @@ public class EpollSocketChannelBenchmark extends AbstractMicrobenchmark { group = new MultithreadEventLoopGroup(1, EpollHandler.newFactory()); // add an arbitrary timeout to make the timer reschedule - future = group.schedule(new Runnable() { - @Override - public void run() { - throw new AssertionError(); - } + future = group.schedule((Runnable) () -> { + throw new AssertionError(); }, 5, TimeUnit.MINUTES); serverChan = new ServerBootstrap() .channel(EpollServerSocketChannel.class) diff --git a/microbench/src/main/java/io/netty/microbench/concurrent/BurstCostExecutorsBenchmark.java b/microbench/src/main/java/io/netty/microbench/concurrent/BurstCostExecutorsBenchmark.java index bd78a6c51e..ab305ec32c 100644 --- a/microbench/src/main/java/io/netty/microbench/concurrent/BurstCostExecutorsBenchmark.java +++ b/microbench/src/main/java/io/netty/microbench/concurrent/BurstCostExecutorsBenchmark.java @@ -62,10 +62,7 @@ public class BurstCostExecutorsBenchmark extends AbstractMicrobenchmark { */ private static final class SpinExecutorService implements ExecutorService { - private static final Runnable POISON_PILL = new Runnable() { - @Override - public void run() { - } + private static final Runnable POISON_PILL = () -> { }; private final Queue tasks; private final AtomicBoolean poisoned = new AtomicBoolean(); @@ -73,15 +70,12 @@ public class BurstCostExecutorsBenchmark extends AbstractMicrobenchmark { SpinExecutorService(int maxTasks) { tasks = PlatformDependent.newFixedMpscQueue(maxTasks); - executorThread = new Thread(new Runnable() { - @Override - public void run() { - final Queue tasks = SpinExecutorService.this.tasks; - Runnable task; - while ((task = tasks.poll()) != POISON_PILL) { - if (task != null) { - task.run(); - } + executorThread = new Thread(() -> { + final Queue tasks = SpinExecutorService.this.tasks; + Runnable task; + while ((task = tasks.poll()) != POISON_PILL) { + if (task != null) { + task.run(); } } }); @@ -255,27 +249,21 @@ public class BurstCostExecutorsBenchmark extends AbstractMicrobenchmark { public void setup(BurstCostExecutorsBenchmark bench) { final int work = bench.work; if (work > 0) { - completeTask = new Runnable() { - @Override - public void run() { - Blackhole.consumeCPU(work); - //We can avoid the full barrier cost of a volatile set given that the - //benchmark is focusing on executors with a single threaded consumer: - //it would reduce the cost on consumer side while allowing to focus just - //to the threads hand-off/wake-up cost - DONE_UPDATER.lazySet(PerThreadState.this, completed + 1); - } + completeTask = () -> { + Blackhole.consumeCPU(work); + //We can avoid the full barrier cost of a volatile set given that the + //benchmark is focusing on executors with a single threaded consumer: + //it would reduce the cost on consumer side while allowing to focus just + //to the threads hand-off/wake-up cost + DONE_UPDATER.lazySet(PerThreadState.this, completed + 1); }; } else { - completeTask = new Runnable() { - @Override - public void run() { - //We can avoid the full barrier cost of a volatile set given that the - //benchmark is focusing on executors with a single threaded consumer: - //it would reduce the cost on consumer side while allowing to focus just - //to the threads hand-off/wake-up cost - DONE_UPDATER.lazySet(PerThreadState.this, completed + 1); - } + completeTask = () -> { + //We can avoid the full barrier cost of a volatile set given that the + //benchmark is focusing on executors with a single threaded consumer: + //it would reduce the cost on consumer side while allowing to focus just + //to the threads hand-off/wake-up cost + DONE_UPDATER.lazySet(PerThreadState.this, completed + 1); }; } } diff --git a/microbench/src/main/java/io/netty/microbench/concurrent/RunnableScheduledFutureAdapterBenchmark.java b/microbench/src/main/java/io/netty/microbench/concurrent/RunnableScheduledFutureAdapterBenchmark.java index 5f8774a673..ca450d7de2 100644 --- a/microbench/src/main/java/io/netty/microbench/concurrent/RunnableScheduledFutureAdapterBenchmark.java +++ b/microbench/src/main/java/io/netty/microbench/concurrent/RunnableScheduledFutureAdapterBenchmark.java @@ -42,12 +42,7 @@ public class RunnableScheduledFutureAdapterBenchmark extends AbstractMicrobenchm @State(Scope.Thread) public static class FuturesHolder { - private static final Callable NO_OP = new Callable() { - @Override - public Void call() throws Exception { - return null; - } - }; + private static final Callable NO_OP = () -> null; @Param({ "100", "1000", "10000", "100000" }) int num; @@ -57,12 +52,9 @@ public class RunnableScheduledFutureAdapterBenchmark extends AbstractMicrobenchm @Setup(Level.Invocation) public void reset() { futures.clear(); - executor.submit(new Runnable() { - @Override - public void run() { - for (int i = 1; i <= num; i++) { - futures.add(executor.schedule(NO_OP, i, TimeUnit.HOURS)); - } + executor.submit(() -> { + for (int i = 1; i <= num; i++) { + futures.add(executor.schedule(NO_OP, i, TimeUnit.HOURS)); } }).syncUninterruptibly(); } @@ -75,24 +67,18 @@ public class RunnableScheduledFutureAdapterBenchmark extends AbstractMicrobenchm @Benchmark public Future cancelInOrder(final FuturesHolder futuresHolder) { - return executor.submit(new Runnable() { - @Override - public void run() { - for (int i = 0; i < futuresHolder.num; i++) { - futuresHolder.futures.get(i).cancel(false); - } + return executor.submit(() -> { + for (int i = 0; i < futuresHolder.num; i++) { + futuresHolder.futures.get(i).cancel(false); } }).syncUninterruptibly(); } @Benchmark public Future cancelInReverseOrder(final FuturesHolder futuresHolder) { - return executor.submit(new Runnable() { - @Override - public void run() { - for (int i = futuresHolder.num - 1; i >= 0; i--) { - futuresHolder.futures.get(i).cancel(false); - } + return executor.submit(() -> { + for (int i = futuresHolder.num - 1; i >= 0; i--) { + futuresHolder.futures.get(i).cancel(false); } }).syncUninterruptibly(); } diff --git a/microbench/src/main/java/io/netty/microbench/http2/NoPriorityByteDistributionBenchmark.java b/microbench/src/main/java/io/netty/microbench/http2/NoPriorityByteDistributionBenchmark.java index 928247a530..3911ff0ae6 100644 --- a/microbench/src/main/java/io/netty/microbench/http2/NoPriorityByteDistributionBenchmark.java +++ b/microbench/src/main/java/io/netty/microbench/http2/NoPriorityByteDistributionBenchmark.java @@ -98,16 +98,13 @@ public class NoPriorityByteDistributionBenchmark extends AbstractMicrobenchmark } } - private Http2StreamVisitor invocationVisitor = new Http2StreamVisitor() { - @Override - public boolean visit(Http2Stream stream) throws Http2Exception { - // Restore the connection window. - resetWindow(stream); + private Http2StreamVisitor invocationVisitor = stream -> { + // Restore the connection window. + resetWindow(stream); - // Restore the data to each stream. - dataRefresher(stream).refreshData(); - return true; - } + // Restore the data to each stream. + dataRefresher(stream).refreshData(); + return true; }; @TearDown(Level.Trial) diff --git a/microbench/src/main/java/io/netty/microbench/internal/PrivilegedSocketOperationsBenchmark.java b/microbench/src/main/java/io/netty/microbench/internal/PrivilegedSocketOperationsBenchmark.java index 377ea1ee9a..6ab96a578e 100644 --- a/microbench/src/main/java/io/netty/microbench/internal/PrivilegedSocketOperationsBenchmark.java +++ b/microbench/src/main/java/io/netty/microbench/internal/PrivilegedSocketOperationsBenchmark.java @@ -81,15 +81,12 @@ public class PrivilegedSocketOperationsBenchmark extends AbstractMicrobenchmark public ServerSocketChannel testWithSM(final SecurityManagerInstalled sm) throws IOException { try { final ServerSocketChannel ssc = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public ServerSocketChannel run() throws Exception { - final ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(null); - ssc.configureBlocking(false); - ssc.accept(); - return ssc; - } + (PrivilegedExceptionAction) () -> { + final ServerSocketChannel ssc1 = ServerSocketChannel.open(); + ssc1.socket().bind(null); + ssc1.configureBlocking(false); + ssc1.accept(); + return ssc1; }); ssc.close(); return ssc; @@ -103,15 +100,12 @@ public class PrivilegedSocketOperationsBenchmark extends AbstractMicrobenchmark if (System.getSecurityManager() != null) { try { final ServerSocketChannel ssc = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public ServerSocketChannel run() throws Exception { - final ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(null); - ssc.configureBlocking(false); - ssc.accept(); - return ssc; - } + (PrivilegedExceptionAction) () -> { + final ServerSocketChannel ssc1 = ServerSocketChannel.open(); + ssc1.socket().bind(null); + ssc1.configureBlocking(false); + ssc1.accept(); + return ssc1; }); ssc.close(); return ssc; @@ -143,15 +137,12 @@ public class PrivilegedSocketOperationsBenchmark extends AbstractMicrobenchmark public ServerSocketChannel testWithoutSM(final SecurityManagerEmpty sm) throws IOException { try { final ServerSocketChannel ssc = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public ServerSocketChannel run() throws Exception { - final ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(null); - ssc.configureBlocking(false); - ssc.accept(); - return ssc; - } + (PrivilegedExceptionAction) () -> { + final ServerSocketChannel ssc1 = ServerSocketChannel.open(); + ssc1.socket().bind(null); + ssc1.configureBlocking(false); + ssc1.accept(); + return ssc1; }); ssc.close(); return ssc; @@ -166,15 +157,12 @@ public class PrivilegedSocketOperationsBenchmark extends AbstractMicrobenchmark // this should never happen during benchmarking, but we write the correct code here try { final ServerSocketChannel ssc = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public ServerSocketChannel run() throws Exception { - final ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(null); - ssc.configureBlocking(false); - ssc.accept(); - return ssc; - } + (PrivilegedExceptionAction) () -> { + final ServerSocketChannel ssc1 = ServerSocketChannel.open(); + ssc1.socket().bind(null); + ssc1.configureBlocking(false); + ssc1.accept(); + return ssc1; }); ssc.close(); return ssc; diff --git a/microbench/src/main/java/io/netty/microbench/util/ResourceLeakDetectorRecordBenchmark.java b/microbench/src/main/java/io/netty/microbench/util/ResourceLeakDetectorRecordBenchmark.java index 7687048f93..ac42c1df42 100644 --- a/microbench/src/main/java/io/netty/microbench/util/ResourceLeakDetectorRecordBenchmark.java +++ b/microbench/src/main/java/io/netty/microbench/util/ResourceLeakDetectorRecordBenchmark.java @@ -26,12 +26,7 @@ import org.openjdk.jmh.annotations.TearDown; public class ResourceLeakDetectorRecordBenchmark extends AbstractMicrobenchmark { private static final Object TRACKED = new Object(); - private static final ResourceLeakHint HINT = new ResourceLeakHint() { - @Override - public String toHintString() { - return "BenchmarkHint"; - } - }; + private static final ResourceLeakHint HINT = () -> "BenchmarkHint"; @Param({ "8", "16" }) private int recordTimes; diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java index a2fc58a4d1..15e9fe5a24 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java @@ -406,13 +406,10 @@ public class DnsNameResolver extends InetNameResolver { ch = future.channel(); ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(maxPayloadSize)); - ch.closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - resolveCache.clear(); - cnameCache.clear(); - authoritativeDnsServerCache.clear(); - } + ch.closeFuture().addListener((ChannelFutureListener) future1 -> { + resolveCache.clear(); + cnameCache.clear(); + authoritativeDnsServerCache.clear(); }); } @@ -877,14 +874,11 @@ public class DnsNameResolver extends InetNameResolver { DnsCache resolveCache) { final Promise> allPromise = executor().newPromise(); doResolveAllUncached(hostname, additionals, allPromise, resolveCache); - allPromise.addListener(new FutureListener>() { - @Override - public void operationComplete(Future> future) { - if (future.isSuccess()) { - trySuccess(promise, future.getNow().get(0)); - } else { - tryFailure(promise, future.cause()); - } + allPromise.addListener((FutureListener>) future -> { + if (future.isSuccess()) { + trySuccess(promise, future.getNow().get(0)); + } else { + tryFailure(promise, future.cause()); } }); } @@ -973,12 +967,7 @@ public class DnsNameResolver extends InetNameResolver { if (executor.inEventLoop()) { doResolveAllUncached0(hostname, additionals, promise, resolveCache); } else { - executor.execute(new Runnable() { - @Override - public void run() { - doResolveAllUncached0(hostname, additionals, promise, resolveCache); - } - }); + executor.execute(() -> doResolveAllUncached0(hostname, additionals, promise, resolveCache)); } } diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java index 08bbcb6088..67934534c3 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java @@ -117,19 +117,16 @@ final class DnsQueryContext implements FutureListener>() { - @Override - public void operationComplete(Future future) { - if (future.isSuccess()) { - // If the query is done in a late fashion (as the channel was not ready yet) we always flush - // to ensure we did not race with a previous flush() that was done when the Channel was not - // ready yet. - writeQuery(query, true, writePromise); - } else { - Throwable cause = future.cause(); - promise.tryFailure(cause); - writePromise.setFailure(cause); - } + parent.channelFuture.addListener(future -> { + if (future.isSuccess()) { + // If the query is done in a late fashion (as the channel was not ready yet) we always flush + // to ensure we did not race with a previous flush() that was done when the Channel was not + // ready yet. + writeQuery(query, true, writePromise); + } else { + Throwable cause = future.cause(); + promise.tryFailure(cause); + writePromise.setFailure(cause); } }); } @@ -141,12 +138,7 @@ final class DnsQueryContext implements FutureListener onQueryWriteCompletion(writeFuture)); } } @@ -159,16 +151,13 @@ final class DnsQueryContext implements FutureListener 0) { - timeoutFuture = parent.ch.eventLoop().schedule(new Runnable() { - @Override - public void run() { - if (promise.isDone()) { - // Received a response before the query times out. - return; - } - - setFailure("query timed out after " + queryTimeoutMillis + " milliseconds", null); + timeoutFuture = parent.ch.eventLoop().schedule(() -> { + if (promise.isDone()) { + // Received a response before the query times out. + return; } + + setFailure("query timed out after " + queryTimeoutMillis + " milliseconds", null); }, queryTimeoutMillis, TimeUnit.MILLISECONDS); } } diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java index cd62e3e537..bc77fd2487 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java @@ -63,12 +63,9 @@ import static java.lang.Math.min; abstract class DnsResolveContext { private static final FutureListener> RELEASE_RESPONSE = - new FutureListener>() { - @Override - public void operationComplete(Future> future) { - if (future.isSuccess()) { - future.getNow().release(); - } + future -> { + if (future.isSuccess()) { + future.getNow().release(); } }; private static final RuntimeException NXDOMAIN_QUERY_FAILED_EXCEPTION = ThrowableUtil.unknownStackTrace( @@ -354,41 +351,38 @@ abstract class DnsResolveContext { queryLifecycleObserver.queryWritten(nameServerAddr, writePromise); - f.addListener(new FutureListener>() { - @Override - public void operationComplete(Future> future) { - queriesInProgress.remove(future); + f.addListener((FutureListener>) future -> { + queriesInProgress.remove(future); - if (promise.isDone() || future.isCancelled()) { - queryLifecycleObserver.queryCancelled(allowedQueries); + if (promise.isDone() || future.isCancelled()) { + queryLifecycleObserver.queryCancelled(allowedQueries); - // Check if we need to release the envelope itself. If the query was cancelled the getNow() will - // return null as well as the Future will be failed with a CancellationException. - AddressedEnvelope result = future.getNow(); - if (result != null) { - result.release(); - } - return; + // Check if we need to release the envelope itself. If the query was cancelled the getNow() will + // return null as well as the Future will be failed with a CancellationException. + AddressedEnvelope result = future.getNow(); + if (result != null) { + result.release(); } + return; + } - final Throwable queryCause = future.cause(); - try { - if (queryCause == null) { - onResponse(nameServerAddrStream, nameServerAddrStreamIndex, question, future.getNow(), - queryLifecycleObserver, promise); - } else { - // Server did not respond or I/O error occurred; try again. - queryLifecycleObserver.queryFailed(queryCause); - query(nameServerAddrStream, nameServerAddrStreamIndex + 1, question, - newDnsQueryLifecycleObserver(question), true, promise, queryCause); - } - } finally { - tryToFinishResolve(nameServerAddrStream, nameServerAddrStreamIndex, question, - // queryLifecycleObserver has already been terminated at this point so we must - // not allow it to be terminated again by tryToFinishResolve. - NoopDnsQueryLifecycleObserver.INSTANCE, - promise, queryCause); + final Throwable queryCause = future.cause(); + try { + if (queryCause == null) { + onResponse(nameServerAddrStream, nameServerAddrStreamIndex, question, future.getNow(), + queryLifecycleObserver, promise); + } else { + // Server did not respond or I/O error occurred; try again. + queryLifecycleObserver.queryFailed(queryCause); + query(nameServerAddrStream, nameServerAddrStreamIndex + 1, question, + newDnsQueryLifecycleObserver(question), true, promise, queryCause); } + } finally { + tryToFinishResolve(nameServerAddrStream, nameServerAddrStreamIndex, question, + // queryLifecycleObserver has already been terminated at this point so we must + // not allow it to be terminated again by tryToFinishResolve. + NoopDnsQueryLifecycleObserver.INSTANCE, + promise, queryCause); } }); } @@ -409,23 +403,20 @@ abstract class DnsResolveContext { queriesInProgress.add(resolveFuture); Promise> resolverPromise = parent.executor().newPromise(); - resolverPromise.addListener(new FutureListener>() { - @Override - public void operationComplete(final Future> future) { - // Remove placeholder. - queriesInProgress.remove(resolveFuture); + resolverPromise.addListener((FutureListener>) future -> { + // Remove placeholder. + queriesInProgress.remove(resolveFuture); - if (future.isSuccess()) { - List resolvedAddresses = future.getNow(); - DnsServerAddressStream addressStream = new CombinedDnsServerAddressStream( - nameServerAddr, resolvedAddresses, nameServerAddrStream); - query(addressStream, nameServerAddrStreamIndex, question, - queryLifecycleObserver, true, promise, cause); - } else { - // Ignore the server and try the next one... - query(nameServerAddrStream, nameServerAddrStreamIndex + 1, - question, queryLifecycleObserver, true, promise, cause); - } + if (future.isSuccess()) { + List resolvedAddresses = future.getNow(); + DnsServerAddressStream addressStream = new CombinedDnsServerAddressStream( + nameServerAddr, resolvedAddresses, nameServerAddrStream); + query(addressStream, nameServerAddrStreamIndex, question, + queryLifecycleObserver, true, promise, cause); + } else { + // Ignore the server and try the next one... + query(nameServerAddrStream, nameServerAddrStreamIndex + 1, + question, queryLifecycleObserver, true, promise, cause); } }); if (!DnsNameResolver.doResolveAllCached(nameServerName, additionals, resolverPromise, resolveCache(), diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/InflightNameResolver.java b/resolver-dns/src/main/java/io/netty/resolver/dns/InflightNameResolver.java index f9eeb1a894..a3b0decf6b 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/InflightNameResolver.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/InflightNameResolver.java @@ -81,12 +81,7 @@ final class InflightNameResolver implements NameResolver { if (earlyPromise.isDone()) { transferResult(earlyPromise, promise); } else { - earlyPromise.addListener(new FutureListener() { - @Override - public void operationComplete(Future f) throws Exception { - transferResult(f, promise); - } - }); + earlyPromise.addListener((FutureListener) f -> transferResult(f, promise)); } } else { try { @@ -103,12 +98,7 @@ final class InflightNameResolver implements NameResolver { if (promise.isDone()) { resolveMap.remove(inetHost); } else { - promise.addListener(new FutureListener() { - @Override - public void operationComplete(Future f) throws Exception { - resolveMap.remove(inetHost); - } - }); + promise.addListener((FutureListener) f -> resolveMap.remove(inetHost)); } } } diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCacheTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCacheTest.java index 6e9cb1a199..93e15d618e 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCacheTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCacheTest.java @@ -47,15 +47,12 @@ public class DefaultAuthoritativeDnsServerCacheTest { cache.cache("netty.io", resolved1, 1, loop); cache.cache("netty.io", resolved2, 10000, loop); - Throwable error = loop.schedule(new Callable() { - @Override - public Throwable call() { - try { - assertNull(cache.get("netty.io")); - return null; - } catch (Throwable cause) { - return cause; - } + Throwable error = loop.schedule(() -> { + try { + assertNull(cache.get("netty.io")); + return null; + } catch (Throwable cause) { + return cause; } }, 1, TimeUnit.SECONDS).get(); if (error != null) { @@ -163,19 +160,16 @@ public class DefaultAuthoritativeDnsServerCacheTest { cache = new DefaultAuthoritativeDnsServerCache(10000, 10000, null); } else { cache = new DefaultAuthoritativeDnsServerCache(10000, 10000, - new Comparator() { - @Override - public int compare(InetSocketAddress o1, InetSocketAddress o2) { - if (o1.equals(o2)) { - return 0; - } - if (o1.isUnresolved()) { - return 1; - } else { - return -1; - } - } - }); + (o1, o2) -> { + if (o1.equals(o2)) { + return 0; + } + if (o1.isUnresolved()) { + return 1; + } else { + return -1; + } + }); } cache.cache("netty.io", unresolved, 100, loop); cache.cache("netty.io", resolved, 10000, loop); diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCacheTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCacheTest.java index 7acaf15fbe..2e24d37909 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCacheTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCacheTest.java @@ -49,15 +49,12 @@ public class DefaultDnsCacheTest { cache.cache("netty.io", null, addr1, 1, loop); cache.cache("netty.io", null, addr2, 10000, loop); - Throwable error = loop.schedule(new Callable() { - @Override - public Throwable call() { - try { - assertNull(cache.get("netty.io", null)); - return null; - } catch (Throwable cause) { - return cause; - } + Throwable error = loop.schedule(() -> { + try { + assertNull(cache.get("netty.io", null)); + return null; + } catch (Throwable cause) { + return cause; } }, 1, TimeUnit.SECONDS).get(); if (error != null) { diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCnameCacheTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCnameCacheTest.java index 4629182deb..106e9a4d4e 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCnameCacheTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DefaultDnsCnameCacheTest.java @@ -38,15 +38,12 @@ public class DefaultDnsCnameCacheTest { final DefaultDnsCnameCache cache = new DefaultDnsCnameCache(); cache.cache("netty.io", "mapping.netty.io", 1, loop); - Throwable error = loop.schedule(new Callable() { - @Override - public Throwable call() { - try { - assertNull(cache.get("netty.io")); - return null; - } catch (Throwable cause) { - return cause; - } + Throwable error = loop.schedule(() -> { + try { + assertNull(cache.get("netty.io")); + return null; + } catch (Throwable cause) { + return cause; } }, 1, TimeUnit.SECONDS).get(); if (error != null) { diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java index b5ff0db457..a04a14c21e 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java @@ -396,19 +396,16 @@ public class DnsNameResolverTest { @Test public void testNameServerCache() throws IOException, InterruptedException { final String overriddenIP = "12.34.12.34"; - final TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) { - switch (question.getRecordType()) { - case A: - Map attr = new HashMap<>(); - attr.put(DnsAttribute.IP_ADDRESS.toLowerCase(Locale.US), overriddenIP); - return Collections.singleton( - new TestDnsServer.TestResourceRecord( - question.getDomainName(), question.getRecordType(), attr)); - default: - return null; - } + final TestDnsServer dnsServer2 = new TestDnsServer(question -> { + switch (question.getRecordType()) { + case A: + Map attr = new HashMap<>(); + attr.put(DnsAttribute.IP_ADDRESS.toLowerCase(Locale.US), overriddenIP); + return Collections.singleton( + new TestDnsServer.TestResourceRecord( + question.getDomainName(), question.getRecordType(), attr)); + default: + return null; } }); dnsServer2.start(); @@ -422,13 +419,9 @@ public class DnsNameResolverTest { overriddenHostnames.add(name); } } - DnsNameResolver resolver = newResolver(false, new DnsServerAddressStreamProvider() { - @Override - public DnsServerAddressStream nameServerAddressStream(String hostname) { - return overriddenHostnames.contains(hostname) ? sequential(dnsServer2.localAddress()).stream() : - null; - } - }).build(); + DnsNameResolver resolver = newResolver(false, hostname -> + overriddenHostnames.contains(hostname) ? sequential(dnsServer2.localAddress()).stream() : null) + .build(); try { final Map resultA = testResolve0(resolver, EXCLUSIONS_RESOLVE_A, AAAA); for (Entry resolvedEntry : resultA.entrySet()) { @@ -784,36 +777,33 @@ public class DnsNameResolverTest { final String lastName = "lastname.com"; final String ipv4Addr = "1.2.3.4"; final String ipv6Addr = "::1"; - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) { - ResourceRecordModifier rm = new ResourceRecordModifier(); - rm.setDnsClass(RecordClass.IN); - rm.setDnsName(question.getDomainName()); - rm.setDnsTtl(100); - rm.setDnsType(RecordType.CNAME); + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + ResourceRecordModifier rm = new ResourceRecordModifier(); + rm.setDnsClass(RecordClass.IN); + rm.setDnsName(question.getDomainName()); + rm.setDnsTtl(100); + rm.setDnsType(RecordType.CNAME); - if (question.getDomainName().equals(firstName)) { - rm.put(DnsAttribute.DOMAIN_NAME, secondName); - } else if (question.getDomainName().equals(secondName)) { - rm.put(DnsAttribute.DOMAIN_NAME, lastName); - } else if (question.getDomainName().equals(lastName)) { - rm.setDnsType(question.getRecordType()); - switch (question.getRecordType()) { - case A: - rm.put(DnsAttribute.IP_ADDRESS, ipv4Addr); - break; - case AAAA: - rm.put(DnsAttribute.IP_ADDRESS, ipv6Addr); - break; - default: - return null; - } - } else { - return null; + if (question.getDomainName().equals(firstName)) { + rm.put(DnsAttribute.DOMAIN_NAME, secondName); + } else if (question.getDomainName().equals(secondName)) { + rm.put(DnsAttribute.DOMAIN_NAME, lastName); + } else if (question.getDomainName().equals(lastName)) { + rm.setDnsType(question.getRecordType()); + switch (question.getRecordType()) { + case A: + rm.put(DnsAttribute.IP_ADDRESS, ipv4Addr); + break; + case AAAA: + rm.put(DnsAttribute.IP_ADDRESS, ipv6Addr); + break; + default: + return null; } - return Collections.singleton(rm.getEntry()); + } else { + return null; } + return Collections.singleton(rm.getEntry()); }); dnsServer2.start(); DnsNameResolver resolver = null; @@ -859,47 +849,41 @@ public class DnsNameResolverTest { final String ipv4Addr = "1.2.3.4"; final String ipv6Addr = "::1"; final AtomicBoolean hitServer2 = new AtomicBoolean(); - final TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) throws DnsException { - hitServer2.set(true); - if (question.getDomainName().equals(firstName)) { - ResourceRecordModifier rm = new ResourceRecordModifier(); - rm.setDnsClass(RecordClass.IN); - rm.setDnsName(question.getDomainName()); - rm.setDnsTtl(100); - rm.setDnsType(RecordType.CNAME); - rm.put(DnsAttribute.DOMAIN_NAME, lastName); - return Collections.singleton(rm.getEntry()); - } else { - throw new DnsException(ResponseCode.REFUSED); - } + final TestDnsServer dnsServer2 = new TestDnsServer(question -> { + hitServer2.set(true); + if (question.getDomainName().equals(firstName)) { + ResourceRecordModifier rm = new ResourceRecordModifier(); + rm.setDnsClass(RecordClass.IN); + rm.setDnsName(question.getDomainName()); + rm.setDnsTtl(100); + rm.setDnsType(RecordType.CNAME); + rm.put(DnsAttribute.DOMAIN_NAME, lastName); + return Collections.singleton(rm.getEntry()); + } else { + throw new DnsException(ResponseCode.REFUSED); } }); - final TestDnsServer dnsServer3 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) throws DnsException { - if (question.getDomainName().equals(lastName)) { - ResourceRecordModifier rm = new ResourceRecordModifier(); - rm.setDnsClass(RecordClass.IN); - rm.setDnsName(question.getDomainName()); - rm.setDnsTtl(100); - rm.setDnsType(question.getRecordType()); - switch (question.getRecordType()) { - case A: - rm.put(DnsAttribute.IP_ADDRESS, ipv4Addr); - break; - case AAAA: - rm.put(DnsAttribute.IP_ADDRESS, ipv6Addr); - break; - default: - return null; - } - - return Collections.singleton(rm.getEntry()); - } else { - throw new DnsException(ResponseCode.REFUSED); + final TestDnsServer dnsServer3 = new TestDnsServer(question -> { + if (question.getDomainName().equals(lastName)) { + ResourceRecordModifier rm = new ResourceRecordModifier(); + rm.setDnsClass(RecordClass.IN); + rm.setDnsName(question.getDomainName()); + rm.setDnsTtl(100); + rm.setDnsType(question.getRecordType()); + switch (question.getRecordType()) { + case A: + rm.put(DnsAttribute.IP_ADDRESS, ipv4Addr); + break; + case AAAA: + rm.put(DnsAttribute.IP_ADDRESS, ipv6Addr); + break; + default: + return null; } + + return Collections.singleton(rm.getEntry()); + } else { + throw new DnsException(ResponseCode.REFUSED); } }); dnsServer2.start(); @@ -1020,18 +1004,15 @@ public class DnsNameResolverTest { public void testResolveAllHostsFile() { final DnsNameResolver resolver = new DnsNameResolverBuilder(group.next()) .channelType(NioDatagramChannel.class) - .hostsFileEntriesResolver(new HostsFileEntriesResolver() { - @Override - public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) { - if ("foo.com.".equals(inetHost)) { - try { - return InetAddress.getByAddress("foo.com", new byte[] { 1, 2, 3, 4 }); - } catch (UnknownHostException e) { - throw new Error(e); - } + .hostsFileEntriesResolver((inetHost, resolvedAddressTypes) -> { + if ("foo.com.".equals(inetHost)) { + try { + return InetAddress.getByAddress("foo.com", new byte[] { 1, 2, 3, 4 }); + } catch (UnknownHostException e) { + throw new Error(e); } - return null; } + return null; }).build(); final List records = resolver.resolveAll(new DefaultDnsQuestion("foo.com.", A)) @@ -1220,12 +1201,7 @@ public class DnsNameResolverTest { records.add(Collections.singleton(TestDnsServer.newAddressRecord(name, RecordType.AAAA, ipv6Address))); } final Iterator> recordsIterator = records.iterator(); - RecordStore arbitrarilyOrderedStore = new RecordStore() { - @Override - public Set getRecords(QuestionRecord questionRecord) { - return recordsIterator.next(); - } - }; + RecordStore arbitrarilyOrderedStore = questionRecord -> recordsIterator.next(); TestDnsServer nonCompliantDnsServer = new TestDnsServer(arbitrarilyOrderedStore); nonCompliantDnsServer.start(); try { @@ -1388,15 +1364,12 @@ public class DnsNameResolverTest { // This is used to simulate a query timeout... final DatagramSocket socket = new DatagramSocket(new InetSocketAddress(0)); - final TestDnsServer dnsServerAuthority = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) { - if (question.getDomainName().equals(expected.getHostName())) { - return Collections.singleton(TestDnsServer.newARecord( - expected.getHostName(), expected.getHostAddress())); - } - return Collections.emptySet(); + final TestDnsServer dnsServerAuthority = new TestDnsServer(question -> { + if (question.getDomainName().equals(expected.getHostName())) { + return Collections.singleton(TestDnsServer.newARecord( + expected.getHostName(), expected.getHostAddress())); } + return Collections.emptySet(); }); dnsServerAuthority.start(); @@ -2090,28 +2063,24 @@ public class DnsNameResolverTest { @Test public void testFollowCNAMEEvenIfARecordIsPresent() throws IOException { - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + if (question.getDomainName().equals("cname.netty.io")) { + Map map1 = new HashMap<>(); + map1.put(DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.99"); + return Collections.singleton( + new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.A, map1)); + } else { + Set records = new LinkedHashSet<>(2); + Map map = new HashMap<>(); + map.put(DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"); + records.add(new TestDnsServer.TestResourceRecord( + question.getDomainName(), RecordType.CNAME, map)); - @Override - public Set getRecords(QuestionRecord question) { - if (question.getDomainName().equals("cname.netty.io")) { - Map map1 = new HashMap<>(); - map1.put(DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.99"); - return Collections.singleton( - new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.A, map1)); - } else { - Set records = new LinkedHashSet<>(2); - Map map = new HashMap<>(); - map.put(DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"); - records.add(new TestDnsServer.TestResourceRecord( - question.getDomainName(), RecordType.CNAME, map)); - - Map map1 = new HashMap<>(); - map1.put(DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.2"); - records.add(new TestDnsServer.TestResourceRecord( - question.getDomainName(), RecordType.A, map1)); - return records; - } + Map map1 = new HashMap<>(); + map1.put(DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.2"); + records.add(new TestDnsServer.TestResourceRecord( + question.getDomainName(), RecordType.A, map1)); + return records; } }); dnsServer2.start(); @@ -2140,29 +2109,25 @@ public class DnsNameResolverTest { @Test public void testFollowCNAMELoop() throws IOException { expectedException.expect(UnknownHostException.class); - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + Set records = new LinkedHashSet<>(4); - @Override - public Set getRecords(QuestionRecord question) { - Set records = new LinkedHashSet<>(4); - - records.add(new TestDnsServer.TestResourceRecord("x." + question.getDomainName(), - RecordType.A, Collections.singletonMap( - DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.99"))); - records.add(new TestDnsServer.TestResourceRecord( - "cname2.netty.io", RecordType.CNAME, - Collections.singletonMap( - DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); - records.add(new TestDnsServer.TestResourceRecord( - "cname.netty.io", RecordType.CNAME, - Collections.singletonMap( - DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname2.netty.io"))); - records.add(new TestDnsServer.TestResourceRecord( - question.getDomainName(), RecordType.CNAME, - Collections.singletonMap( - DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); - return records; - } + records.add(new TestDnsServer.TestResourceRecord("x." + question.getDomainName(), + RecordType.A, Collections.singletonMap( + DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.99"))); + records.add(new TestDnsServer.TestResourceRecord( + "cname2.netty.io", RecordType.CNAME, + Collections.singletonMap( + DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); + records.add(new TestDnsServer.TestResourceRecord( + "cname.netty.io", RecordType.CNAME, + Collections.singletonMap( + DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname2.netty.io"))); + records.add(new TestDnsServer.TestResourceRecord( + question.getDomainName(), RecordType.CNAME, + Collections.singletonMap( + DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); + return records; }); dnsServer2.start(); DnsNameResolver resolver = null; @@ -2325,11 +2290,8 @@ public class DnsNameResolverTest { public void testChannelFactoryException() { final IllegalStateException exception = new IllegalStateException(); try { - newResolver().channelFactory(new ChannelFactory() { - @Override - public DatagramChannel newChannel(EventLoop eventLoop) { - throw exception; - } + newResolver().channelFactory(eventLoop -> { + throw exception; }).build(); fail(); } catch (Exception e) { @@ -2343,36 +2305,32 @@ public class DnsNameResolverTest { final AtomicInteger cnameQueries = new AtomicInteger(); final AtomicInteger aQueries = new AtomicInteger(); - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + if ("cname.netty.io".equals(question.getDomainName())) { + aQueries.incrementAndGet(); - @Override - public Set getRecords(QuestionRecord question) { - if ("cname.netty.io".equals(question.getDomainName())) { - aQueries.incrementAndGet(); - - return Collections.singleton(new TestDnsServer.TestResourceRecord( - question.getDomainName(), RecordType.A, - Collections.singletonMap( - DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.99"))); - } - if ("x.netty.io".equals(question.getDomainName())) { - cnameQueries.incrementAndGet(); - - return Collections.singleton(new TestDnsServer.TestResourceRecord( - question.getDomainName(), RecordType.CNAME, - Collections.singletonMap( - DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); - } - if ("y.netty.io".equals(question.getDomainName())) { - cnameQueries.incrementAndGet(); - - return Collections.singleton(new TestDnsServer.TestResourceRecord( - question.getDomainName(), RecordType.CNAME, - Collections.singletonMap( - DnsAttribute.DOMAIN_NAME.toLowerCase(), "x.netty.io"))); - } - return Collections.emptySet(); + return Collections.singleton(new TestDnsServer.TestResourceRecord( + question.getDomainName(), RecordType.A, + Collections.singletonMap( + DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.99"))); } + if ("x.netty.io".equals(question.getDomainName())) { + cnameQueries.incrementAndGet(); + + return Collections.singleton(new TestDnsServer.TestResourceRecord( + question.getDomainName(), RecordType.CNAME, + Collections.singletonMap( + DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); + } + if ("y.netty.io".equals(question.getDomainName())) { + cnameQueries.incrementAndGet(); + + return Collections.singleton(new TestDnsServer.TestResourceRecord( + question.getDomainName(), RecordType.CNAME, + Collections.singletonMap( + DnsAttribute.DOMAIN_NAME.toLowerCase(), "x.netty.io"))); + } + return Collections.emptySet(); }); dnsServer2.start(); DnsNameResolver resolver = null; diff --git a/resolver/src/main/java/io/netty/resolver/AddressResolverGroup.java b/resolver/src/main/java/io/netty/resolver/AddressResolverGroup.java index 2c898baf72..9f9f5ff59f 100644 --- a/resolver/src/main/java/io/netty/resolver/AddressResolverGroup.java +++ b/resolver/src/main/java/io/netty/resolver/AddressResolverGroup.java @@ -71,14 +71,11 @@ public abstract class AddressResolverGroup implements C } resolvers.put(executor, newResolver); - executor.terminationFuture().addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - synchronized (resolvers) { - resolvers.remove(executor); - } - newResolver.close(); + executor.terminationFuture().addListener((FutureListener) future -> { + synchronized (resolvers) { + resolvers.remove(executor); } + newResolver.close(); }); r = newResolver; diff --git a/resolver/src/main/java/io/netty/resolver/CompositeNameResolver.java b/resolver/src/main/java/io/netty/resolver/CompositeNameResolver.java index 8074c3dcf0..0afc407d3d 100644 --- a/resolver/src/main/java/io/netty/resolver/CompositeNameResolver.java +++ b/resolver/src/main/java/io/netty/resolver/CompositeNameResolver.java @@ -69,14 +69,11 @@ public final class CompositeNameResolver extends SimpleNameResolver { promise.setFailure(lastFailure); } else { NameResolver resolver = resolvers[resolverIndex]; - resolver.resolve(inetHost).addListener(new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - if (future.isSuccess()) { - promise.setSuccess(future.getNow()); - } else { - doResolveRec(inetHost, promise, resolverIndex + 1, future.cause()); - } + resolver.resolve(inetHost).addListener((FutureListener) future -> { + if (future.isSuccess()) { + promise.setSuccess(future.getNow()); + } else { + doResolveRec(inetHost, promise, resolverIndex + 1, future.cause()); } }); } @@ -95,14 +92,11 @@ public final class CompositeNameResolver extends SimpleNameResolver { promise.setFailure(lastFailure); } else { NameResolver resolver = resolvers[resolverIndex]; - resolver.resolveAll(inetHost).addListener(new FutureListener>() { - @Override - public void operationComplete(Future> future) throws Exception { - if (future.isSuccess()) { - promise.setSuccess(future.getNow()); - } else { - doResolveAllRec(inetHost, promise, resolverIndex + 1, future.cause()); - } + resolver.resolveAll(inetHost).addListener((FutureListener>) future -> { + if (future.isSuccess()) { + promise.setSuccess(future.getNow()); + } else { + doResolveAllRec(inetHost, promise, resolverIndex + 1, future.cause()); } }); } diff --git a/resolver/src/main/java/io/netty/resolver/InetSocketAddressResolver.java b/resolver/src/main/java/io/netty/resolver/InetSocketAddressResolver.java index f6aff6093e..70b68628d4 100644 --- a/resolver/src/main/java/io/netty/resolver/InetSocketAddressResolver.java +++ b/resolver/src/main/java/io/netty/resolver/InetSocketAddressResolver.java @@ -55,14 +55,11 @@ public class InetSocketAddressResolver extends AbstractAddressResolver() { - @Override - public void operationComplete(Future future) throws Exception { - if (future.isSuccess()) { - promise.setSuccess(new InetSocketAddress(future.getNow(), unresolvedAddress.getPort())); - } else { - promise.setFailure(future.cause()); - } + .addListener((FutureListener) future -> { + if (future.isSuccess()) { + promise.setSuccess(new InetSocketAddress(future.getNow(), unresolvedAddress.getPort())); + } else { + promise.setFailure(future.cause()); } }); } @@ -73,20 +70,17 @@ public class InetSocketAddressResolver extends AbstractAddressResolver>() { - @Override - public void operationComplete(Future> future) throws Exception { - if (future.isSuccess()) { - List inetAddresses = future.getNow(); - List socketAddresses = - new ArrayList<>(inetAddresses.size()); - for (InetAddress inetAddress : inetAddresses) { - socketAddresses.add(new InetSocketAddress(inetAddress, unresolvedAddress.getPort())); - } - promise.setSuccess(socketAddresses); - } else { - promise.setFailure(future.cause()); + .addListener((FutureListener>) future -> { + if (future.isSuccess()) { + List inetAddresses = future.getNow(); + List socketAddresses = + new ArrayList<>(inetAddresses.size()); + for (InetAddress inetAddress : inetAddresses) { + socketAddresses.add(new InetSocketAddress(inetAddress, unresolvedAddress.getPort())); } + promise.setSuccess(socketAddresses); + } else { + promise.setFailure(future.cause()); } }); } diff --git a/resolver/src/main/java/io/netty/resolver/RoundRobinInetAddressResolver.java b/resolver/src/main/java/io/netty/resolver/RoundRobinInetAddressResolver.java index f722892324..91b04d250a 100644 --- a/resolver/src/main/java/io/netty/resolver/RoundRobinInetAddressResolver.java +++ b/resolver/src/main/java/io/netty/resolver/RoundRobinInetAddressResolver.java @@ -54,45 +54,39 @@ public class RoundRobinInetAddressResolver extends InetNameResolver { // hijack the doResolve request, but do a doResolveAll request under the hood. // Note that InetSocketAddress.getHostName() will never incur a reverse lookup here, // because an unresolved address always has a host name. - nameResolver.resolveAll(inetHost).addListener(new FutureListener>() { - @Override - public void operationComplete(Future> future) throws Exception { - if (future.isSuccess()) { - List inetAddresses = future.getNow(); - int numAddresses = inetAddresses.size(); - if (numAddresses > 0) { - // if there are multiple addresses: we shall pick one by one - // to support the round robin distribution - promise.setSuccess(inetAddresses.get(randomIndex(numAddresses))); - } else { - promise.setFailure(new UnknownHostException(inetHost)); - } + nameResolver.resolveAll(inetHost).addListener((FutureListener>) future -> { + if (future.isSuccess()) { + List inetAddresses = future.getNow(); + int numAddresses = inetAddresses.size(); + if (numAddresses > 0) { + // if there are multiple addresses: we shall pick one by one + // to support the round robin distribution + promise.setSuccess(inetAddresses.get(randomIndex(numAddresses))); } else { - promise.setFailure(future.cause()); + promise.setFailure(new UnknownHostException(inetHost)); } + } else { + promise.setFailure(future.cause()); } }); } @Override protected void doResolveAll(String inetHost, final Promise> promise) throws Exception { - nameResolver.resolveAll(inetHost).addListener(new FutureListener>() { - @Override - public void operationComplete(Future> future) throws Exception { - if (future.isSuccess()) { - List inetAddresses = future.getNow(); - if (!inetAddresses.isEmpty()) { - // create a copy to make sure that it's modifiable random access collection - List result = new ArrayList<>(inetAddresses); - // rotate by different distance each time to force round robin distribution - Collections.rotate(result, randomIndex(inetAddresses.size())); - promise.setSuccess(result); - } else { - promise.setSuccess(inetAddresses); - } + nameResolver.resolveAll(inetHost).addListener((FutureListener>) future -> { + if (future.isSuccess()) { + List inetAddresses = future.getNow(); + if (!inetAddresses.isEmpty()) { + // create a copy to make sure that it's modifiable random access collection + List result = new ArrayList<>(inetAddresses); + // rotate by different distance each time to force round robin distribution + Collections.rotate(result, randomIndex(inetAddresses.size())); + promise.setSuccess(result); } else { - promise.setFailure(future.cause()); + promise.setSuccess(inetAddresses); } + } else { + promise.setFailure(future.cause()); } }); } diff --git a/testsuite-http2/src/main/java/io/netty/testsuite/http2/Http2ServerInitializer.java b/testsuite-http2/src/main/java/io/netty/testsuite/http2/Http2ServerInitializer.java index 4f0f745e83..eb44835796 100644 --- a/testsuite-http2/src/main/java/io/netty/testsuite/http2/Http2ServerInitializer.java +++ b/testsuite-http2/src/main/java/io/netty/testsuite/http2/Http2ServerInitializer.java @@ -40,14 +40,11 @@ import io.netty.util.ReferenceCountUtil; */ public class Http2ServerInitializer extends ChannelInitializer { - private static final UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() { - @Override - public UpgradeCodec newUpgradeCodec(CharSequence protocol) { - if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { - return new Http2ServerUpgradeCodec(new HelloWorldHttp2HandlerBuilder().build()); - } else { - return null; - } + private static final UpgradeCodecFactory upgradeCodecFactory = protocol -> { + if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { + return new Http2ServerUpgradeCodec(new HelloWorldHttp2HandlerBuilder().build()); + } else { + return null; } }; diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/sctp/SctpTestPermutation.java b/testsuite/src/main/java/io/netty/testsuite/transport/sctp/SctpTestPermutation.java index aac9b38a02..019add03b7 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/sctp/SctpTestPermutation.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/sctp/SctpTestPermutation.java @@ -48,14 +48,9 @@ public final class SctpTestPermutation { } // Make the list of ServerBootstrap factories. - return Collections.singletonList(new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap(). - group(nioBossGroup, nioWorkerGroup). - channel(NioSctpServerChannel.class); - } - }); + return Collections.singletonList(() -> new ServerBootstrap(). + group(nioBossGroup, nioWorkerGroup). + channel(NioSctpServerChannel.class)); } static List> sctpClientChannel() { @@ -63,12 +58,8 @@ public final class SctpTestPermutation { return Collections.emptyList(); } - return Collections.singletonList(new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channel(NioSctpChannel.class); - } - }); + return Collections.singletonList(() -> + new Bootstrap().group(nioWorkerGroup).channel(NioSctpChannel.class)); } static List> sctpChannel() { diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketBufReleaseTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketBufReleaseTest.java index 6fc36e9542..35daf21af1 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketBufReleaseTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketBufReleaseTest.java @@ -90,12 +90,7 @@ public class SocketBufReleaseTest extends AbstractSocketTest { // call retain on it so it can't be put back on the pool buf.writeBytes(data).retain(); - ctx.channel().writeAndFlush(buf).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - latch.countDown(); - } - }); + ctx.channel().writeAndFlush(buf).addListener((ChannelFutureListener) future -> latch.countDown()); } @Override diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketCloseForciblyTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketCloseForciblyTest.java index f492132f59..3dd38214c2 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketCloseForciblyTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketCloseForciblyTest.java @@ -36,12 +36,9 @@ public class SocketCloseForciblyTest extends AbstractSocketTest { public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { final SocketChannel childChannel = (SocketChannel) msg; // Dispatch on the EventLoop as all operation on Unsafe should be done while on the EventLoop. - childChannel.eventLoop().execute(new Runnable() { - @Override - public void run() { - childChannel.config().setSoLinger(0); - childChannel.unsafe().closeForcibly(); - } + childChannel.eventLoop().execute(() -> { + childChannel.config().setSoLinger(0); + childChannel.unsafe().closeForcibly(); }); } }).childHandler(new ChannelInboundHandlerAdapter()); diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java index 4729d86684..fbbbe53819 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java @@ -90,12 +90,7 @@ public class SocketHalfClosedTest extends AbstractSocketTest { shutdownEventReceivedCounter.incrementAndGet(); } else if (evt == ChannelInputShutdownReadComplete.INSTANCE) { shutdownReadCompleteEventReceivedCounter.incrementAndGet(); - ctx.executor().schedule(new Runnable() { - @Override - public void run() { - ctx.close(); - } - }, 100, MILLISECONDS); + ctx.executor().schedule((Runnable) ctx::close, 100, MILLISECONDS); } } @@ -152,12 +147,8 @@ public class SocketHalfClosedTest extends AbstractSocketTest { public void channelActive(ChannelHandlerContext ctx) throws Exception { ByteBuf buf = ctx.alloc().buffer(totalServerBytesWritten); buf.writerIndex(buf.capacity()); - ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - ((DuplexChannel) future.channel()).shutdownOutput(); - } - }); + ctx.writeAndFlush(buf).addListener((ChannelFutureListener) future -> + ((DuplexChannel) future.channel()).shutdownOutput()); serverInitializedLatch.countDown(); } @@ -327,27 +318,15 @@ public class SocketHalfClosedTest extends AbstractSocketTest { // We write a reply and immediately close our end of the socket. ByteBuf buf = ctx.alloc().buffer(expectedBytes); buf.writerIndex(buf.writerIndex() + expectedBytes); - ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - future.channel().close().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(final ChannelFuture future) throws Exception { - // This is a bit racy but there is no better way how to handle this in Java11. - // The problem is that on close() the underlying FD will not actually be closed directly - // but the close will be done after the Selector did process all events. Because of - // this we will need to give it a bit time to ensure the FD is actual closed before we - // count down the latch and try to write. - future.channel().eventLoop().schedule(new Runnable() { - @Override - public void run() { - followerCloseLatch.countDown(); - } - }, 200, TimeUnit.MILLISECONDS); - } - }); - } - }); + ctx.writeAndFlush(buf).addListener((ChannelFutureListener) future -> + future.channel().close().addListener((ChannelFutureListener) future1 -> { + // This is a bit racy but there is no better way how to handle this in Java11. + // The problem is that on close() the underlying FD will not actually be closed directly + // but the close will be done after the Selector did process all events. Because of + // this we will need to give it a bit time to ensure the FD is actual closed before we + // count down the latch and try to write. + future1.channel().eventLoop().schedule(followerCloseLatch::countDown, 200, TimeUnit.MILLISECONDS); + })); } } @@ -386,13 +365,10 @@ public class SocketHalfClosedTest extends AbstractSocketTest { followerCloseLatch.await(); // This write should fail, but we should still be allowed to read the peer's data - ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.cause() == null) { - causeRef.set(new IllegalStateException("second write should have failed!")); - doneLatch.countDown(); - } + ctx.writeAndFlush(buf).addListener((ChannelFutureListener) future -> { + if (future.cause() == null) { + causeRef.set(new IllegalStateException("second write should have failed!")); + doneLatch.countDown(); } }); } diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketTestPermutation.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketTestPermutation.java index 8fa2377ace..3af9b7ed01 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketTestPermutation.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketTestPermutation.java @@ -103,22 +103,17 @@ public class SocketTestPermutation { public List> datagram() { // Make the list of Bootstrap factories. List> bfs = Collections.singletonList( - new BootstrapFactory() { + () -> new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory() { @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory() { - @Override - public Channel newChannel(EventLoop eventLoop) { - return new NioDatagramChannel(eventLoop, InternetProtocolFamily.IPv4); - } - - @Override - public String toString() { - return NioDatagramChannel.class.getSimpleName() + ".class"; - } - }); + public Channel newChannel(EventLoop eventLoop) { + return new NioDatagramChannel(eventLoop, InternetProtocolFamily.IPv4); } - } + + @Override + public String toString() { + return NioDatagramChannel.class.getSimpleName() + ".class"; + } + }) ); // Populare the combinations. @@ -127,35 +122,20 @@ public class SocketTestPermutation { public List> serverSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) - .channel(NioServerSocketChannel.class); - } - } + () -> new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) + .channel(NioServerSocketChannel.class) ); } public List> clientSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class); - } - } + () -> new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class) ); } public List> datagramSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channel(NioDatagramChannel.class); - } - } + () -> new Bootstrap().group(nioWorkerGroup).channel(NioDatagramChannel.class) ); } } diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/TrafficShapingHandlerTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/TrafficShapingHandlerTest.java index 529a8dc362..c9269d95b8 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/TrafficShapingHandlerTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/TrafficShapingHandlerTest.java @@ -513,23 +513,17 @@ public class TrafficShapingHandlerTest extends AbstractSocketTest { if (isAutoRead == -3) { wait = stepms * 3; } - executor.schedule(new Runnable() { - @Override - public void run() { - loggerServer.info("Step: " + exactStep + " Reset AutoRead"); - channel.config().setAutoRead(true); - } + executor.schedule(() -> { + loggerServer.info("Step: " + exactStep + " Reset AutoRead"); + channel.config().setAutoRead(true); }, wait, TimeUnit.MILLISECONDS); } else { if (isAutoRead > 1) { loggerServer.debug("Step: " + step + " Will Set AutoRead: True"); final int exactStep = step; - executor.schedule(new Runnable() { - @Override - public void run() { - loggerServer.info("Step: " + exactStep + " Set AutoRead: True"); - channel.config().setAutoRead(true); - } + executor.schedule(() -> { + loggerServer.info("Step: " + exactStep + " Set AutoRead: True"); + channel.config().setAutoRead(true); }, stepms + minimalms, TimeUnit.MILLISECONDS); } } diff --git a/testsuite/src/main/java/io/netty/testsuite/util/TestUtils.java b/testsuite/src/main/java/io/netty/testsuite/util/TestUtils.java index 0da0d8b186..28a9dd82b3 100644 --- a/testsuite/src/main/java/io/netty/testsuite/util/TestUtils.java +++ b/testsuite/src/main/java/io/netty/testsuite/util/TestUtils.java @@ -136,12 +136,7 @@ public final class TestUtils { } public static void compressHeapDumps() throws IOException { - final File[] files = new File(System.getProperty("user.dir")).listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".hprof"); - } - }); + final File[] files = new File(System.getProperty("user.dir")).listFiles((dir, name) -> name.endsWith(".hprof")); final byte[] buf = new byte[65536]; final LZMA2Options options = new LZMA2Options(LZMA2Options.PRESET_DEFAULT); diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java index 8b7f3915d7..d7fe1324d4 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java @@ -183,14 +183,11 @@ abstract class AbstractEpollChannel extends AbstractChannel implements UnixChann if (loop.inEventLoop()) { doDeregister(); } else { - loop.execute(new Runnable() { - @Override - public void run() { - try { - doDeregister(); - } catch (Throwable cause) { - pipeline().fireExceptionCaught(cause); - } + loop.execute(() -> { + try { + doDeregister(); + } catch (Throwable cause) { + pipeline().fireExceptionCaught(cause); } }); } @@ -260,13 +257,10 @@ abstract class AbstractEpollChannel extends AbstractChannel implements UnixChann unsafe.clearEpollIn0(); } else { // schedule a task to clear the EPOLLIN as it is not safe to modify it directly - loop.execute(new Runnable() { - @Override - public void run() { - if (!unsafe.readPending && !config().isAutoRead()) { - // Still no read triggered so clear it now - unsafe.clearEpollIn0(); - } + loop.execute(() -> { + if (!unsafe.readPending && !config().isAutoRead()) { + // Still no read triggered so clear it now + unsafe.clearEpollIn0(); } }); } @@ -564,29 +558,23 @@ abstract class AbstractEpollChannel extends AbstractChannel implements UnixChann // Schedule connect timeout. int connectTimeoutMillis = config().getConnectTimeoutMillis(); if (connectTimeoutMillis > 0) { - connectTimeoutFuture = eventLoop().schedule(new Runnable() { - @Override - public void run() { - ChannelPromise connectPromise = AbstractEpollChannel.this.connectPromise; - ConnectTimeoutException cause = - new ConnectTimeoutException("connection timed out: " + remoteAddress); - if (connectPromise != null && connectPromise.tryFailure(cause)) { - close(voidPromise()); - } + connectTimeoutFuture = eventLoop().schedule(() -> { + ChannelPromise connectPromise = AbstractEpollChannel.this.connectPromise; + ConnectTimeoutException cause = + new ConnectTimeoutException("connection timed out: " + remoteAddress); + if (connectPromise != null && connectPromise.tryFailure(cause)) { + close(voidPromise()); } }, connectTimeoutMillis, TimeUnit.MILLISECONDS); } - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isCancelled()) { - if (connectTimeoutFuture != null) { - connectTimeoutFuture.cancel(false); - } - connectPromise = null; - close(voidPromise()); + promise.addListener((ChannelFutureListener) future -> { + if (future.isCancelled()) { + if (connectTimeoutFuture != null) { + connectTimeoutFuture.cancel(false); } + connectPromise = null; + close(voidPromise()); } }); } diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java index 4c5a3df982..ae3aa77e88 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java @@ -70,13 +70,10 @@ public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel im private static final ClosedChannelException FAIL_SPLICE_IF_CLOSED_CLOSED_CHANNEL_EXCEPTION = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), AbstractEpollStreamChannel.class, "failSpliceIfClosed(...)"); - private final Runnable flushTask = new Runnable() { - @Override - public void run() { - // Calling flush0 directly to ensure we not try to flush messages that were added via write(...) in the - // meantime. - ((AbstractEpollUnsafe) unsafe()).flush0(); - } + private final Runnable flushTask = () -> { + // Calling flush0 directly to ensure we not try to flush messages that were added via write(...) in the + // meantime. + ((AbstractEpollUnsafe) unsafe()).flush0(); }; private Queue spliceQueue; @@ -238,13 +235,8 @@ public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel im // Seems like the Channel was closed in the meantime try to fail the promise to prevent any // cases where a future may not be notified otherwise. if (promise.tryFailure(FAIL_SPLICE_IF_CLOSED_CLOSED_CHANNEL_EXCEPTION)) { - eventLoop().execute(new Runnable() { - @Override - public void run() { - // Call this via the EventLoop as it is a MPSC queue. - clearSpliceQueue(); - } - }); + // Call this via the EventLoop as it is a MPSC queue. + eventLoop().execute(this::clearSpliceQueue); } } } @@ -582,12 +574,7 @@ public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel im if (loop.inEventLoop()) { ((AbstractUnsafe) unsafe()).shutdownOutput(promise); } else { - loop.execute(new Runnable() { - @Override - public void run() { - ((AbstractUnsafe) unsafe()).shutdownOutput(promise); - } - }); + loop.execute(() -> ((AbstractUnsafe) unsafe()).shutdownOutput(promise)); } return promise; @@ -602,23 +589,13 @@ public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel im public ChannelFuture shutdownInput(final ChannelPromise promise) { Executor closeExecutor = ((EpollStreamUnsafe) unsafe()).prepareToClose(); if (closeExecutor != null) { - closeExecutor.execute(new Runnable() { - @Override - public void run() { - shutdownInput0(promise); - } - }); + closeExecutor.execute(() -> shutdownInput0(promise)); } else { EventLoop loop = eventLoop(); if (loop.inEventLoop()) { shutdownInput0(promise); } else { - loop.execute(new Runnable() { - @Override - public void run() { - shutdownInput0(promise); - } - }); + loop.execute(() -> shutdownInput0(promise)); } } return promise; @@ -635,12 +612,8 @@ public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel im if (shutdownOutputFuture.isDone()) { shutdownOutputDone(shutdownOutputFuture, promise); } else { - shutdownOutputFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(final ChannelFuture shutdownOutputFuture) throws Exception { - shutdownOutputDone(shutdownOutputFuture, promise); - } - }); + shutdownOutputFuture.addListener((ChannelFutureListener) shutdownOutputFuture1 -> + shutdownOutputDone(shutdownOutputFuture1, promise)); } return promise; } @@ -650,12 +623,8 @@ public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel im if (shutdownInputFuture.isDone()) { shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise); } else { - shutdownInputFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture shutdownInputFuture) throws Exception { - shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise); - } - }); + shutdownInputFuture.addListener((ChannelFutureListener) shutdownInputFuture1 -> + shutdownDone(shutdownOutputFuture, shutdownInputFuture1, promise)); } } @@ -838,12 +807,7 @@ public abstract class AbstractEpollStreamChannel extends AbstractEpollChannel im if (eventLoop.inEventLoop()) { addToSpliceQueue0(task); } else { - eventLoop.execute(new Runnable() { - @Override - public void run() { - addToSpliceQueue0(task); - } - }); + eventLoop.execute(() -> addToSpliceQueue0(task)); } } diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollHandler.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollHandler.java index d817d8be96..766207a958 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollHandler.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollHandler.java @@ -69,12 +69,7 @@ public class EpollHandler implements IoHandler { private NativeDatagramPacketArray datagramPacketArray; private final SelectStrategy selectStrategy; - private final IntSupplier selectNowSupplier = new IntSupplier() { - @Override - public int get() throws Exception { - return epollWaitNow(); - } - }; + private final IntSupplier selectNowSupplier = this::epollWaitNow; @SuppressWarnings("unused") // AtomicIntegerFieldUpdater private volatile int wakenUp; @@ -152,12 +147,7 @@ public class EpollHandler implements IoHandler { * Returns a new {@link IoHandlerFactory} that creates {@link EpollHandler} instances. */ public static IoHandlerFactory newFactory() { - return new IoHandlerFactory() { - @Override - public IoHandler newHandler() { - return new EpollHandler(); - } - }; + return EpollHandler::new; } /** @@ -167,12 +157,7 @@ public class EpollHandler implements IoHandler { final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkPositiveOrZero(maxEvents, "maxEvents"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); - return new IoHandlerFactory() { - @Override - public IoHandler newHandler() { - return new EpollHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); - } - }; + return () -> new EpollHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); } private IovArray cleanIovArray() { diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollRecvByteAllocatorHandle.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollRecvByteAllocatorHandle.java index a500a891b0..4a84cdc37d 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollRecvByteAllocatorHandle.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollRecvByteAllocatorHandle.java @@ -27,12 +27,7 @@ class EpollRecvByteAllocatorHandle implements RecvByteBufAllocator.ExtendedHandl private final PreferredDirectByteBufAllocator preferredDirectByteBufAllocator = new PreferredDirectByteBufAllocator(); private final RecvByteBufAllocator.ExtendedHandle delegate; - private final UncheckedBooleanSupplier defaultMaybeMoreDataSupplier = new UncheckedBooleanSupplier() { - @Override - public boolean get() { - return maybeMoreDataToRead(); - } - }; + private final UncheckedBooleanSupplier defaultMaybeMoreDataSupplier = this::maybeMoreDataToRead; private boolean isEdgeTriggered; private boolean receivedRdHup; diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDomainSocketFdTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDomainSocketFdTest.java index 0c46694690..b7d32f0ee5 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDomainSocketFdTest.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDomainSocketFdTest.java @@ -59,13 +59,10 @@ public class EpollDomainSocketFdTest extends AbstractSocketTest { // Create new channel and obtain a file descriptor from it. final EpollDomainSocketChannel ch = new EpollDomainSocketChannel(ctx.channel().eventLoop()); - ctx.writeAndFlush(ch.fd()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - Throwable cause = future.cause(); - queue.offer(cause); - } + ctx.writeAndFlush(ch.fd()).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + Throwable cause = future.cause(); + queue.offer(cause); } }); } diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java index 89afe52a37..25bba974e2 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java @@ -49,11 +49,8 @@ public class EpollEventLoopTest { try { final EventLoop eventLoop = group.next(); - Future future = eventLoop.schedule(new Runnable() { - @Override - public void run() { - // NOOP - } + Future future = eventLoop.schedule(() -> { + // NOOP }, Long.MAX_VALUE, TimeUnit.MILLISECONDS); assertFalse(future.awaitUninterruptibly(1000)); diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollReuseAddrTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollReuseAddrTest.java index 4585978d65..febd356918 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollReuseAddrTest.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollReuseAddrTest.java @@ -138,21 +138,18 @@ public class EpollReuseAddrTest { // on both sockets. int count = 16; final CountDownLatch latch = new CountDownLatch(count); - Runnable r = new Runnable() { - @Override - public void run() { - try { - DatagramSocket socket = new DatagramSocket(); - while (!received1.get() || !received2.get()) { - socket.send(new DatagramPacket( - bytes, 0, bytes.length, address1.getAddress(), address1.getPort())); - } - socket.close(); - } catch (IOException e) { - e.printStackTrace(); + Runnable r = () -> { + try { + DatagramSocket socket = new DatagramSocket(); + while (!received1.get() || !received2.get()) { + socket.send(new DatagramPacket( + bytes, 0, bytes.length, address1.getAddress(), address1.getPort())); } - latch.countDown(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); } + latch.countDown(); }; ExecutorService executor = Executors.newFixedThreadPool(count); diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketStringEchoBusyWaitTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketStringEchoBusyWaitTest.java index 1ecc07a08b..ef5be28237 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketStringEchoBusyWaitTest.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketStringEchoBusyWaitTest.java @@ -41,17 +41,7 @@ public class EpollSocketStringEchoBusyWaitTest extends SocketStringEchoTest { @BeforeClass public static void setup() throws Exception { EPOLL_LOOP = new MultithreadEventLoopGroup(2, new DefaultThreadFactory("testsuite-epoll-busy-wait", true), - EpollHandler.newFactory(0, new SelectStrategyFactory() { - @Override - public SelectStrategy newSelectStrategy() { - return new SelectStrategy() { - @Override - public int calculateStrategy(IntSupplier selectSupplier, boolean hasTasks) { - return SelectStrategy.BUSY_WAIT; - } - }; - } - })); + EpollHandler.newFactory(0, () -> (selectSupplier, hasTasks) -> SelectStrategy.BUSY_WAIT)); } @AfterClass @@ -83,20 +73,10 @@ public class EpollSocketStringEchoBusyWaitTest extends SocketStringEchoTest { } private static BootstrapFactory serverSocket() { - return new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(EPOLL_LOOP, EPOLL_LOOP).channel(EpollServerSocketChannel.class); - } - }; + return () -> new ServerBootstrap().group(EPOLL_LOOP, EPOLL_LOOP).channel(EpollServerSocketChannel.class); } private static BootstrapFactory clientSocket() { - return new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(EPOLL_LOOP).channel(EpollSocketChannel.class); - } - }; + return () -> new Bootstrap().group(EPOLL_LOOP).channel(EpollSocketChannel.class); } } diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketTestPermutation.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketTestPermutation.java index f4f05cd49b..ef47ec8426 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketTestPermutation.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketTestPermutation.java @@ -73,31 +73,18 @@ class EpollSocketTestPermutation extends SocketTestPermutation { @Override public List> serverSocket() { List> toReturn = new ArrayList<>(); - toReturn.add(new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP) - .channel(EpollServerSocketChannel.class); - } - }); + toReturn.add(() -> new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP) + .channel(EpollServerSocketChannel.class)); if (isServerFastOpen()) { - toReturn.add(new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - ServerBootstrap serverBootstrap = new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP) - .channel(EpollServerSocketChannel.class); - serverBootstrap.option(EpollChannelOption.TCP_FASTOPEN, 5); - return serverBootstrap; - } + toReturn.add(() -> { + ServerBootstrap serverBootstrap = new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP) + .channel(EpollServerSocketChannel.class); + serverBootstrap.option(EpollChannelOption.TCP_FASTOPEN, 5); + return serverBootstrap; }); } - toReturn.add(new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) - .channel(NioServerSocketChannel.class); - } - }); + toReturn.add(() -> new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) + .channel(NioServerSocketChannel.class)); return toReturn; } @@ -106,18 +93,8 @@ class EpollSocketTestPermutation extends SocketTestPermutation { @Override public List> clientSocket() { return Arrays.asList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollSocketChannel.class); - } - }, - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class); - } - } + () -> new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollSocketChannel.class), + () -> new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class) ); } @@ -126,28 +103,18 @@ class EpollSocketTestPermutation extends SocketTestPermutation { // Make the list of Bootstrap factories. @SuppressWarnings("unchecked") List> bfs = Arrays.asList( - new BootstrapFactory() { + () -> new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory() { @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory() { - @Override - public Channel newChannel(EventLoop eventLoop) { - return new NioDatagramChannel(eventLoop, InternetProtocolFamily.IPv4); - } + public Channel newChannel(EventLoop eventLoop) { + return new NioDatagramChannel(eventLoop, InternetProtocolFamily.IPv4); + } - @Override - public String toString() { - return NioDatagramChannel.class.getSimpleName() + ".class"; - } - }); - } - }, - new BootstrapFactory() { @Override - public Bootstrap newInstance() { - return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDatagramChannel.class); + public String toString() { + return NioDatagramChannel.class.getSimpleName() + ".class"; } - } + }), + () -> new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDatagramChannel.class) ); return combo(bfs, bfs); } @@ -161,71 +128,53 @@ class EpollSocketTestPermutation extends SocketTestPermutation { public List> serverDomainSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP) - .channel(EpollServerDomainSocketChannel.class); - } - } + () -> new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP) + .channel(EpollServerDomainSocketChannel.class) ); } public List> clientDomainSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDomainSocketChannel.class); - } - } + () -> new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDomainSocketChannel.class) ); } @Override public List> datagramSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDatagramChannel.class); - } - } + () -> new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDatagramChannel.class) ); } public boolean isServerFastOpen() { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Integer run() { - int fastopen = 0; - File file = new File("/proc/sys/net/ipv4/tcp_fastopen"); - if (file.exists()) { - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(file)); - fastopen = Integer.parseInt(in.readLine()); - if (logger.isDebugEnabled()) { - logger.debug("{}: {}", file, fastopen); - } - } catch (Exception e) { - logger.debug("Failed to get TCP_FASTOPEN from: {}", file, e); - } finally { - if (in != null) { - try { - in.close(); - } catch (Exception e) { - // Ignored. - } - } - } - } else { + return AccessController.doPrivileged((PrivilegedAction) () -> { + int fastopen = 0; + File file = new File("/proc/sys/net/ipv4/tcp_fastopen"); + if (file.exists()) { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(file)); + fastopen = Integer.parseInt(in.readLine()); if (logger.isDebugEnabled()) { - logger.debug("{}: {} (non-existent)", file, fastopen); + logger.debug("{}: {}", file, fastopen); + } + } catch (Exception e) { + logger.debug("Failed to get TCP_FASTOPEN from: {}", file, e); + } finally { + if (in != null) { + try { + in.close(); + } catch (Exception e) { + // Ignored. + } } } - return fastopen; + } else { + if (logger.isDebugEnabled()) { + logger.debug("{}: {} (non-existent)", file, fastopen); + } } + return fastopen; }) == 3; } diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSpliceTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSpliceTest.java index feb6e6c630..6a4ad43c9e 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSpliceTest.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSpliceTest.java @@ -81,12 +81,9 @@ public class EpollSpliceTest { // the data transfer only in kernel space! // Integer.MAX_VALUE will splice infinitly. - ch.spliceTo(ch2, Integer.MAX_VALUE).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - future.channel().close(); - } + ch.spliceTo(ch2, Integer.MAX_VALUE).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + future.channel().close(); } }); // Trigger multiple splices to see if partial splicing works as well. @@ -108,19 +105,11 @@ public class EpollSpliceTest { context.close(); } }); - bs.connect(sc.localAddress()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - ctx.close(); - } else { - future.channel().closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - ctx.close(); - } - }); - } + bs.connect(sc.localAddress()).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + ctx.close(); + } else { + future.channel().closeFuture().addListener((ChannelFutureListener) future1 -> ctx.close()); } }); } diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollTest.java index 94108560bb..25885ce5ba 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollTest.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollTest.java @@ -43,16 +43,13 @@ public class EpollTest { Native.epollCtlAdd(epoll.intValue(), eventfd.intValue(), Native.EPOLLIN); final AtomicReference ref = new AtomicReference<>(); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - assertEquals(1, Native.epollWait(epoll, eventArray, timerFd, -1, -1)); - // This should have been woken up because of eventfd_write. - assertEquals(eventfd.intValue(), eventArray.fd(0)); - } catch (Throwable cause) { - ref.set(cause); - } + Thread t = new Thread(() -> { + try { + assertEquals(1, Native.epollWait(epoll, eventArray, timerFd, -1, -1)); + // This should have been woken up because of eventfd_write. + assertEquals(eventfd.intValue(), eventArray.fd(0)); + } catch (Throwable cause) { + ref.set(cause); } }); t.start(); diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java index 2b8bafc268..2cdadf3595 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java @@ -145,14 +145,11 @@ abstract class AbstractKQueueChannel extends AbstractChannel implements UnixChan if (loop.inEventLoop()) { doDeregister(); } else { - loop.execute(new Runnable() { - @Override - public void run() { - try { - doDeregister(); - } catch (Throwable cause) { - pipeline().fireExceptionCaught(cause); - } + loop.execute(() -> { + try { + doDeregister(); + } catch (Throwable cause) { + pipeline().fireExceptionCaught(cause); } }); } @@ -327,13 +324,10 @@ abstract class AbstractKQueueChannel extends AbstractChannel implements UnixChan unsafe.clearReadFilter0(); } else { // schedule a task to clear the EPOLLIN as it is not safe to modify it directly - loop.execute(new Runnable() { - @Override - public void run() { - if (!unsafe.readPending && !config().isAutoRead()) { - // Still no read triggered so clear it now - unsafe.clearReadFilter0(); - } + loop.execute(() -> { + if (!unsafe.readPending && !config().isAutoRead()) { + // Still no read triggered so clear it now + unsafe.clearReadFilter0(); } }); } @@ -563,29 +557,23 @@ abstract class AbstractKQueueChannel extends AbstractChannel implements UnixChan // Schedule connect timeout. int connectTimeoutMillis = config().getConnectTimeoutMillis(); if (connectTimeoutMillis > 0) { - connectTimeoutFuture = eventLoop().schedule(new Runnable() { - @Override - public void run() { - ChannelPromise connectPromise = AbstractKQueueChannel.this.connectPromise; - ConnectTimeoutException cause = - new ConnectTimeoutException("connection timed out: " + remoteAddress); - if (connectPromise != null && connectPromise.tryFailure(cause)) { - close(voidPromise()); - } + connectTimeoutFuture = eventLoop().schedule(() -> { + ChannelPromise connectPromise = AbstractKQueueChannel.this.connectPromise; + ConnectTimeoutException cause = + new ConnectTimeoutException("connection timed out: " + remoteAddress); + if (connectPromise != null && connectPromise.tryFailure(cause)) { + close(voidPromise()); } }, connectTimeoutMillis, TimeUnit.MILLISECONDS); } - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isCancelled()) { - if (connectTimeoutFuture != null) { - connectTimeoutFuture.cancel(false); - } - connectPromise = null; - close(voidPromise()); + promise.addListener((ChannelFutureListener) future -> { + if (future.isCancelled()) { + if (connectTimeoutFuture != null) { + connectTimeoutFuture.cancel(false); } + connectPromise = null; + close(voidPromise()); } }); } diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java index 37aa526c9f..73c19cc9a7 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java @@ -55,13 +55,10 @@ public abstract class AbstractKQueueStreamChannel extends AbstractKQueueChannel " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ", " + StringUtil.simpleClassName(DefaultFileRegion.class) + ')'; private WritableByteChannel byteChannel; - private final Runnable flushTask = new Runnable() { - @Override - public void run() { - // Calling flush0 directly to ensure we not try to flush messages that were added via write(...) in the - // meantime. - ((AbstractKQueueUnsafe) unsafe()).flush0(); - } + private final Runnable flushTask = () -> { + // Calling flush0 directly to ensure we not try to flush messages that were added via write(...) in the + // meantime. + ((AbstractKQueueUnsafe) unsafe()).flush0(); }; AbstractKQueueStreamChannel(Channel parent, EventLoop eventLoop, BsdSocket fd, boolean active) { @@ -404,12 +401,7 @@ public abstract class AbstractKQueueStreamChannel extends AbstractKQueueChannel if (loop.inEventLoop()) { ((AbstractUnsafe) unsafe()).shutdownOutput(promise); } else { - loop.execute(new Runnable() { - @Override - public void run() { - ((AbstractUnsafe) unsafe()).shutdownOutput(promise); - } - }); + loop.execute(() -> ((AbstractUnsafe) unsafe()).shutdownOutput(promise)); } return promise; } @@ -425,12 +417,7 @@ public abstract class AbstractKQueueStreamChannel extends AbstractKQueueChannel if (loop.inEventLoop()) { shutdownInput0(promise); } else { - loop.execute(new Runnable() { - @Override - public void run() { - shutdownInput0(promise); - } - }); + loop.execute(() -> shutdownInput0(promise)); } return promise; } @@ -456,12 +443,8 @@ public abstract class AbstractKQueueStreamChannel extends AbstractKQueueChannel if (shutdownOutputFuture.isDone()) { shutdownOutputDone(shutdownOutputFuture, promise); } else { - shutdownOutputFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(final ChannelFuture shutdownOutputFuture) throws Exception { - shutdownOutputDone(shutdownOutputFuture, promise); - } - }); + shutdownOutputFuture.addListener((ChannelFutureListener) shutdownOutputFuture1 -> + shutdownOutputDone(shutdownOutputFuture1, promise)); } return promise; } @@ -471,12 +454,8 @@ public abstract class AbstractKQueueStreamChannel extends AbstractKQueueChannel if (shutdownInputFuture.isDone()) { shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise); } else { - shutdownInputFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture shutdownInputFuture) throws Exception { - shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise); - } - }); + shutdownInputFuture.addListener((ChannelFutureListener) shutdownInputFuture1 -> + shutdownDone(shutdownOutputFuture, shutdownInputFuture1, promise)); } } diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueHandler.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueHandler.java index 936206a462..0559bee741 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueHandler.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueHandler.java @@ -62,12 +62,7 @@ public final class KQueueHandler implements IoHandler { private final KQueueEventArray eventList; private final SelectStrategy selectStrategy; private final IovArray iovArray = new IovArray(); - private final IntSupplier selectNowSupplier = new IntSupplier() { - @Override - public int get() throws Exception { - return kqueueWaitNow(); - } - }; + private final IntSupplier selectNowSupplier = this::kqueueWaitNow; private final IntObjectMap channels = new IntObjectHashMap(4096); private volatile int wakenUp; @@ -105,12 +100,7 @@ public final class KQueueHandler implements IoHandler { * Returns a new {@link IoHandlerFactory} that creates {@link KQueueHandler} instances. */ public static IoHandlerFactory newFactory() { - return new IoHandlerFactory() { - @Override - public IoHandler newHandler() { - return new KQueueHandler(); - } - }; + return KQueueHandler::new; } /** @@ -120,12 +110,7 @@ public final class KQueueHandler implements IoHandler { final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkPositiveOrZero(maxEvents, "maxEvents"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); - return new IoHandlerFactory() { - @Override - public IoHandler newHandler() { - return new KQueueHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); - } - }; + return () -> new KQueueHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); } @Override diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueRecvByteAllocatorHandle.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueRecvByteAllocatorHandle.java index 9eed7d49f5..229e7857a0 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueRecvByteAllocatorHandle.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueRecvByteAllocatorHandle.java @@ -31,12 +31,7 @@ final class KQueueRecvByteAllocatorHandle implements RecvByteBufAllocator.Extend new PreferredDirectByteBufAllocator(); private final RecvByteBufAllocator.ExtendedHandle delegate; - private final UncheckedBooleanSupplier defaultMaybeMoreDataSupplier = new UncheckedBooleanSupplier() { - @Override - public boolean get() { - return maybeMoreDataToRead(); - } - }; + private final UncheckedBooleanSupplier defaultMaybeMoreDataSupplier = this::maybeMoreDataToRead; private boolean overrideGuess; private boolean readEOF; private long numberBytesPending; diff --git a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueDomainSocketFdTest.java b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueDomainSocketFdTest.java index 2dbe144901..e2efeabf14 100644 --- a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueDomainSocketFdTest.java +++ b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueDomainSocketFdTest.java @@ -58,13 +58,10 @@ public class KQueueDomainSocketFdTest extends AbstractSocketTest { // Create new channel and obtain a file descriptor from it. final KQueueDomainSocketChannel ch = new KQueueDomainSocketChannel(ctx.channel().eventLoop()); - ctx.writeAndFlush(ch.fd()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - Throwable cause = future.cause(); - queue.offer(cause); - } + ctx.writeAndFlush(ch.fd()).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + Throwable cause = future.cause(); + queue.offer(cause); } }); } diff --git a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java index ebebae7856..b8ce7e3514 100644 --- a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java +++ b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java @@ -33,11 +33,8 @@ public class KQueueEventLoopTest { EventLoopGroup group = new MultithreadEventLoopGroup(1, KQueueHandler.newFactory()); final EventLoop el = group.next(); - Future future = el.schedule(new Runnable() { - @Override - public void run() { - // NOOP - } + Future future = el.schedule(() -> { + // NOOP }, Long.MAX_VALUE, TimeUnit.MILLISECONDS); assertFalse(future.awaitUninterruptibly(1000)); diff --git a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueSocketTestPermutation.java b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueSocketTestPermutation.java index 23ef178c84..65b854e422 100644 --- a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueSocketTestPermutation.java +++ b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueSocketTestPermutation.java @@ -68,21 +68,11 @@ class KQueueSocketTestPermutation extends SocketTestPermutation { @Override public List> serverSocket() { List> toReturn = new ArrayList<>(); - toReturn.add(new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(KQUEUE_BOSS_GROUP, KQUEUE_WORKER_GROUP) - .channel(KQueueServerSocketChannel.class); - } - }); + toReturn.add(() -> new ServerBootstrap().group(KQUEUE_BOSS_GROUP, KQUEUE_WORKER_GROUP) + .channel(KQueueServerSocketChannel.class)); - toReturn.add(new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) - .channel(NioServerSocketChannel.class); - } - }); + toReturn.add(() -> new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) + .channel(NioServerSocketChannel.class)); return toReturn; } @@ -91,18 +81,8 @@ class KQueueSocketTestPermutation extends SocketTestPermutation { @Override public List> clientSocket() { return Arrays.asList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueSocketChannel.class); - } - }, - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class); - } - } + () -> new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueSocketChannel.class), + () -> new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class) ); } @@ -111,28 +91,18 @@ class KQueueSocketTestPermutation extends SocketTestPermutation { // Make the list of Bootstrap factories. @SuppressWarnings("unchecked") List> bfs = Arrays.asList( - new BootstrapFactory() { + () -> new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory() { @Override - public Bootstrap newInstance() { - return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory() { - @Override - public Channel newChannel(EventLoop eventLoop) { - return new NioDatagramChannel(eventLoop, InternetProtocolFamily.IPv4); - } + public Channel newChannel(EventLoop eventLoop) { + return new NioDatagramChannel(eventLoop, InternetProtocolFamily.IPv4); + } - @Override - public String toString() { - return NioDatagramChannel.class.getSimpleName() + ".class"; - } - }); - } - }, - new BootstrapFactory() { @Override - public Bootstrap newInstance() { - return new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueDatagramChannel.class); + public String toString() { + return NioDatagramChannel.class.getSimpleName() + ".class"; } - } + }), + () -> new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueDatagramChannel.class) ); return combo(bfs, bfs); } @@ -146,36 +116,21 @@ class KQueueSocketTestPermutation extends SocketTestPermutation { public List> serverDomainSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public ServerBootstrap newInstance() { - return new ServerBootstrap().group(KQUEUE_BOSS_GROUP, KQUEUE_WORKER_GROUP) - .channel(KQueueServerDomainSocketChannel.class); - } - } + () -> new ServerBootstrap().group(KQUEUE_BOSS_GROUP, KQUEUE_WORKER_GROUP) + .channel(KQueueServerDomainSocketChannel.class) ); } public List> clientDomainSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueDomainSocketChannel.class); - } - } + () -> new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueDomainSocketChannel.class) ); } @Override public List> datagramSocket() { return Collections.singletonList( - new BootstrapFactory() { - @Override - public Bootstrap newInstance() { - return new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueDatagramChannel.class); - } - } + () -> new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueDatagramChannel.class) ); } public static DomainSocketAddress newSocketAddress() { diff --git a/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java b/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java index 26f0af6008..b670a291e0 100644 --- a/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java +++ b/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java @@ -354,12 +354,7 @@ public class NioSctpChannel extends AbstractNioMessageChannel implements io.nett promise.setFailure(t); } } else { - eventLoop().execute(new Runnable() { - @Override - public void run() { - bindAddress(localAddress, promise); - } - }); + eventLoop().execute(() -> bindAddress(localAddress, promise)); } return promise; } @@ -379,12 +374,7 @@ public class NioSctpChannel extends AbstractNioMessageChannel implements io.nett promise.setFailure(t); } } else { - eventLoop().execute(new Runnable() { - @Override - public void run() { - unbindAddress(localAddress, promise); - } - }); + eventLoop().execute(() -> unbindAddress(localAddress, promise)); } return promise; } diff --git a/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpServerChannel.java b/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpServerChannel.java index a4c3d524ba..3899e533ab 100644 --- a/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpServerChannel.java +++ b/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpServerChannel.java @@ -169,12 +169,7 @@ public class NioSctpServerChannel extends AbstractNioMessageChannel promise.setFailure(t); } } else { - eventLoop().execute(new Runnable() { - @Override - public void run() { - bindAddress(localAddress, promise); - } - }); + eventLoop().execute(() -> bindAddress(localAddress, promise)); } return promise; } @@ -194,12 +189,7 @@ public class NioSctpServerChannel extends AbstractNioMessageChannel promise.setFailure(t); } } else { - eventLoop().execute(new Runnable() { - @Override - public void run() { - unbindAddress(localAddress, promise); - } - }); + eventLoop().execute(() -> unbindAddress(localAddress, promise)); } return promise; }