From 6a43807843d7ce27bbe231c22f11d14066e66a22 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Thu, 30 Jan 2020 09:28:24 +0100 Subject: [PATCH] Use lambdas whenever possible (#9979) Motivation: We should update our code to use lamdas whenever possible Modifications: Use lambdas when possible Result: Cleanup code for Java8 --- .../java/io/netty/buffer/ByteBufUtil.java | 15 +- .../java/io/netty/buffer/PoolThreadCache.java | 9 +- .../io/netty/buffer/PooledDirectByteBuf.java | 8 +- .../netty/buffer/PooledDuplicatedByteBuf.java | 10 +- .../io/netty/buffer/PooledHeapByteBuf.java | 7 +- .../io/netty/buffer/PooledSlicedByteBuf.java | 9 +- .../buffer/PooledUnsafeDirectByteBuf.java | 7 +- .../netty/buffer/PooledUnsafeHeapByteBuf.java | 8 +- .../java/io/netty/buffer/ByteBufUtilTest.java | 25 +--- .../SimpleLeakAwareCompositeByteBufTest.java | 8 +- ...bSocketClientProtocolHandshakeHandler.java | 26 ++-- .../WebSocketCloseFrameHandler.java | 23 +-- ...bSocketServerProtocolHandshakeHandler.java | 22 +-- .../extensions/WebSocketExtensionFilter.java | 14 +- .../WebSocketHandshakeHandOverTest.java | 7 +- .../PerMessageDeflateDecoderTest.java | 15 +- .../PerMessageDeflateEncoderTest.java | 17 +-- .../http2/AbstractHttp2StreamChannel.java | 6 +- .../codec/http2/Http2ConnectionHandler.java | 13 +- .../handler/codec/http2/Http2FrameCodec.java | 7 +- .../DefaultHttp2LocalFlowControllerTest.java | 9 +- .../http2/Http2ConnectionHandlerTest.java | 34 ++--- .../Http2ControlFrameLimitEncoderTest.java | 50 ++----- ...p2EmptyDataFrameConnectionDecoderTest.java | 9 +- .../java/io/netty/util/internal/Hidden.java | 16 +- .../io/netty/util/internal/PendingWrite.java | 8 +- .../util/internal/RecyclableArrayList.java | 9 +- .../util/internal/ThreadExecutorMap.java | 29 +--- .../SingleThreadEventExecutorTest.java | 5 +- .../util/internal/ThreadExecutorMapTest.java | 24 +-- .../handler/flow/FlowControlHandler.java | 8 +- .../ssl/ReferenceCountedOpenSslEngine.java | 23 ++- .../java/io/netty/handler/ssl/SslHandler.java | 11 +- .../flush/FlushConsolidationHandlerTest.java | 9 +- .../ssl/OpenSslPrivateKeyMethodTest.java | 8 +- .../io/netty/handler/ssl/SslHandlerTest.java | 9 +- .../stream/ChunkedWriteHandlerTest.java | 36 ++--- .../epoll/EpollSocketChannelBenchmark.java | 5 +- .../netty/resolver/dns/DnsNameResolver.java | 141 +++++++++--------- .../resolver/dns/DnsNameResolverTest.java | 130 +++++++--------- .../io/netty/osgitests/OsgiBundleTest.java | 9 +- .../AbstractSingleThreadEventLoopTest.java | 12 +- .../socket/AbstractSocketReuseFdTest.java | 10 +- .../netty/channel/ChannelOutboundBuffer.java | 8 +- .../channel/DefaultChannelHandlerContext.java | 16 +- .../io/netty/channel/PendingWriteQueue.java | 8 +- .../channel/DefaultChannelPipelineTest.java | 23 ++- .../netty/channel/PendingWriteQueueTest.java | 11 +- 48 files changed, 283 insertions(+), 643 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index fe3cab43c9..37ef93fc75 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -22,7 +22,6 @@ import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.internal.MathUtil; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; @@ -1173,12 +1172,7 @@ public final class ByteBufUtil { static final class ThreadLocalUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf { private static final ObjectPool RECYCLER = - ObjectPool.newPool(new ObjectCreator() { - @Override - public ThreadLocalUnsafeDirectByteBuf newObject(Handle handle) { - return new ThreadLocalUnsafeDirectByteBuf(handle); - } - }); + ObjectPool.newPool(ThreadLocalUnsafeDirectByteBuf::new); static ThreadLocalUnsafeDirectByteBuf newInstance() { ThreadLocalUnsafeDirectByteBuf buf = RECYCLER.get(); @@ -1207,12 +1201,7 @@ public final class ByteBufUtil { static final class ThreadLocalDirectByteBuf extends UnpooledDirectByteBuf { private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public ThreadLocalDirectByteBuf newObject(Handle handle) { - return new ThreadLocalDirectByteBuf(handle); - } - }); + ThreadLocalDirectByteBuf::new); static ThreadLocalDirectByteBuf newInstance() { ThreadLocalDirectByteBuf buf = RECYCLER.get(); diff --git a/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java b/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java index ab68824462..d7eb4373d0 100644 --- a/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java +++ b/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java @@ -23,7 +23,6 @@ import io.netty.buffer.PoolArena.SizeClass; import io.netty.util.internal.MathUtil; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; @@ -493,12 +492,6 @@ final class PoolThreadCache { } @SuppressWarnings("rawtypes") - private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() { - @SuppressWarnings("unchecked") - @Override - public Entry newObject(Handle handle) { - return new Entry(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(handle -> new Entry(handle)); } } diff --git a/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java index 3d77ecf195..c6f460d61f 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java @@ -18,7 +18,6 @@ package io.netty.buffer; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import java.io.IOException; import java.io.InputStream; @@ -28,12 +27,7 @@ import java.nio.ByteBuffer; final class PooledDirectByteBuf extends PooledByteBuf { private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public PooledDirectByteBuf newObject(Handle handle) { - return new PooledDirectByteBuf(handle, 0); - } - }); + handle -> new PooledDirectByteBuf(handle, 0)); static PooledDirectByteBuf newInstance(int maxCapacity) { PooledDirectByteBuf buf = RECYCLER.get(); diff --git a/buffer/src/main/java/io/netty/buffer/PooledDuplicatedByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledDuplicatedByteBuf.java index b590f57d3c..69c2f55413 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledDuplicatedByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledDuplicatedByteBuf.java @@ -19,7 +19,6 @@ package io.netty.buffer; import io.netty.util.ByteProcessor; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import java.io.IOException; import java.io.InputStream; @@ -31,13 +30,8 @@ import java.nio.channels.ScatteringByteChannel; final class PooledDuplicatedByteBuf extends AbstractPooledDerivedByteBuf { - private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public PooledDuplicatedByteBuf newObject(Handle handle) { - return new PooledDuplicatedByteBuf(handle); - } - }); + private static final ObjectPool RECYCLER = + ObjectPool.newPool(PooledDuplicatedByteBuf::new); static PooledDuplicatedByteBuf newInstance(AbstractByteBuf unwrapped, ByteBuf wrapped, int readerIndex, int writerIndex) { diff --git a/buffer/src/main/java/io/netty/buffer/PooledHeapByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledHeapByteBuf.java index f271e6c050..1c03ed3fad 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledHeapByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledHeapByteBuf.java @@ -27,12 +27,7 @@ import java.nio.ByteBuffer; class PooledHeapByteBuf extends PooledByteBuf { private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public PooledHeapByteBuf newObject(Handle handle) { - return new PooledHeapByteBuf(handle, 0); - } - }); + handle -> new PooledHeapByteBuf(handle, 0)); static PooledHeapByteBuf newInstance(int maxCapacity) { PooledHeapByteBuf buf = RECYCLER.get(); diff --git a/buffer/src/main/java/io/netty/buffer/PooledSlicedByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledSlicedByteBuf.java index 5231d1ca7f..9b10febf06 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledSlicedByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledSlicedByteBuf.java @@ -19,7 +19,6 @@ package io.netty.buffer; import io.netty.util.ByteProcessor; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import java.io.IOException; import java.io.InputStream; @@ -33,13 +32,7 @@ import static io.netty.buffer.AbstractUnpooledSlicedByteBuf.checkSliceOutOfBound final class PooledSlicedByteBuf extends AbstractPooledDerivedByteBuf { - private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public PooledSlicedByteBuf newObject(Handle handle) { - return new PooledSlicedByteBuf(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(PooledSlicedByteBuf::new); static PooledSlicedByteBuf newInstance(AbstractByteBuf unwrapped, ByteBuf wrapped, int index, int length) { diff --git a/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java index fd7e27d214..6b9cfdceea 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java @@ -28,12 +28,7 @@ import java.nio.ByteBuffer; final class PooledUnsafeDirectByteBuf extends PooledByteBuf { private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public PooledUnsafeDirectByteBuf newObject(Handle handle) { - return new PooledUnsafeDirectByteBuf(handle, 0); - } - }); + handle -> new PooledUnsafeDirectByteBuf(handle, 0)); static PooledUnsafeDirectByteBuf newInstance(int maxCapacity) { PooledUnsafeDirectByteBuf buf = RECYCLER.get(); diff --git a/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java index f8e18b213f..e832f9cf1a 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java @@ -17,18 +17,12 @@ package io.netty.buffer; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import io.netty.util.internal.PlatformDependent; final class PooledUnsafeHeapByteBuf extends PooledHeapByteBuf { private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public PooledUnsafeHeapByteBuf newObject(Handle handle) { - return new PooledUnsafeHeapByteBuf(handle, 0); - } - }); + handle -> new PooledUnsafeHeapByteBuf(handle, 0)); static PooledUnsafeHeapByteBuf newUnsafeInstance(int maxCapacity) { PooledUnsafeHeapByteBuf buf = RECYCLER.get(); diff --git a/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java b/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java index 78fa1a7344..c62571d2e6 100644 --- a/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java +++ b/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java @@ -585,34 +585,19 @@ public class ByteBufUtilTest { @Test public void testWriteUtf8InvalidSubsequences() { - testInvalidSubsequences(new TestMethod() { - @Override - public int invoke(Object... args) { - return ByteBufUtil.writeUtf8((ByteBuf) args[0], (String) args[1], - (Integer) args[2], (Integer) args[3]); - } - }); + testInvalidSubsequences(args -> ByteBufUtil.writeUtf8((ByteBuf) args[0], (String) args[1], + (Integer) args[2], (Integer) args[3])); } @Test public void testReserveAndWriteUtf8InvalidSubsequences() { - testInvalidSubsequences(new TestMethod() { - @Override - public int invoke(Object... args) { - return ByteBufUtil.reserveAndWriteUtf8((ByteBuf) args[0], (String) args[1], - (Integer) args[2], (Integer) args[3], 32); - } - }); + testInvalidSubsequences(args -> ByteBufUtil.reserveAndWriteUtf8((ByteBuf) args[0], (String) args[1], + (Integer) args[2], (Integer) args[3], 32)); } @Test public void testUtf8BytesInvalidSubsequences() { - testInvalidSubsequences(new TestMethod() { - @Override - public int invoke(Object... args) { - return ByteBufUtil.utf8Bytes((String) args[1], (Integer) args[2], (Integer) args[3]); - } - }); + testInvalidSubsequences(args -> ByteBufUtil.utf8Bytes((String) args[1], (Integer) args[2], (Integer) args[3])); } @Test diff --git a/buffer/src/test/java/io/netty/buffer/SimpleLeakAwareCompositeByteBufTest.java b/buffer/src/test/java/io/netty/buffer/SimpleLeakAwareCompositeByteBufTest.java index e173ddcb5c..ccdc8e9eb0 100644 --- a/buffer/src/test/java/io/netty/buffer/SimpleLeakAwareCompositeByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/SimpleLeakAwareCompositeByteBufTest.java @@ -15,7 +15,6 @@ */ package io.netty.buffer; -import io.netty.util.ByteProcessor; import io.netty.util.ResourceLeakTracker; import org.hamcrest.CoreMatchers; import org.junit.After; @@ -146,12 +145,7 @@ public class SimpleLeakAwareCompositeByteBufTest extends WrappedCompositeByteBuf comp.addComponent(true, inner); buf.addComponent(true, comp); - assertEquals(-1, buf.forEachByte(new ByteProcessor() { - @Override - public boolean process(byte value) { - return true; - } - })); + assertEquals(-1, buf.forEachByte(value -> true)); assertTrue(buf.release()); } 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 e37beb58b6..a3354ae0f2 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 @@ -97,28 +97,20 @@ class WebSocketClientProtocolHandshakeHandler implements ChannelHandler { return; } - final Future timeoutFuture = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - if (localHandshakePromise.isDone()) { - return; - } + final Future timeoutFuture = ctx.executor().schedule(() -> { + if (localHandshakePromise.isDone()) { + return; + } - if (localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) { - ctx.flush() - .fireUserEventTriggered(ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT) - .close(); - } + if (localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) { + ctx.flush() + .fireUserEventTriggered(ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT) + .close(); } }, 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)); } /** diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketCloseFrameHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketCloseFrameHandler.java index a9f959bb50..5ec10f48a4 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketCloseFrameHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketCloseFrameHandler.java @@ -51,12 +51,7 @@ final class WebSocketCloseFrameHandler implements ChannelHandler { } flush(ctx); applyCloseSentTimeout(ctx); - closeSent.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - ctx.close(promise); - } - }); + closeSent.addListener((ChannelFutureListener) future -> ctx.close(promise)); } @Override @@ -78,20 +73,12 @@ final class WebSocketCloseFrameHandler implements ChannelHandler { return; } - final ScheduledFuture timeoutTask = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - if (!closeSent.isDone()) { - closeSent.tryFailure(new WebSocketHandshakeException("send close frame timed out")); - } + final ScheduledFuture timeoutTask = ctx.executor().schedule(() -> { + if (!closeSent.isDone()) { + closeSent.tryFailure(new WebSocketHandshakeException("send close frame timed out")); } }, forceCloseTimeoutMillis, TimeUnit.MILLISECONDS); - closeSent.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - timeoutTask.cancel(false); - } - }); + closeSent.addListener((ChannelFutureListener) future -> timeoutTask.cancel(false)); } } 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 c34104ea9d..b6ea2aa8af 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 @@ -139,24 +139,16 @@ class WebSocketServerProtocolHandshakeHandler implements ChannelHandler { return; } - final Future timeoutFuture = ctx.executor().schedule(new Runnable() { - @Override - public void run() { - if (!localHandshakePromise.isDone() && - localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) { - ctx.flush() - .fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT) - .close(); - } + final Future timeoutFuture = ctx.executor().schedule(() -> { + if (!localHandshakePromise.isDone() && + localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) { + ctx.flush() + .fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT) + .close(); } }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS); // Cancel the handshake timeout when handshake is finished. - localHandshakePromise.addListener(new FutureListener() { - @Override - public void operationComplete(Future f) { - timeoutFuture.cancel(false); - } - }); + localHandshakePromise.addListener((FutureListener) f -> timeoutFuture.cancel(false)); } } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketExtensionFilter.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketExtensionFilter.java index 6485e276c6..caf765d630 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketExtensionFilter.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketExtensionFilter.java @@ -27,23 +27,13 @@ public interface WebSocketExtensionFilter { * A {@link WebSocketExtensionFilter} that never skip the evaluation of an * any given extensions {@link WebSocketExtension}. */ - WebSocketExtensionFilter NEVER_SKIP = new WebSocketExtensionFilter() { - @Override - public boolean mustSkip(WebSocketFrame frame) { - return false; - } - }; + WebSocketExtensionFilter NEVER_SKIP = frame -> false; /** * A {@link WebSocketExtensionFilter} that always skip the evaluation of an * any given extensions {@link WebSocketExtension}. */ - WebSocketExtensionFilter ALWAYS_SKIP = new WebSocketExtensionFilter() { - @Override - public boolean mustSkip(WebSocketFrame frame) { - return true; - } - }; + WebSocketExtensionFilter ALWAYS_SKIP = frame -> true; /** * Returns {@code true} if the evaluation of the extension must skipped diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketHandshakeHandOverTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketHandshakeHandOverTest.java index b6f28d5f28..dfd91091fb 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketHandshakeHandOverTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketHandshakeHandOverTest.java @@ -204,12 +204,7 @@ public class WebSocketHandshakeHandOverTest { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) { - ctx.channel().closeFuture().addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - clientForceClosed = true; - } - }); + ctx.channel().closeFuture().addListener((ChannelFutureListener) future -> clientForceClosed = true); handshaker.close(ctx.channel(), new CloseWebSocketFrame()); } } diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateDecoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateDecoderTest.java index 9529b4448b..51d1f55f15 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateDecoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateDecoderTest.java @@ -221,12 +221,8 @@ public class PerMessageDeflateDecoderTest { @Test public void testSelectivityDecompressionSkip() { - WebSocketExtensionFilter selectivityDecompressionFilter = new WebSocketExtensionFilter() { - @Override - public boolean mustSkip(WebSocketFrame frame) { - return frame instanceof TextWebSocketFrame && frame.content().readableBytes() < 100; - } - }; + WebSocketExtensionFilter selectivityDecompressionFilter = + frame -> frame instanceof TextWebSocketFrame && frame.content().readableBytes() < 100; EmbeddedChannel encoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); EmbeddedChannel decoderChannel = new EmbeddedChannel( @@ -266,12 +262,7 @@ public class PerMessageDeflateDecoderTest { @Test(expected = DecoderException.class) public void testIllegalStateWhenDecompressionInProgress() { - WebSocketExtensionFilter selectivityDecompressionFilter = new WebSocketExtensionFilter() { - @Override - public boolean mustSkip(WebSocketFrame frame) { - return frame.content().readableBytes() < 100; - } - }; + WebSocketExtensionFilter selectivityDecompressionFilter = frame -> frame.content().readableBytes() < 100; EmbeddedChannel encoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateEncoderTest.java index 1f8b47744a..ab8bbb8d29 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateEncoderTest.java @@ -190,13 +190,9 @@ public class PerMessageDeflateEncoderTest { @Test public void testSelectivityCompressionSkip() { - WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() { - @Override - public boolean mustSkip(WebSocketFrame frame) { - return (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame) - && frame.content().readableBytes() < 100; - } - }; + WebSocketExtensionFilter selectivityCompressionFilter = + frame -> (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame) + && frame.content().readableBytes() < 100; EmbeddedChannel encoderChannel = new EmbeddedChannel( new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter)); EmbeddedChannel decoderChannel = new EmbeddedChannel( @@ -238,12 +234,7 @@ public class PerMessageDeflateEncoderTest { @Test(expected = EncoderException.class) public void testIllegalStateWhenCompressionInProgress() { - WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() { - @Override - public boolean mustSkip(WebSocketFrame frame) { - return frame.content().readableBytes() < 100; - } - }; + WebSocketExtensionFilter selectivityCompressionFilter = frame -> frame.content().readableBytes() < 100; EmbeddedChannel encoderChannel = new EmbeddedChannel( new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter)); diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java index c6c6ee04de..464ee88226 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java @@ -114,12 +114,8 @@ abstract class AbstractHttp2StreamChannel extends DefaultAttributeMap implements } } - private final ChannelFutureListener windowUpdateFrameWriteListener = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { + private final ChannelFutureListener windowUpdateFrameWriteListener = future -> windowUpdateFrameWriteComplete(future, AbstractHttp2StreamChannel.this); - } - }; /** * The current status of the read-processing for a {@link AbstractHttp2StreamChannel}. 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 c900e98eb7..f034345887 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 @@ -497,14 +497,11 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http closeListener = listener; } else if (promise != null) { final ChannelFutureListener oldCloseListener = closeListener; - closeListener = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - try { - oldCloseListener.operationComplete(future); - } finally { - listener.operationComplete(future); - } + closeListener = future1 -> { + try { + oldCloseListener.operationComplete(future1); + } finally { + listener.operationComplete(future1); } }; } 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 f10574d288..c6dbd05105 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 @@ -249,12 +249,7 @@ public class Http2FrameCodec extends Http2ConnectionHandler { // We schedule this on the EventExecutor to allow to have any extra handlers added to the pipeline // before we pass the event to the next handler. This is needed as the event may be called from within // handlerAdded(...) which will be run before other handlers will be added to the pipeline. - ctx.executor().execute(new Runnable() { - @Override - public void run() { - ctx.fireUserEventTriggered(evt); - } - }); + ctx.executor().execute(() -> ctx.fireUserEventTriggered(evt)); } else if (evt instanceof UpgradeEvent) { UpgradeEvent upgrade = (UpgradeEvent) evt; try { diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowControllerTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowControllerTest.java index cea7793a4e..706dfe5907 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowControllerTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowControllerTest.java @@ -27,7 +27,6 @@ import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -43,7 +42,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** @@ -81,12 +79,7 @@ public class DefaultHttp2LocalFlowControllerTest { reset(ctx); when(ctx.newPromise()).thenReturn(promise); if (allowFlush) { - when(ctx.flush()).then(new Answer() { - @Override - public ChannelHandlerContext answer(InvocationOnMock invocationOnMock) { - return ctx; - } - }); + when(ctx.flush()).then((Answer) invocationOnMock -> ctx); } else { when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden")); } 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 3e0d341651..2ba75c005e 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 @@ -41,7 +41,6 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.concurrent.CountDownLatch; @@ -743,38 +742,23 @@ public class Http2ConnectionHandlerTest { when(stream.id()).thenReturn(STREAM_ID); final AtomicBoolean resetSent = new AtomicBoolean(); - when(stream.resetSent()).then(new Answer() { - @Override - public Http2Stream answer(InvocationOnMock invocationOnMock) { - resetSent.set(true); - return stream; - } - }); - when(stream.isResetSent()).then(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocationOnMock) { - return resetSent.get(); - } + when(stream.resetSent()).then((Answer) invocationOnMock -> { + resetSent.set(true); + return stream; }); + when(stream.isResetSent()).then((Answer) invocationOnMock -> resetSent.get()); when(frameWriter.writeRstStream(eq(ctx), eq(STREAM_ID), anyLong(), any(ChannelPromise.class))) - .then(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable { - ChannelPromise promise = invocationOnMock.getArgument(3); - return promise.setSuccess(); - } + .then((Answer) invocationOnMock -> { + ChannelPromise promise = invocationOnMock.getArgument(3); + return promise.setSuccess(); }); ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); final ChannelPromise promise2 = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - handler.resetStream(ctx, STREAM_ID, STREAM_CLOSED.code(), promise2); - } - }); + promise.addListener((ChannelFutureListener) future -> + handler.resetStream(ctx, STREAM_ID, STREAM_CLOSED.code(), promise2)); handler.resetStream(ctx, STREAM_ID, CANCEL.code(), promise); verify(frameWriter).writeRstStream(eq(ctx), eq(STREAM_ID), anyLong(), any(ChannelPromise.class)); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ControlFrameLimitEncoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ControlFrameLimitEncoderTest.java index bbae3af5ae..27ecf27e7e 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ControlFrameLimitEncoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ControlFrameLimitEncoderTest.java @@ -25,7 +25,6 @@ import io.netty.channel.ChannelMetadata; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.DefaultMessageSizeEstimator; -import io.netty.handler.codec.http2.Http2Exception.ShutdownHint; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.ImmediateEventExecutor; @@ -92,40 +91,24 @@ public class Http2ControlFrameLimitEncoderTest { when(frameSizePolicy.maxFrameSize()).thenReturn(DEFAULT_MAX_FRAME_SIZE); when(writer.writeRstStream(eq(ctx), anyInt(), anyLong(), any(ChannelPromise.class))) - .thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return handlePromise(invocationOnMock, 3); - } - }); + .thenAnswer((Answer) invocationOnMock -> handlePromise(invocationOnMock, 3)); when(writer.writeSettingsAck(any(ChannelHandlerContext.class), any(ChannelPromise.class))) - .thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - return handlePromise(invocationOnMock, 1); - } - }); + .thenAnswer((Answer) invocationOnMock -> handlePromise(invocationOnMock, 1)); when(writer.writePing(any(ChannelHandlerContext.class), anyBoolean(), anyLong(), any(ChannelPromise.class))) - .thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - ChannelPromise promise = handlePromise(invocationOnMock, 3); - if (invocationOnMock.getArgument(1) == Boolean.FALSE) { - promise.trySuccess(); - } - return promise; + .thenAnswer((Answer) invocationOnMock -> { + ChannelPromise promise = handlePromise(invocationOnMock, 3); + if (invocationOnMock.getArgument(1) == Boolean.FALSE) { + promise.trySuccess(); } + return promise; }); when(writer.writeGoAway(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), - any(ChannelPromise.class))).thenAnswer(new Answer() { - @Override - public ChannelFuture answer(InvocationOnMock invocationOnMock) { - ReferenceCountUtil.release(invocationOnMock.getArgument(3)); - ChannelPromise promise = invocationOnMock.getArgument(4); - goAwayPromises.offer(promise); - return promise; - } - }); + any(ChannelPromise.class))).thenAnswer((Answer) invocationOnMock -> { + ReferenceCountUtil.release(invocationOnMock.getArgument(3)); + ChannelPromise promise = invocationOnMock.getArgument(4); + goAwayPromises.offer(promise); + return promise; + }); Http2Connection connection = new DefaultHttp2Connection(false); connection.remote().flowController(new DefaultHttp2RemoteFlowController(connection)); connection.local().flowController(new DefaultHttp2LocalFlowController(connection).frameWriter(writer)); @@ -144,12 +127,7 @@ public class Http2ControlFrameLimitEncoderTest { 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); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2EmptyDataFrameConnectionDecoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2EmptyDataFrameConnectionDecoderTest.java index 346a09a863..87945c561c 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2EmptyDataFrameConnectionDecoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2EmptyDataFrameConnectionDecoderTest.java @@ -17,7 +17,6 @@ package io.netty.handler.codec.http2; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.junit.Assert.assertNull; @@ -33,12 +32,8 @@ public class Http2EmptyDataFrameConnectionDecoderTest { Http2ConnectionDecoder delegate = mock(Http2ConnectionDecoder.class); final ArgumentCaptor listenerArgumentCaptor = ArgumentCaptor.forClass(Http2FrameListener.class); - when(delegate.frameListener()).then(new Answer() { - @Override - public Http2FrameListener answer(InvocationOnMock invocationOnMock) { - return listenerArgumentCaptor.getValue(); - } - }); + when(delegate.frameListener()).then( + (Answer) invocationOnMock -> listenerArgumentCaptor.getValue()); Http2FrameListener listener = mock(Http2FrameListener.class); Http2EmptyDataFrameConnectionDecoder decoder = new Http2EmptyDataFrameConnectionDecoder(delegate, 2); decoder.frameListener(listener); diff --git a/common/src/main/java/io/netty/util/internal/Hidden.java b/common/src/main/java/io/netty/util/internal/Hidden.java index 0603f6d8f9..86348a04d5 100644 --- a/common/src/main/java/io/netty/util/internal/Hidden.java +++ b/common/src/main/java/io/netty/util/internal/Hidden.java @@ -20,8 +20,6 @@ import io.netty.util.concurrent.FastThreadLocalThread; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; -import java.util.function.Function; -import java.util.function.Predicate; /** * Contains classes that must be have public visibility but are not public API. @@ -64,18 +62,8 @@ class Hidden { "confirmShutdown" ); - builder.nonBlockingThreadPredicate(new Function, Predicate>() { - @Override - public Predicate apply(final Predicate p) { - return new Predicate() { - @Override - @SuppressJava6Requirement(reason = "Predicate#test") - public boolean test(Thread thread) { - return p.test(thread) || thread instanceof FastThreadLocalThread; - } - }; - } - }); + builder.nonBlockingThreadPredicate(p -> thread -> + p.test(thread) || thread instanceof FastThreadLocalThread); } } } diff --git a/common/src/main/java/io/netty/util/internal/PendingWrite.java b/common/src/main/java/io/netty/util/internal/PendingWrite.java index f84826caf4..f315059a09 100644 --- a/common/src/main/java/io/netty/util/internal/PendingWrite.java +++ b/common/src/main/java/io/netty/util/internal/PendingWrite.java @@ -18,18 +18,12 @@ package io.netty.util.internal; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.Promise; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; /** * Some pending write which should be picked up later. */ public final class PendingWrite { - private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() { - @Override - public PendingWrite newObject(Handle handle) { - return new PendingWrite(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(PendingWrite::new); /** * Create a new empty {@link RecyclableArrayList} instance diff --git a/common/src/main/java/io/netty/util/internal/RecyclableArrayList.java b/common/src/main/java/io/netty/util/internal/RecyclableArrayList.java index fc86284017..01f325ba5a 100644 --- a/common/src/main/java/io/netty/util/internal/RecyclableArrayList.java +++ b/common/src/main/java/io/netty/util/internal/RecyclableArrayList.java @@ -19,7 +19,6 @@ package io.netty.util.internal; import static java.util.Objects.requireNonNull; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import java.util.ArrayList; import java.util.Collection; @@ -35,13 +34,7 @@ public final class RecyclableArrayList extends ArrayList { private static final int DEFAULT_INITIAL_CAPACITY = 8; - private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public RecyclableArrayList newObject(Handle handle) { - return new RecyclableArrayList(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(RecyclableArrayList::new); private boolean insertSinceRecycled; diff --git a/common/src/main/java/io/netty/util/internal/ThreadExecutorMap.java b/common/src/main/java/io/netty/util/internal/ThreadExecutorMap.java index 2f0f23f7e8..5467ccf1e1 100644 --- a/common/src/main/java/io/netty/util/internal/ThreadExecutorMap.java +++ b/common/src/main/java/io/netty/util/internal/ThreadExecutorMap.java @@ -52,12 +52,7 @@ public final class ThreadExecutorMap { public static Executor apply(final Executor executor, final EventExecutor eventExecutor) { Objects.requireNonNull(executor, "executor"); Objects.requireNonNull(eventExecutor, "eventExecutor"); - return new Executor() { - @Override - public void execute(final Runnable command) { - executor.execute(apply(command, eventExecutor)); - } - }; + return command -> executor.execute(apply(command, eventExecutor)); } /** @@ -67,15 +62,12 @@ public final class ThreadExecutorMap { public static Runnable apply(final Runnable command, final EventExecutor eventExecutor) { Objects.requireNonNull(command, "command"); Objects.requireNonNull(eventExecutor, "eventExecutor"); - return new Runnable() { - @Override - public void run() { - setCurrentEventExecutor(eventExecutor); - try { - command.run(); - } finally { - setCurrentEventExecutor(null); - } + return () -> { + setCurrentEventExecutor(eventExecutor); + try { + command.run(); + } finally { + setCurrentEventExecutor(null); } }; } @@ -87,11 +79,6 @@ public final class ThreadExecutorMap { public static ThreadFactory apply(final ThreadFactory threadFactory, final EventExecutor eventExecutor) { Objects.requireNonNull(threadFactory, "command"); Objects.requireNonNull(eventExecutor, "eventExecutor"); - return new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return threadFactory.newThread(apply(r, eventExecutor)); - } - }; + return r -> threadFactory.newThread(apply(r, eventExecutor)); } } 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 0e2f7759ba..3486f9a4eb 100644 --- a/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java +++ b/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java @@ -193,10 +193,7 @@ public class SingleThreadEventExecutorTest { } }; - final Runnable dummyTask = new Runnable() { - @Override - public void run() { - } + final Runnable dummyTask = () -> { }; final LinkedBlockingQueue> submittedTasks = new LinkedBlockingQueue>(); diff --git a/common/src/test/java/io/netty/util/internal/ThreadExecutorMapTest.java b/common/src/test/java/io/netty/util/internal/ThreadExecutorMapTest.java index 22069e4b30..83e301d145 100644 --- a/common/src/test/java/io/netty/util/internal/ThreadExecutorMapTest.java +++ b/common/src/test/java/io/netty/util/internal/ThreadExecutorMapTest.java @@ -29,34 +29,22 @@ public class ThreadExecutorMapTest { @Test public void testDecorateExecutor() { Executor executor = ThreadExecutorMap.apply(ImmediateExecutor.INSTANCE, ImmediateEventExecutor.INSTANCE); - executor.execute(new Runnable() { - @Override - public void run() { - Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor()); - } - }); + executor.execute(() -> Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor())); } @Test public void testDecorateRunnable() { - ThreadExecutorMap.apply(new Runnable() { - @Override - public void run() { - Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor()); - } - }, ImmediateEventExecutor.INSTANCE).run(); + ThreadExecutorMap.apply(() -> + Assert.assertSame(ImmediateEventExecutor.INSTANCE, + ThreadExecutorMap.currentExecutor()), ImmediateEventExecutor.INSTANCE).run(); } @Test public void testDecorateThreadFactory() throws InterruptedException { ThreadFactory threadFactory = ThreadExecutorMap.apply(Executors.defaultThreadFactory(), ImmediateEventExecutor.INSTANCE); - Thread thread = threadFactory.newThread(new Runnable() { - @Override - public void run() { - Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor()); - } - }); + Thread thread = threadFactory.newThread(() -> Assert.assertSame(ImmediateEventExecutor.INSTANCE, + ThreadExecutorMap.currentExecutor())); thread.start(); thread.join(); } diff --git a/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java b/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java index dc94e66c0a..a40961315b 100644 --- a/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java +++ b/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java @@ -26,7 +26,6 @@ import io.netty.handler.codec.MessageToByteEncoder; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; @@ -218,12 +217,7 @@ public class FlowControlHandler implements ChannelHandler { private static final int DEFAULT_NUM_ELEMENTS = 2; private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectCreator() { - @Override - public RecyclableArrayDeque newObject(Handle handle) { - return new RecyclableArrayDeque(DEFAULT_NUM_ELEMENTS, handle); - } - }); + handle -> new RecyclableArrayDeque(DEFAULT_NUM_ELEMENTS, handle)); public static RecyclableArrayDeque newInstance() { return RECYCLER.get(); diff --git a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java index b71d01bb10..844cd593bf 100644 --- a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java @@ -1351,19 +1351,16 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc if (task == null) { return null; } - return new Runnable() { - @Override - public void run() { - if (isDestroyed()) { - // The engine was destroyed in the meantime, just return. - return; - } - try { - task.run(); - } finally { - // The task was run, reset needTask to false so getHandshakeStatus() returns the correct value. - needTask = false; - } + return () -> { + if (isDestroyed()) { + // The engine was destroyed in the meantime, just return. + return; + } + try { + task.run(); + } finally { + // The task was run, reset needTask to false so getHandshakeStatus() returns the correct value. + needTask = false; } }; } 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 ea8d4d296c..818287a362 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -945,13 +945,10 @@ public class SslHandler extends ByteToMessageDecoder { SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out); if (result.bytesProduced() > 0) { - ctx.write(out).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - Throwable cause = future.cause(); - if (cause != null) { - setHandshakeFailureTransportFailure(ctx, cause); - } + ctx.write(out).addListener((ChannelFutureListener) future -> { + Throwable cause = future.cause(); + if (cause != null) { + setHandshakeFailureTransportFailure(ctx, cause); } }); if (inUnwrap) { diff --git a/handler/src/test/java/io/netty/handler/flush/FlushConsolidationHandlerTest.java b/handler/src/test/java/io/netty/handler/flush/FlushConsolidationHandlerTest.java index 12ff91f308..bb25e465a2 100644 --- a/handler/src/test/java/io/netty/handler/flush/FlushConsolidationHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/flush/FlushConsolidationHandlerTest.java @@ -18,8 +18,6 @@ package io.netty.handler.flush; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.embedded.EmbeddedChannel; -import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.GenericFutureListener; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; @@ -163,12 +161,7 @@ public class FlushConsolidationHandlerTest { public void testResend() throws Exception { final AtomicInteger flushCount = new AtomicInteger(); final EmbeddedChannel channel = newChannel(flushCount, true); - channel.writeAndFlush(1L).addListener(new GenericFutureListener>() { - @Override - public void operationComplete(Future future) throws Exception { - channel.writeAndFlush(1L); - } - }); + channel.writeAndFlush(1L).addListener(future -> channel.writeAndFlush(1L)); channel.flushOutbound(); assertEquals(1L, ((Long) channel.readOutbound()).longValue()); assertEquals(1L, ((Long) channel.readOutbound()).longValue()); diff --git a/handler/src/test/java/io/netty/handler/ssl/OpenSslPrivateKeyMethodTest.java b/handler/src/test/java/io/netty/handler/ssl/OpenSslPrivateKeyMethodTest.java index 5e8a35cd08..1e95b04f7c 100644 --- a/handler/src/test/java/io/netty/handler/ssl/OpenSslPrivateKeyMethodTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/OpenSslPrivateKeyMethodTest.java @@ -62,7 +62,6 @@ import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -100,12 +99,7 @@ public class OpenSslPrivateKeyMethodTest { GROUP = new MultithreadEventLoopGroup(LocalHandler.newFactory()); CERT = new SelfSignedCertificate(); - EXECUTOR = Executors.newCachedThreadPool(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new DelegateThread(r); - } - }); + EXECUTOR = Executors.newCachedThreadPool(DelegateThread::new); } @AfterClass 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 e75b3c2354..b3a67c915d 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java @@ -123,12 +123,9 @@ public class SslHandlerTest { try { final CountDownLatch writeCauseLatch = new CountDownLatch(1); final AtomicReference failureRef = new AtomicReference(); - ch.write(Unpooled.wrappedBuffer(new byte[]{1})).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - failureRef.compareAndSet(null, future.cause()); - writeCauseLatch.countDown(); - } + ch.write(Unpooled.wrappedBuffer(new byte[]{1})).addListener((ChannelFutureListener) future -> { + failureRef.compareAndSet(null, future.cause()); + writeCauseLatch.countDown(); }); writeLatch.await(); 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 010d98851a..3847c09f73 100644 --- a/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java @@ -513,12 +513,9 @@ public class ChunkedWriteHandlerTest { final CountDownLatch listenerInvoked = new CountDownLatch(1); ChannelFuture writeFuture = ch.write(input); - writeFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - inputClosedWhenListenerInvoked.set(input.isClosed()); - listenerInvoked.countDown(); - } + writeFuture.addListener((ChannelFutureListener) future -> { + inputClosedWhenListenerInvoked.set(input.isClosed()); + listenerInvoked.countDown(); }); ch.flush(); @@ -537,12 +534,9 @@ public class ChunkedWriteHandlerTest { final CountDownLatch listenerInvoked = new CountDownLatch(1); ChannelFuture writeFuture = ch.write(input); - writeFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - inputClosedWhenListenerInvoked.set(input.isClosed()); - listenerInvoked.countDown(); - } + writeFuture.addListener((ChannelFutureListener) future -> { + inputClosedWhenListenerInvoked.set(input.isClosed()); + listenerInvoked.countDown(); }); ch.flush(); @@ -562,12 +556,9 @@ public class ChunkedWriteHandlerTest { final CountDownLatch listenerInvoked = new CountDownLatch(1); ChannelFuture writeFuture = ch.write(input); - writeFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - inputClosedWhenListenerInvoked.set(input.isClosed()); - listenerInvoked.countDown(); - } + writeFuture.addListener((ChannelFutureListener) future -> { + inputClosedWhenListenerInvoked.set(input.isClosed()); + listenerInvoked.countDown(); }); ch.close(); // close channel to make handler discard the input on subsequent flush ch.flush(); @@ -588,12 +579,9 @@ public class ChunkedWriteHandlerTest { final CountDownLatch listenerInvoked = new CountDownLatch(1); ChannelFuture writeFuture = ch.write(input); - writeFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - inputClosedWhenListenerInvoked.set(input.isClosed()); - listenerInvoked.countDown(); - } + writeFuture.addListener((ChannelFutureListener) future -> { + inputClosedWhenListenerInvoked.set(input.isClosed()); + listenerInvoked.countDown(); }); ch.close(); // close channel to make handler discard the input on subsequent flush ch.flush(); 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 c70f3f9b83..3351f2ffbe 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 @@ -37,10 +37,7 @@ import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.TearDown; public class EpollSocketChannelBenchmark extends AbstractMicrobenchmark { - private static final Runnable runnable = new Runnable() { - @Override - public void run() { } - }; + private static final Runnable runnable = () -> { }; private EventLoopGroup group; private Channel serverChan; 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 34ebad5d84..9456fa8058 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 @@ -1211,81 +1211,78 @@ public class DnsNameResolver extends InetNameResolver { .group(executor()) .channelFactory(socketChannelFactory) .handler(TCP_ENCODER); - bs.connect(res.sender()).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (!future.isSuccess()) { - if (logger.isDebugEnabled()) { - logger.debug("{} Unable to fallback to TCP [{}]", queryId, future.cause()); - } - - // TCP fallback failed, just use the truncated response. - qCtx.finish(res); - return; + bs.connect(res.sender()).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + if (logger.isDebugEnabled()) { + logger.debug("{} Unable to fallback to TCP [{}]", queryId, future.cause()); } - final Channel channel = future.channel(); - Promise> promise = - channel.eventLoop().newPromise(); - final TcpDnsQueryContext tcpCtx = new TcpDnsQueryContext(DnsNameResolver.this, channel, - (InetSocketAddress) channel.remoteAddress(), qCtx.question(), - EMPTY_ADDITIONALS, promise); - - channel.pipeline().addLast(new TcpDnsResponseDecoder()); - channel.pipeline().addLast(new ChannelHandler() { - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) { - Channel channel = ctx.channel(); - DnsResponse response = (DnsResponse) msg; - int queryId = response.id(); - - if (logger.isDebugEnabled()) { - logger.debug("{} RECEIVED: TCP [{}: {}], {}", channel, queryId, - channel.remoteAddress(), response); - } - - DnsQueryContext foundCtx = queryContextManager.get(res.sender(), queryId); - if (foundCtx == tcpCtx) { - tcpCtx.finish(new AddressedEnvelopeAdapter( - (InetSocketAddress) ctx.channel().remoteAddress(), - (InetSocketAddress) ctx.channel().localAddress(), - response)); - } else { - response.release(); - tcpCtx.tryFailure("Received TCP response with unexpected ID", null, false); - logger.warn("{} Received a DNS response with an unexpected ID: {}", - channel, queryId); - } - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - if (tcpCtx.tryFailure("TCP fallback error", cause, false) && logger.isDebugEnabled()) { - logger.debug("{} Error during processing response: TCP [{}: {}]", - ctx.channel(), queryId, - ctx.channel().remoteAddress(), cause); - } - } - }); - - promise.addListener( - new FutureListener>() { - @Override - public void operationComplete( - Future> future) { - channel.close(); - - if (future.isSuccess()) { - qCtx.finish(future.getNow()); - res.release(); - } else { - // TCP fallback failed, just use the truncated response. - qCtx.finish(res); - } - } - }); - tcpCtx.query(true, future.channel().newPromise()); + // TCP fallback failed, just use the truncated response. + qCtx.finish(res); + return; } + final Channel channel = future.channel(); + + Promise> promise = + channel.eventLoop().newPromise(); + final TcpDnsQueryContext tcpCtx = new TcpDnsQueryContext(DnsNameResolver.this, channel, + (InetSocketAddress) channel.remoteAddress(), qCtx.question(), + EMPTY_ADDITIONALS, promise); + + channel.pipeline().addLast(new TcpDnsResponseDecoder()); + channel.pipeline().addLast(new ChannelHandler() { + @Override + public void channelRead(ChannelHandlerContext ctx1, Object msg1) { + Channel channel = ctx1.channel(); + DnsResponse response = (DnsResponse) msg1; + int queryId1 = response.id(); + + if (logger.isDebugEnabled()) { + logger.debug("{} RECEIVED: TCP [{}: {}], {}", channel, queryId1, + channel.remoteAddress(), response); + } + + DnsQueryContext foundCtx = queryContextManager.get(res.sender(), queryId1); + if (foundCtx == tcpCtx) { + tcpCtx.finish(new AddressedEnvelopeAdapter( + (InetSocketAddress) ctx1.channel().remoteAddress(), + (InetSocketAddress) ctx1.channel().localAddress(), + response)); + } else { + response.release(); + tcpCtx.tryFailure("Received TCP response with unexpected ID", null, false); + logger.warn("{} Received a DNS response with an unexpected ID: {}", + channel, queryId1); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx1, Throwable cause) { + if (tcpCtx.tryFailure("TCP fallback error", cause, false) && logger.isDebugEnabled()) { + logger.debug("{} Error during processing response: TCP [{}: {}]", + ctx1.channel(), queryId, + ctx1.channel().remoteAddress(), cause); + } + } + }); + + promise.addListener( + new FutureListener>() { + @Override + public void operationComplete( + Future> future) { + channel.close(); + + if (future.isSuccess()) { + qCtx.finish(future.getNow()); + res.release(); + } else { + // TCP fallback failed, just use the truncated response. + qCtx.finish(res); + } + } + }); + tcpCtx.query(true, future.channel().newPromise()); }); } 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 165e229952..d1203dd61e 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 @@ -2467,24 +2467,20 @@ public class DnsNameResolverTest { final String txt1 = "some text"; final String txt2 = "some more text"; - TestDnsServer server = new TestDnsServer(new RecordStore() { + TestDnsServer server = new TestDnsServer(question -> { + if (question.getDomainName().equals(hostname)) { + Map map1 = new HashMap(); + map1.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt1); - @Override - public Set getRecords(QuestionRecord question) { - if (question.getDomainName().equals(hostname)) { - Map map1 = new HashMap(); - map1.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt1); + Map map2 = new HashMap(); + map2.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt2); - Map map2 = new HashMap(); - map2.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt2); - - Set records = new HashSet(); - records.add(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.TXT, map1)); - records.add(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.TXT, map2)); - return records; - } - return Collections.emptySet(); + Set records = new HashSet(); + records.add(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.TXT, map1)); + records.add(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.TXT, map2)); + return records; } + return Collections.emptySet(); }); server.start(); DnsNameResolver resolver = newResolver(ResolvedAddressTypes.IPV4_ONLY) @@ -2536,26 +2532,23 @@ public class DnsNameResolverTest { public void testNotIncludeDuplicates() throws IOException { final String name = "netty.io"; final String ipv4Addr = "1.2.3.4"; - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) { - Set records = new LinkedHashSet(4); - String qName = question.getDomainName().toLowerCase(); - if (qName.equals(name)) { - records.add(new TestDnsServer.TestResourceRecord( - qName, RecordType.CNAME, - Collections.singletonMap( - DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); - records.add(new TestDnsServer.TestResourceRecord(qName, - RecordType.A, Collections.singletonMap( - DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); - } else { - records.add(new TestDnsServer.TestResourceRecord(qName, - RecordType.A, Collections.singletonMap( - DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); - } - return records; + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + Set records = new LinkedHashSet(4); + String qName = question.getDomainName().toLowerCase(); + if (qName.equals(name)) { + records.add(new TestDnsServer.TestResourceRecord( + qName, RecordType.CNAME, + Collections.singletonMap( + DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); + records.add(new TestDnsServer.TestResourceRecord(qName, + RecordType.A, Collections.singletonMap( + DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); + } else { + records.add(new TestDnsServer.TestResourceRecord(qName, + RecordType.A, Collections.singletonMap( + DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); } + return records; }); dnsServer2.start(); DnsNameResolver resolver = null; @@ -2582,19 +2575,16 @@ public class DnsNameResolverTest { public void testIncludeDuplicates() throws IOException { final String name = "netty.io"; final String ipv4Addr = "1.2.3.4"; - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) { - Set records = new LinkedHashSet(2); - String qName = question.getDomainName().toLowerCase(); - records.add(new TestDnsServer.TestResourceRecord(qName, - RecordType.A, Collections.singletonMap( - DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); - records.add(new TestDnsServer.TestResourceRecord(qName, - RecordType.A, Collections.singletonMap( - DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); - return records; - } + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + Set records = new LinkedHashSet(2); + String qName = question.getDomainName().toLowerCase(); + records.add(new TestDnsServer.TestResourceRecord(qName, + RecordType.A, Collections.singletonMap( + DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); + records.add(new TestDnsServer.TestResourceRecord(qName, + RecordType.A, Collections.singletonMap( + DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); + return records; }); dnsServer2.start(); DnsNameResolver resolver = null; @@ -2674,22 +2664,19 @@ public class DnsNameResolverTest { @Test(timeout = 2000) public void testDropAAAAResolveAllFast() throws IOException { final String host = "somehost.netty.io"; - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) throws DnsException { - String name = question.getDomainName(); - if (name.equals(host)) { - Set records = new HashSet(2); - records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, - Collections.singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), - "10.0.0.1"))); - records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, - Collections.singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), - "10.0.0.2"))); - return records; - } - return null; + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + String name = question.getDomainName(); + if (name.equals(host)) { + Set records = new HashSet(2); + records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, + Collections.singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), + "10.0.0.1"))); + records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, + Collections.singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), + "10.0.0.2"))); + return records; } + return null; }); dnsServer2.start(true); DnsNameResolver resolver = null; @@ -2756,18 +2743,15 @@ public class DnsNameResolverTest { final String txt = "this is a txt record"; final AtomicReference messageRef = new AtomicReference(); - TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { - @Override - public Set getRecords(QuestionRecord question) { - String name = question.getDomainName(); - if (name.equals(host)) { - return Collections.singleton( - new TestDnsServer.TestResourceRecord(name, RecordType.TXT, - Collections.singletonMap( - DnsAttribute.CHARACTER_STRING.toLowerCase(), txt))); - } - return null; + TestDnsServer dnsServer2 = new TestDnsServer(question -> { + String name = question.getDomainName(); + if (name.equals(host)) { + return Collections.singleton( + new TestDnsServer.TestResourceRecord(name, RecordType.TXT, + Collections.singletonMap( + DnsAttribute.CHARACTER_STRING.toLowerCase(), txt))); } + return null; }) { @Override protected DnsMessage filterMessage(DnsMessage message) { diff --git a/testsuite-osgi/src/test/java/io/netty/osgitests/OsgiBundleTest.java b/testsuite-osgi/src/test/java/io/netty/osgitests/OsgiBundleTest.java index a55a436d73..ab384b5c0e 100644 --- a/testsuite-osgi/src/test/java/io/netty/osgitests/OsgiBundleTest.java +++ b/testsuite-osgi/src/test/java/io/netty/osgitests/OsgiBundleTest.java @@ -24,7 +24,6 @@ import static org.ops4j.pax.exam.CoreOptions.url; import static org.osgi.framework.Constants.FRAMEWORK_BOOTDELEGATION; import java.io.File; -import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -45,12 +44,8 @@ public class OsgiBundleTest { final Set links = new HashSet(); final File directory = new File("target/generated-test-resources/alta/"); - File[] files = directory.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return (name.startsWith("io.netty") || name.startsWith("com.barchart.udt")) && name.endsWith(".link"); - } - }); + File[] files = directory.listFiles((dir, name) -> + (name.startsWith("io.netty") || name.startsWith("com.barchart.udt")) && name.endsWith(".link")); if (files == null) { throw new IllegalStateException(directory + " is not found or is not a directory"); } diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/AbstractSingleThreadEventLoopTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/AbstractSingleThreadEventLoopTest.java index 4b7ef60383..64227e3fb9 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/AbstractSingleThreadEventLoopTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/AbstractSingleThreadEventLoopTest.java @@ -86,12 +86,7 @@ public abstract class AbstractSingleThreadEventLoopTest { public void gracefulShutdownAfterStart() throws Exception { EventLoop loop = new MultithreadEventLoopGroup(newIoHandlerFactory()).next(); final CountDownLatch latch = new CountDownLatch(1); - loop.execute(new Runnable() { - @Override - public void run() { - latch.countDown(); - } - }); + loop.execute(latch::countDown); // Wait for the event loop thread to start. latch.await(); @@ -105,10 +100,7 @@ public abstract class AbstractSingleThreadEventLoopTest { assertRejection(loop); } - private static final Runnable NOOP = new Runnable() { - @Override - public void run() { } - }; + private static final Runnable NOOP = () -> { }; private static void assertRejection(EventExecutor loop) { try { diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/AbstractSocketReuseFdTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/AbstractSocketReuseFdTest.java index a66afff3cb..0bd567f895 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/AbstractSocketReuseFdTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/AbstractSocketReuseFdTest.java @@ -20,7 +20,6 @@ import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; @@ -87,12 +86,9 @@ public abstract class AbstractSocketReuseFdTest extends AbstractSocketTest { } }); - ChannelFutureListener listener = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (!future.isSuccess()) { - clientDonePromise.tryFailure(future.cause()); - } + ChannelFutureListener listener = future -> { + if (!future.isSuccess()) { + clientDonePromise.tryFailure(future.cause()); } }; diff --git a/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java b/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java index 3259f19515..d921ae9bdd 100644 --- a/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java +++ b/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java @@ -24,7 +24,6 @@ import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.internal.InternalThreadLocalMap; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool.Handle; -import io.netty.util.internal.ObjectPool.ObjectCreator; import io.netty.util.internal.PromiseNotificationUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; @@ -788,12 +787,7 @@ public final class ChannelOutboundBuffer { } static final class Entry { - private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() { - @Override - public Entry newObject(Handle handle) { - return new Entry(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(Entry::new); private final Handle handle; Entry next; diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java index 929075f6c7..aa79904c8a 100644 --- a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java +++ b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java @@ -966,13 +966,7 @@ final class DefaultChannelHandlerContext implements ChannelHandlerContext, Resou static final class WriteTask extends AbstractWriteTask implements SingleThreadEventLoop.NonWakeupRunnable { - private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectPool.ObjectCreator() { - @Override - public WriteTask newObject(ObjectPool.Handle handle) { - return new WriteTask(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(WriteTask::new); static WriteTask newInstance( DefaultChannelHandlerContext ctx, Object msg, ChannelPromise promise) { @@ -993,13 +987,7 @@ final class DefaultChannelHandlerContext implements ChannelHandlerContext, Resou static final class WriteAndFlushTask extends AbstractWriteTask { - private static final ObjectPool RECYCLER = ObjectPool.newPool( - new ObjectPool.ObjectCreator() { - @Override - public WriteAndFlushTask newObject(ObjectPool.Handle handle) { - return new WriteAndFlushTask(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(WriteAndFlushTask::new); static WriteAndFlushTask newInstance( DefaultChannelHandlerContext ctx, Object msg, ChannelPromise promise) { diff --git a/transport/src/main/java/io/netty/channel/PendingWriteQueue.java b/transport/src/main/java/io/netty/channel/PendingWriteQueue.java index 3b692d4c8a..6b7d918cf2 100644 --- a/transport/src/main/java/io/netty/channel/PendingWriteQueue.java +++ b/transport/src/main/java/io/netty/channel/PendingWriteQueue.java @@ -20,7 +20,6 @@ import static java.util.Objects.requireNonNull; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.PromiseCombiner; import io.netty.util.internal.ObjectPool; -import io.netty.util.internal.ObjectPool.ObjectCreator; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; @@ -286,12 +285,7 @@ public final class PendingWriteQueue { * Holds all meta-data and construct the linked-list structure. */ static final class PendingWrite { - private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() { - @Override - public PendingWrite newObject(ObjectPool.Handle handle) { - return new PendingWrite(handle); - } - }); + private static final ObjectPool RECYCLER = ObjectPool.newPool(PendingWrite::new); private final ObjectPool.Handle handle; private PendingWrite next; diff --git a/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java b/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java index 6125296e00..9fca86df87 100644 --- a/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java +++ b/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java @@ -1608,22 +1608,19 @@ public class DefaultChannelPipelineTest { assertEquals(expectedNumber, pipeline.names().size()); assertEquals(expectedNumber, pipeline.toMap().size()); - pipeline.executor().submit(new Runnable() { - @Override - public void run() { - DefaultChannelHandlerContext ctx = (DefaultChannelHandlerContext) pipeline.firstContext(); - int handlerNumber = 0; - if (ctx != null) { - for (;;) { - handlerNumber++; - if (ctx == pipeline.lastContext()) { - break; - } - ctx = ctx.next; + pipeline.executor().submit(() -> { + DefaultChannelHandlerContext ctx = (DefaultChannelHandlerContext) pipeline.firstContext(); + int handlerNumber = 0; + if (ctx != null) { + for (;;) { + handlerNumber++; + if (ctx == pipeline.lastContext()) { + break; } + ctx = ctx.next; } - assertEquals(expectedNumber, handlerNumber); } + assertEquals(expectedNumber, handlerNumber); }).syncUninterruptibly(); } diff --git a/transport/src/test/java/io/netty/channel/PendingWriteQueueTest.java b/transport/src/test/java/io/netty/channel/PendingWriteQueueTest.java index 8d63c59e7b..152c2dbeb0 100644 --- a/transport/src/test/java/io/netty/channel/PendingWriteQueueTest.java +++ b/transport/src/test/java/io/netty/channel/PendingWriteQueueTest.java @@ -295,13 +295,10 @@ public class PendingWriteQueueTest { }); ChannelPromise promise2 = channel.newPromise(); promise2.addListener((ChannelFutureListener) future -> failOrder.add(2)); - channel.eventLoop().execute(new Runnable() { - @Override - public void run() { - queue.add(1L, promise); - queue.add(2L, promise2); - queue.removeAndFailAll(new Exception()); - } + channel.eventLoop().execute(() -> { + queue.add(1L, promise); + queue.add(2L, promise2); + queue.removeAndFailAll(new Exception()); }); assertTrue(promise.isDone());