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
This commit is contained in:
Norman Maurer 2020-01-30 09:28:24 +01:00 committed by GitHub
parent 6b6782ea01
commit 6a43807843
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 283 additions and 643 deletions

View File

@ -22,7 +22,6 @@ import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.internal.MathUtil; import io.netty.util.internal.MathUtil;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; 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.PlatformDependent;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.SystemPropertyUtil;
@ -1173,12 +1172,7 @@ public final class ByteBufUtil {
static final class ThreadLocalUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf { static final class ThreadLocalUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf {
private static final ObjectPool<ThreadLocalUnsafeDirectByteBuf> RECYCLER = private static final ObjectPool<ThreadLocalUnsafeDirectByteBuf> RECYCLER =
ObjectPool.newPool(new ObjectCreator<ThreadLocalUnsafeDirectByteBuf>() { ObjectPool.newPool(ThreadLocalUnsafeDirectByteBuf::new);
@Override
public ThreadLocalUnsafeDirectByteBuf newObject(Handle<ThreadLocalUnsafeDirectByteBuf> handle) {
return new ThreadLocalUnsafeDirectByteBuf(handle);
}
});
static ThreadLocalUnsafeDirectByteBuf newInstance() { static ThreadLocalUnsafeDirectByteBuf newInstance() {
ThreadLocalUnsafeDirectByteBuf buf = RECYCLER.get(); ThreadLocalUnsafeDirectByteBuf buf = RECYCLER.get();
@ -1207,12 +1201,7 @@ public final class ByteBufUtil {
static final class ThreadLocalDirectByteBuf extends UnpooledDirectByteBuf { static final class ThreadLocalDirectByteBuf extends UnpooledDirectByteBuf {
private static final ObjectPool<ThreadLocalDirectByteBuf> RECYCLER = ObjectPool.newPool( private static final ObjectPool<ThreadLocalDirectByteBuf> RECYCLER = ObjectPool.newPool(
new ObjectCreator<ThreadLocalDirectByteBuf>() { ThreadLocalDirectByteBuf::new);
@Override
public ThreadLocalDirectByteBuf newObject(Handle<ThreadLocalDirectByteBuf> handle) {
return new ThreadLocalDirectByteBuf(handle);
}
});
static ThreadLocalDirectByteBuf newInstance() { static ThreadLocalDirectByteBuf newInstance() {
ThreadLocalDirectByteBuf buf = RECYCLER.get(); ThreadLocalDirectByteBuf buf = RECYCLER.get();

View File

@ -23,7 +23,6 @@ import io.netty.buffer.PoolArena.SizeClass;
import io.netty.util.internal.MathUtil; import io.netty.util.internal.MathUtil;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; 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.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.InternalLoggerFactory;
@ -493,12 +492,6 @@ final class PoolThreadCache {
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static final ObjectPool<Entry> RECYCLER = ObjectPool.newPool(new ObjectCreator<Entry>() { private static final ObjectPool<Entry> RECYCLER = ObjectPool.newPool(handle -> new Entry(handle));
@SuppressWarnings("unchecked")
@Override
public Entry newObject(Handle<Entry> handle) {
return new Entry(handle);
}
});
} }
} }

View File

@ -18,7 +18,6 @@ package io.netty.buffer;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; import io.netty.util.internal.ObjectPool.Handle;
import io.netty.util.internal.ObjectPool.ObjectCreator;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -28,12 +27,7 @@ import java.nio.ByteBuffer;
final class PooledDirectByteBuf extends PooledByteBuf<ByteBuffer> { final class PooledDirectByteBuf extends PooledByteBuf<ByteBuffer> {
private static final ObjectPool<PooledDirectByteBuf> RECYCLER = ObjectPool.newPool( private static final ObjectPool<PooledDirectByteBuf> RECYCLER = ObjectPool.newPool(
new ObjectCreator<PooledDirectByteBuf>() { handle -> new PooledDirectByteBuf(handle, 0));
@Override
public PooledDirectByteBuf newObject(Handle<PooledDirectByteBuf> handle) {
return new PooledDirectByteBuf(handle, 0);
}
});
static PooledDirectByteBuf newInstance(int maxCapacity) { static PooledDirectByteBuf newInstance(int maxCapacity) {
PooledDirectByteBuf buf = RECYCLER.get(); PooledDirectByteBuf buf = RECYCLER.get();

View File

@ -19,7 +19,6 @@ package io.netty.buffer;
import io.netty.util.ByteProcessor; import io.netty.util.ByteProcessor;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; import io.netty.util.internal.ObjectPool.Handle;
import io.netty.util.internal.ObjectPool.ObjectCreator;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -31,13 +30,8 @@ import java.nio.channels.ScatteringByteChannel;
final class PooledDuplicatedByteBuf extends AbstractPooledDerivedByteBuf { final class PooledDuplicatedByteBuf extends AbstractPooledDerivedByteBuf {
private static final ObjectPool<PooledDuplicatedByteBuf> RECYCLER = ObjectPool.newPool( private static final ObjectPool<PooledDuplicatedByteBuf> RECYCLER =
new ObjectCreator<PooledDuplicatedByteBuf>() { ObjectPool.newPool(PooledDuplicatedByteBuf::new);
@Override
public PooledDuplicatedByteBuf newObject(Handle<PooledDuplicatedByteBuf> handle) {
return new PooledDuplicatedByteBuf(handle);
}
});
static PooledDuplicatedByteBuf newInstance(AbstractByteBuf unwrapped, ByteBuf wrapped, static PooledDuplicatedByteBuf newInstance(AbstractByteBuf unwrapped, ByteBuf wrapped,
int readerIndex, int writerIndex) { int readerIndex, int writerIndex) {

View File

@ -27,12 +27,7 @@ import java.nio.ByteBuffer;
class PooledHeapByteBuf extends PooledByteBuf<byte[]> { class PooledHeapByteBuf extends PooledByteBuf<byte[]> {
private static final ObjectPool<PooledHeapByteBuf> RECYCLER = ObjectPool.newPool( private static final ObjectPool<PooledHeapByteBuf> RECYCLER = ObjectPool.newPool(
new ObjectCreator<PooledHeapByteBuf>() { handle -> new PooledHeapByteBuf(handle, 0));
@Override
public PooledHeapByteBuf newObject(Handle<PooledHeapByteBuf> handle) {
return new PooledHeapByteBuf(handle, 0);
}
});
static PooledHeapByteBuf newInstance(int maxCapacity) { static PooledHeapByteBuf newInstance(int maxCapacity) {
PooledHeapByteBuf buf = RECYCLER.get(); PooledHeapByteBuf buf = RECYCLER.get();

View File

@ -19,7 +19,6 @@ package io.netty.buffer;
import io.netty.util.ByteProcessor; import io.netty.util.ByteProcessor;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; import io.netty.util.internal.ObjectPool.Handle;
import io.netty.util.internal.ObjectPool.ObjectCreator;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -33,13 +32,7 @@ import static io.netty.buffer.AbstractUnpooledSlicedByteBuf.checkSliceOutOfBound
final class PooledSlicedByteBuf extends AbstractPooledDerivedByteBuf { final class PooledSlicedByteBuf extends AbstractPooledDerivedByteBuf {
private static final ObjectPool<PooledSlicedByteBuf> RECYCLER = ObjectPool.newPool( private static final ObjectPool<PooledSlicedByteBuf> RECYCLER = ObjectPool.newPool(PooledSlicedByteBuf::new);
new ObjectCreator<PooledSlicedByteBuf>() {
@Override
public PooledSlicedByteBuf newObject(Handle<PooledSlicedByteBuf> handle) {
return new PooledSlicedByteBuf(handle);
}
});
static PooledSlicedByteBuf newInstance(AbstractByteBuf unwrapped, ByteBuf wrapped, static PooledSlicedByteBuf newInstance(AbstractByteBuf unwrapped, ByteBuf wrapped,
int index, int length) { int index, int length) {

View File

@ -28,12 +28,7 @@ import java.nio.ByteBuffer;
final class PooledUnsafeDirectByteBuf extends PooledByteBuf<ByteBuffer> { final class PooledUnsafeDirectByteBuf extends PooledByteBuf<ByteBuffer> {
private static final ObjectPool<PooledUnsafeDirectByteBuf> RECYCLER = ObjectPool.newPool( private static final ObjectPool<PooledUnsafeDirectByteBuf> RECYCLER = ObjectPool.newPool(
new ObjectCreator<PooledUnsafeDirectByteBuf>() { handle -> new PooledUnsafeDirectByteBuf(handle, 0));
@Override
public PooledUnsafeDirectByteBuf newObject(Handle<PooledUnsafeDirectByteBuf> handle) {
return new PooledUnsafeDirectByteBuf(handle, 0);
}
});
static PooledUnsafeDirectByteBuf newInstance(int maxCapacity) { static PooledUnsafeDirectByteBuf newInstance(int maxCapacity) {
PooledUnsafeDirectByteBuf buf = RECYCLER.get(); PooledUnsafeDirectByteBuf buf = RECYCLER.get();

View File

@ -17,18 +17,12 @@ package io.netty.buffer;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; 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.PlatformDependent;
final class PooledUnsafeHeapByteBuf extends PooledHeapByteBuf { final class PooledUnsafeHeapByteBuf extends PooledHeapByteBuf {
private static final ObjectPool<PooledUnsafeHeapByteBuf> RECYCLER = ObjectPool.newPool( private static final ObjectPool<PooledUnsafeHeapByteBuf> RECYCLER = ObjectPool.newPool(
new ObjectCreator<PooledUnsafeHeapByteBuf>() { handle -> new PooledUnsafeHeapByteBuf(handle, 0));
@Override
public PooledUnsafeHeapByteBuf newObject(Handle<PooledUnsafeHeapByteBuf> handle) {
return new PooledUnsafeHeapByteBuf(handle, 0);
}
});
static PooledUnsafeHeapByteBuf newUnsafeInstance(int maxCapacity) { static PooledUnsafeHeapByteBuf newUnsafeInstance(int maxCapacity) {
PooledUnsafeHeapByteBuf buf = RECYCLER.get(); PooledUnsafeHeapByteBuf buf = RECYCLER.get();

View File

@ -585,34 +585,19 @@ public class ByteBufUtilTest {
@Test @Test
public void testWriteUtf8InvalidSubsequences() { public void testWriteUtf8InvalidSubsequences() {
testInvalidSubsequences(new TestMethod() { testInvalidSubsequences(args -> ByteBufUtil.writeUtf8((ByteBuf) args[0], (String) args[1],
@Override (Integer) args[2], (Integer) args[3]));
public int invoke(Object... args) {
return ByteBufUtil.writeUtf8((ByteBuf) args[0], (String) args[1],
(Integer) args[2], (Integer) args[3]);
}
});
} }
@Test @Test
public void testReserveAndWriteUtf8InvalidSubsequences() { public void testReserveAndWriteUtf8InvalidSubsequences() {
testInvalidSubsequences(new TestMethod() { testInvalidSubsequences(args -> ByteBufUtil.reserveAndWriteUtf8((ByteBuf) args[0], (String) args[1],
@Override (Integer) args[2], (Integer) args[3], 32));
public int invoke(Object... args) {
return ByteBufUtil.reserveAndWriteUtf8((ByteBuf) args[0], (String) args[1],
(Integer) args[2], (Integer) args[3], 32);
}
});
} }
@Test @Test
public void testUtf8BytesInvalidSubsequences() { public void testUtf8BytesInvalidSubsequences() {
testInvalidSubsequences(new TestMethod() { testInvalidSubsequences(args -> ByteBufUtil.utf8Bytes((String) args[1], (Integer) args[2], (Integer) args[3]));
@Override
public int invoke(Object... args) {
return ByteBufUtil.utf8Bytes((String) args[1], (Integer) args[2], (Integer) args[3]);
}
});
} }
@Test @Test

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.ByteProcessor;
import io.netty.util.ResourceLeakTracker; import io.netty.util.ResourceLeakTracker;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.After; import org.junit.After;
@ -146,12 +145,7 @@ public class SimpleLeakAwareCompositeByteBufTest extends WrappedCompositeByteBuf
comp.addComponent(true, inner); comp.addComponent(true, inner);
buf.addComponent(true, comp); buf.addComponent(true, comp);
assertEquals(-1, buf.forEachByte(new ByteProcessor() { assertEquals(-1, buf.forEachByte(value -> true));
@Override
public boolean process(byte value) {
return true;
}
}));
assertTrue(buf.release()); assertTrue(buf.release());
} }

View File

@ -97,28 +97,20 @@ class WebSocketClientProtocolHandshakeHandler implements ChannelHandler {
return; return;
} }
final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() { final Future<?> timeoutFuture = ctx.executor().schedule(() -> {
@Override if (localHandshakePromise.isDone()) {
public void run() { return;
if (localHandshakePromise.isDone()) { }
return;
}
if (localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) { if (localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) {
ctx.flush() ctx.flush()
.fireUserEventTriggered(ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT) .fireUserEventTriggered(ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT)
.close(); .close();
}
} }
}, handshakeTimeoutMillis, TimeUnit.MILLISECONDS); }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
// Cancel the handshake timeout when handshake is finished. // Cancel the handshake timeout when handshake is finished.
localHandshakePromise.addListener(new FutureListener<Void>() { localHandshakePromise.addListener((FutureListener<Void>) f -> timeoutFuture.cancel(false));
@Override
public void operationComplete(Future<Void> f) throws Exception {
timeoutFuture.cancel(false);
}
});
} }
/** /**

View File

@ -51,12 +51,7 @@ final class WebSocketCloseFrameHandler implements ChannelHandler {
} }
flush(ctx); flush(ctx);
applyCloseSentTimeout(ctx); applyCloseSentTimeout(ctx);
closeSent.addListener(new ChannelFutureListener() { closeSent.addListener((ChannelFutureListener) future -> ctx.close(promise));
@Override
public void operationComplete(ChannelFuture future) {
ctx.close(promise);
}
});
} }
@Override @Override
@ -78,20 +73,12 @@ final class WebSocketCloseFrameHandler implements ChannelHandler {
return; return;
} }
final ScheduledFuture<?> timeoutTask = ctx.executor().schedule(new Runnable() { final ScheduledFuture<?> timeoutTask = ctx.executor().schedule(() -> {
@Override if (!closeSent.isDone()) {
public void run() { closeSent.tryFailure(new WebSocketHandshakeException("send close frame timed out"));
if (!closeSent.isDone()) {
closeSent.tryFailure(new WebSocketHandshakeException("send close frame timed out"));
}
} }
}, forceCloseTimeoutMillis, TimeUnit.MILLISECONDS); }, forceCloseTimeoutMillis, TimeUnit.MILLISECONDS);
closeSent.addListener(new ChannelFutureListener() { closeSent.addListener((ChannelFutureListener) future -> timeoutTask.cancel(false));
@Override
public void operationComplete(ChannelFuture future) {
timeoutTask.cancel(false);
}
});
} }
} }

View File

@ -139,24 +139,16 @@ class WebSocketServerProtocolHandshakeHandler implements ChannelHandler {
return; return;
} }
final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() { final Future<?> timeoutFuture = ctx.executor().schedule(() -> {
@Override if (!localHandshakePromise.isDone() &&
public void run() { localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) {
if (!localHandshakePromise.isDone() && ctx.flush()
localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) { .fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT)
ctx.flush() .close();
.fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT)
.close();
}
} }
}, handshakeTimeoutMillis, TimeUnit.MILLISECONDS); }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
// Cancel the handshake timeout when handshake is finished. // Cancel the handshake timeout when handshake is finished.
localHandshakePromise.addListener(new FutureListener<Void>() { localHandshakePromise.addListener((FutureListener<Void>) f -> timeoutFuture.cancel(false));
@Override
public void operationComplete(Future<Void> f) {
timeoutFuture.cancel(false);
}
});
} }
} }

View File

@ -27,23 +27,13 @@ public interface WebSocketExtensionFilter {
* A {@link WebSocketExtensionFilter} that never skip the evaluation of an * A {@link WebSocketExtensionFilter} that never skip the evaluation of an
* any given extensions {@link WebSocketExtension}. * any given extensions {@link WebSocketExtension}.
*/ */
WebSocketExtensionFilter NEVER_SKIP = new WebSocketExtensionFilter() { WebSocketExtensionFilter NEVER_SKIP = frame -> false;
@Override
public boolean mustSkip(WebSocketFrame frame) {
return false;
}
};
/** /**
* A {@link WebSocketExtensionFilter} that always skip the evaluation of an * A {@link WebSocketExtensionFilter} that always skip the evaluation of an
* any given extensions {@link WebSocketExtension}. * any given extensions {@link WebSocketExtension}.
*/ */
WebSocketExtensionFilter ALWAYS_SKIP = new WebSocketExtensionFilter() { WebSocketExtensionFilter ALWAYS_SKIP = frame -> true;
@Override
public boolean mustSkip(WebSocketFrame frame) {
return true;
}
};
/** /**
* Returns {@code true} if the evaluation of the extension must skipped * Returns {@code true} if the evaluation of the extension must skipped

View File

@ -204,12 +204,7 @@ public class WebSocketHandshakeHandOverTest {
@Override @Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) { if (evt == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
ctx.channel().closeFuture().addListener(new ChannelFutureListener() { ctx.channel().closeFuture().addListener((ChannelFutureListener) future -> clientForceClosed = true);
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientForceClosed = true;
}
});
handshaker.close(ctx.channel(), new CloseWebSocketFrame()); handshaker.close(ctx.channel(), new CloseWebSocketFrame());
} }
} }

View File

@ -221,12 +221,8 @@ public class PerMessageDeflateDecoderTest {
@Test @Test
public void testSelectivityDecompressionSkip() { public void testSelectivityDecompressionSkip() {
WebSocketExtensionFilter selectivityDecompressionFilter = new WebSocketExtensionFilter() { WebSocketExtensionFilter selectivityDecompressionFilter =
@Override frame -> frame instanceof TextWebSocketFrame && frame.content().readableBytes() < 100;
public boolean mustSkip(WebSocketFrame frame) {
return frame instanceof TextWebSocketFrame && frame.content().readableBytes() < 100;
}
};
EmbeddedChannel encoderChannel = new EmbeddedChannel( EmbeddedChannel encoderChannel = new EmbeddedChannel(
ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8));
EmbeddedChannel decoderChannel = new EmbeddedChannel( EmbeddedChannel decoderChannel = new EmbeddedChannel(
@ -266,12 +262,7 @@ public class PerMessageDeflateDecoderTest {
@Test(expected = DecoderException.class) @Test(expected = DecoderException.class)
public void testIllegalStateWhenDecompressionInProgress() { public void testIllegalStateWhenDecompressionInProgress() {
WebSocketExtensionFilter selectivityDecompressionFilter = new WebSocketExtensionFilter() { WebSocketExtensionFilter selectivityDecompressionFilter = frame -> frame.content().readableBytes() < 100;
@Override
public boolean mustSkip(WebSocketFrame frame) {
return frame.content().readableBytes() < 100;
}
};
EmbeddedChannel encoderChannel = new EmbeddedChannel( EmbeddedChannel encoderChannel = new EmbeddedChannel(
ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8));

View File

@ -190,13 +190,9 @@ public class PerMessageDeflateEncoderTest {
@Test @Test
public void testSelectivityCompressionSkip() { public void testSelectivityCompressionSkip() {
WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() { WebSocketExtensionFilter selectivityCompressionFilter =
@Override frame -> (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame)
public boolean mustSkip(WebSocketFrame frame) { && frame.content().readableBytes() < 100;
return (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame)
&& frame.content().readableBytes() < 100;
}
};
EmbeddedChannel encoderChannel = new EmbeddedChannel( EmbeddedChannel encoderChannel = new EmbeddedChannel(
new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter)); new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter));
EmbeddedChannel decoderChannel = new EmbeddedChannel( EmbeddedChannel decoderChannel = new EmbeddedChannel(
@ -238,12 +234,7 @@ public class PerMessageDeflateEncoderTest {
@Test(expected = EncoderException.class) @Test(expected = EncoderException.class)
public void testIllegalStateWhenCompressionInProgress() { public void testIllegalStateWhenCompressionInProgress() {
WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() { WebSocketExtensionFilter selectivityCompressionFilter = frame -> frame.content().readableBytes() < 100;
@Override
public boolean mustSkip(WebSocketFrame frame) {
return frame.content().readableBytes() < 100;
}
};
EmbeddedChannel encoderChannel = new EmbeddedChannel( EmbeddedChannel encoderChannel = new EmbeddedChannel(
new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter)); new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter));

View File

@ -114,12 +114,8 @@ abstract class AbstractHttp2StreamChannel extends DefaultAttributeMap implements
} }
} }
private final ChannelFutureListener windowUpdateFrameWriteListener = new ChannelFutureListener() { private final ChannelFutureListener windowUpdateFrameWriteListener = future ->
@Override
public void operationComplete(ChannelFuture future) {
windowUpdateFrameWriteComplete(future, AbstractHttp2StreamChannel.this); windowUpdateFrameWriteComplete(future, AbstractHttp2StreamChannel.this);
}
};
/** /**
* The current status of the read-processing for a {@link AbstractHttp2StreamChannel}. * The current status of the read-processing for a {@link AbstractHttp2StreamChannel}.

View File

@ -497,14 +497,11 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http
closeListener = listener; closeListener = listener;
} else if (promise != null) { } else if (promise != null) {
final ChannelFutureListener oldCloseListener = closeListener; final ChannelFutureListener oldCloseListener = closeListener;
closeListener = new ChannelFutureListener() { closeListener = future1 -> {
@Override try {
public void operationComplete(ChannelFuture future) throws Exception { oldCloseListener.operationComplete(future1);
try { } finally {
oldCloseListener.operationComplete(future); listener.operationComplete(future1);
} finally {
listener.operationComplete(future);
}
} }
}; };
} }

View File

@ -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 // 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 // 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. // handlerAdded(...) which will be run before other handlers will be added to the pipeline.
ctx.executor().execute(new Runnable() { ctx.executor().execute(() -> ctx.fireUserEventTriggered(evt));
@Override
public void run() {
ctx.fireUserEventTriggered(evt);
}
});
} else if (evt instanceof UpgradeEvent) { } else if (evt instanceof UpgradeEvent) {
UpgradeEvent upgrade = (UpgradeEvent) evt; UpgradeEvent upgrade = (UpgradeEvent) evt;
try { try {

View File

@ -27,7 +27,6 @@ import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.eq; import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset; import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -43,7 +42,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
/** /**
@ -81,12 +79,7 @@ public class DefaultHttp2LocalFlowControllerTest {
reset(ctx); reset(ctx);
when(ctx.newPromise()).thenReturn(promise); when(ctx.newPromise()).thenReturn(promise);
if (allowFlush) { if (allowFlush) {
when(ctx.flush()).then(new Answer<ChannelHandlerContext>() { when(ctx.flush()).then((Answer<ChannelHandlerContext>) invocationOnMock -> ctx);
@Override
public ChannelHandlerContext answer(InvocationOnMock invocationOnMock) {
return ctx;
}
});
} else { } else {
when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden")); when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden"));
} }

View File

@ -41,7 +41,6 @@ import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@ -743,38 +742,23 @@ public class Http2ConnectionHandlerTest {
when(stream.id()).thenReturn(STREAM_ID); when(stream.id()).thenReturn(STREAM_ID);
final AtomicBoolean resetSent = new AtomicBoolean(); final AtomicBoolean resetSent = new AtomicBoolean();
when(stream.resetSent()).then(new Answer<Http2Stream>() { when(stream.resetSent()).then((Answer<Http2Stream>) invocationOnMock -> {
@Override resetSent.set(true);
public Http2Stream answer(InvocationOnMock invocationOnMock) { return stream;
resetSent.set(true);
return stream;
}
});
when(stream.isResetSent()).then(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocationOnMock) {
return resetSent.get();
}
}); });
when(stream.isResetSent()).then((Answer<Boolean>) invocationOnMock -> resetSent.get());
when(frameWriter.writeRstStream(eq(ctx), eq(STREAM_ID), anyLong(), any(ChannelPromise.class))) when(frameWriter.writeRstStream(eq(ctx), eq(STREAM_ID), anyLong(), any(ChannelPromise.class)))
.then(new Answer<ChannelFuture>() { .then((Answer<ChannelFuture>) invocationOnMock -> {
@Override ChannelPromise promise = invocationOnMock.getArgument(3);
public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable { return promise.setSuccess();
ChannelPromise promise = invocationOnMock.getArgument(3);
return promise.setSuccess();
}
}); });
ChannelPromise promise = ChannelPromise promise =
new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
final ChannelPromise promise2 = final ChannelPromise promise2 =
new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
promise.addListener(new ChannelFutureListener() { promise.addListener((ChannelFutureListener) future ->
@Override handler.resetStream(ctx, STREAM_ID, STREAM_CLOSED.code(), promise2));
public void operationComplete(ChannelFuture future) {
handler.resetStream(ctx, STREAM_ID, STREAM_CLOSED.code(), promise2);
}
});
handler.resetStream(ctx, STREAM_ID, CANCEL.code(), promise); handler.resetStream(ctx, STREAM_ID, CANCEL.code(), promise);
verify(frameWriter).writeRstStream(eq(ctx), eq(STREAM_ID), anyLong(), any(ChannelPromise.class)); verify(frameWriter).writeRstStream(eq(ctx), eq(STREAM_ID), anyLong(), any(ChannelPromise.class));

View File

@ -25,7 +25,6 @@ import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise; import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.DefaultMessageSizeEstimator; import io.netty.channel.DefaultMessageSizeEstimator;
import io.netty.handler.codec.http2.Http2Exception.ShutdownHint;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.ImmediateEventExecutor; import io.netty.util.concurrent.ImmediateEventExecutor;
@ -92,40 +91,24 @@ public class Http2ControlFrameLimitEncoderTest {
when(frameSizePolicy.maxFrameSize()).thenReturn(DEFAULT_MAX_FRAME_SIZE); when(frameSizePolicy.maxFrameSize()).thenReturn(DEFAULT_MAX_FRAME_SIZE);
when(writer.writeRstStream(eq(ctx), anyInt(), anyLong(), any(ChannelPromise.class))) when(writer.writeRstStream(eq(ctx), anyInt(), anyLong(), any(ChannelPromise.class)))
.thenAnswer(new Answer<ChannelFuture>() { .thenAnswer((Answer<ChannelFuture>) invocationOnMock -> handlePromise(invocationOnMock, 3));
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return handlePromise(invocationOnMock, 3);
}
});
when(writer.writeSettingsAck(any(ChannelHandlerContext.class), any(ChannelPromise.class))) when(writer.writeSettingsAck(any(ChannelHandlerContext.class), any(ChannelPromise.class)))
.thenAnswer(new Answer<ChannelFuture>() { .thenAnswer((Answer<ChannelFuture>) invocationOnMock -> handlePromise(invocationOnMock, 1));
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return handlePromise(invocationOnMock, 1);
}
});
when(writer.writePing(any(ChannelHandlerContext.class), anyBoolean(), anyLong(), any(ChannelPromise.class))) when(writer.writePing(any(ChannelHandlerContext.class), anyBoolean(), anyLong(), any(ChannelPromise.class)))
.thenAnswer(new Answer<ChannelFuture>() { .thenAnswer((Answer<ChannelFuture>) invocationOnMock -> {
@Override ChannelPromise promise = handlePromise(invocationOnMock, 3);
public ChannelFuture answer(InvocationOnMock invocationOnMock) { if (invocationOnMock.getArgument(1) == Boolean.FALSE) {
ChannelPromise promise = handlePromise(invocationOnMock, 3); promise.trySuccess();
if (invocationOnMock.getArgument(1) == Boolean.FALSE) {
promise.trySuccess();
}
return promise;
} }
return promise;
}); });
when(writer.writeGoAway(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), when(writer.writeGoAway(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() { any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock -> {
@Override ReferenceCountUtil.release(invocationOnMock.getArgument(3));
public ChannelFuture answer(InvocationOnMock invocationOnMock) { ChannelPromise promise = invocationOnMock.getArgument(4);
ReferenceCountUtil.release(invocationOnMock.getArgument(3)); goAwayPromises.offer(promise);
ChannelPromise promise = invocationOnMock.getArgument(4); return promise;
goAwayPromises.offer(promise); });
return promise;
}
});
Http2Connection connection = new DefaultHttp2Connection(false); Http2Connection connection = new DefaultHttp2Connection(false);
connection.remote().flowController(new DefaultHttp2RemoteFlowController(connection)); connection.remote().flowController(new DefaultHttp2RemoteFlowController(connection));
connection.local().flowController(new DefaultHttp2LocalFlowController(connection).frameWriter(writer)); connection.local().flowController(new DefaultHttp2LocalFlowController(connection).frameWriter(writer));
@ -144,12 +127,7 @@ public class Http2ControlFrameLimitEncoderTest {
when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(executor.inEventLoop()).thenReturn(true); when(executor.inEventLoop()).thenReturn(true);
doAnswer(new Answer<ChannelPromise>() { doAnswer((Answer<ChannelPromise>) invocation -> newPromise()).when(ctx).newPromise();
@Override
public ChannelPromise answer(InvocationOnMock invocation) throws Throwable {
return newPromise();
}
}).when(ctx).newPromise();
when(ctx.executor()).thenReturn(executor); when(ctx.executor()).thenReturn(executor);
when(channel.isActive()).thenReturn(false); when(channel.isActive()).thenReturn(false);
when(channel.config()).thenReturn(config); when(channel.config()).thenReturn(config);

View File

@ -17,7 +17,6 @@ package io.netty.handler.codec.http2;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@ -33,12 +32,8 @@ public class Http2EmptyDataFrameConnectionDecoderTest {
Http2ConnectionDecoder delegate = mock(Http2ConnectionDecoder.class); Http2ConnectionDecoder delegate = mock(Http2ConnectionDecoder.class);
final ArgumentCaptor<Http2FrameListener> listenerArgumentCaptor = final ArgumentCaptor<Http2FrameListener> listenerArgumentCaptor =
ArgumentCaptor.forClass(Http2FrameListener.class); ArgumentCaptor.forClass(Http2FrameListener.class);
when(delegate.frameListener()).then(new Answer<Http2FrameListener>() { when(delegate.frameListener()).then(
@Override (Answer<Http2FrameListener>) invocationOnMock -> listenerArgumentCaptor.getValue());
public Http2FrameListener answer(InvocationOnMock invocationOnMock) {
return listenerArgumentCaptor.getValue();
}
});
Http2FrameListener listener = mock(Http2FrameListener.class); Http2FrameListener listener = mock(Http2FrameListener.class);
Http2EmptyDataFrameConnectionDecoder decoder = new Http2EmptyDataFrameConnectionDecoder(delegate, 2); Http2EmptyDataFrameConnectionDecoder decoder = new Http2EmptyDataFrameConnectionDecoder(delegate, 2);
decoder.frameListener(listener); decoder.frameListener(listener);

View File

@ -20,8 +20,6 @@ import io.netty.util.concurrent.FastThreadLocalThread;
import reactor.blockhound.BlockHound; import reactor.blockhound.BlockHound;
import reactor.blockhound.integration.BlockHoundIntegration; 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. * Contains classes that must be have public visibility but are not public API.
@ -64,18 +62,8 @@ class Hidden {
"confirmShutdown" "confirmShutdown"
); );
builder.nonBlockingThreadPredicate(new Function<Predicate<Thread>, Predicate<Thread>>() { builder.nonBlockingThreadPredicate(p -> thread ->
@Override p.test(thread) || thread instanceof FastThreadLocalThread);
public Predicate<Thread> apply(final Predicate<Thread> p) {
return new Predicate<Thread>() {
@Override
@SuppressJava6Requirement(reason = "Predicate#test")
public boolean test(Thread thread) {
return p.test(thread) || thread instanceof FastThreadLocalThread;
}
};
}
});
} }
} }
} }

View File

@ -18,18 +18,12 @@ package io.netty.util.internal;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.Promise;
import io.netty.util.internal.ObjectPool.Handle; import io.netty.util.internal.ObjectPool.Handle;
import io.netty.util.internal.ObjectPool.ObjectCreator;
/** /**
* Some pending write which should be picked up later. * Some pending write which should be picked up later.
*/ */
public final class PendingWrite { public final class PendingWrite {
private static final ObjectPool<PendingWrite> RECYCLER = ObjectPool.newPool(new ObjectCreator<PendingWrite>() { private static final ObjectPool<PendingWrite> RECYCLER = ObjectPool.newPool(PendingWrite::new);
@Override
public PendingWrite newObject(Handle<PendingWrite> handle) {
return new PendingWrite(handle);
}
});
/** /**
* Create a new empty {@link RecyclableArrayList} instance * Create a new empty {@link RecyclableArrayList} instance

View File

@ -19,7 +19,6 @@ package io.netty.util.internal;
import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNull;
import io.netty.util.internal.ObjectPool.Handle; import io.netty.util.internal.ObjectPool.Handle;
import io.netty.util.internal.ObjectPool.ObjectCreator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -35,13 +34,7 @@ public final class RecyclableArrayList extends ArrayList<Object> {
private static final int DEFAULT_INITIAL_CAPACITY = 8; private static final int DEFAULT_INITIAL_CAPACITY = 8;
private static final ObjectPool<RecyclableArrayList> RECYCLER = ObjectPool.newPool( private static final ObjectPool<RecyclableArrayList> RECYCLER = ObjectPool.newPool(RecyclableArrayList::new);
new ObjectCreator<RecyclableArrayList>() {
@Override
public RecyclableArrayList newObject(Handle<RecyclableArrayList> handle) {
return new RecyclableArrayList(handle);
}
});
private boolean insertSinceRecycled; private boolean insertSinceRecycled;

View File

@ -52,12 +52,7 @@ public final class ThreadExecutorMap {
public static Executor apply(final Executor executor, final EventExecutor eventExecutor) { public static Executor apply(final Executor executor, final EventExecutor eventExecutor) {
Objects.requireNonNull(executor, "executor"); Objects.requireNonNull(executor, "executor");
Objects.requireNonNull(eventExecutor, "eventExecutor"); Objects.requireNonNull(eventExecutor, "eventExecutor");
return new Executor() { return command -> executor.execute(apply(command, eventExecutor));
@Override
public void execute(final Runnable command) {
executor.execute(apply(command, eventExecutor));
}
};
} }
/** /**
@ -67,15 +62,12 @@ public final class ThreadExecutorMap {
public static Runnable apply(final Runnable command, final EventExecutor eventExecutor) { public static Runnable apply(final Runnable command, final EventExecutor eventExecutor) {
Objects.requireNonNull(command, "command"); Objects.requireNonNull(command, "command");
Objects.requireNonNull(eventExecutor, "eventExecutor"); Objects.requireNonNull(eventExecutor, "eventExecutor");
return new Runnable() { return () -> {
@Override setCurrentEventExecutor(eventExecutor);
public void run() { try {
setCurrentEventExecutor(eventExecutor); command.run();
try { } finally {
command.run(); setCurrentEventExecutor(null);
} finally {
setCurrentEventExecutor(null);
}
} }
}; };
} }
@ -87,11 +79,6 @@ public final class ThreadExecutorMap {
public static ThreadFactory apply(final ThreadFactory threadFactory, final EventExecutor eventExecutor) { public static ThreadFactory apply(final ThreadFactory threadFactory, final EventExecutor eventExecutor) {
Objects.requireNonNull(threadFactory, "command"); Objects.requireNonNull(threadFactory, "command");
Objects.requireNonNull(eventExecutor, "eventExecutor"); Objects.requireNonNull(eventExecutor, "eventExecutor");
return new ThreadFactory() { return r -> threadFactory.newThread(apply(r, eventExecutor));
@Override
public Thread newThread(Runnable r) {
return threadFactory.newThread(apply(r, eventExecutor));
}
};
} }
} }

View File

@ -193,10 +193,7 @@ public class SingleThreadEventExecutorTest {
} }
}; };
final Runnable dummyTask = new Runnable() { final Runnable dummyTask = () -> {
@Override
public void run() {
}
}; };
final LinkedBlockingQueue<Future<?>> submittedTasks = new LinkedBlockingQueue<Future<?>>(); final LinkedBlockingQueue<Future<?>> submittedTasks = new LinkedBlockingQueue<Future<?>>();

View File

@ -29,34 +29,22 @@ public class ThreadExecutorMapTest {
@Test @Test
public void testDecorateExecutor() { public void testDecorateExecutor() {
Executor executor = ThreadExecutorMap.apply(ImmediateExecutor.INSTANCE, ImmediateEventExecutor.INSTANCE); Executor executor = ThreadExecutorMap.apply(ImmediateExecutor.INSTANCE, ImmediateEventExecutor.INSTANCE);
executor.execute(new Runnable() { executor.execute(() -> Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor()));
@Override
public void run() {
Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor());
}
});
} }
@Test @Test
public void testDecorateRunnable() { public void testDecorateRunnable() {
ThreadExecutorMap.apply(new Runnable() { ThreadExecutorMap.apply(() ->
@Override Assert.assertSame(ImmediateEventExecutor.INSTANCE,
public void run() { ThreadExecutorMap.currentExecutor()), ImmediateEventExecutor.INSTANCE).run();
Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor());
}
}, ImmediateEventExecutor.INSTANCE).run();
} }
@Test @Test
public void testDecorateThreadFactory() throws InterruptedException { public void testDecorateThreadFactory() throws InterruptedException {
ThreadFactory threadFactory = ThreadFactory threadFactory =
ThreadExecutorMap.apply(Executors.defaultThreadFactory(), ImmediateEventExecutor.INSTANCE); ThreadExecutorMap.apply(Executors.defaultThreadFactory(), ImmediateEventExecutor.INSTANCE);
Thread thread = threadFactory.newThread(new Runnable() { Thread thread = threadFactory.newThread(() -> Assert.assertSame(ImmediateEventExecutor.INSTANCE,
@Override ThreadExecutorMap.currentExecutor()));
public void run() {
Assert.assertSame(ImmediateEventExecutor.INSTANCE, ThreadExecutorMap.currentExecutor());
}
});
thread.start(); thread.start();
thread.join(); thread.join();
} }

View File

@ -26,7 +26,6 @@ import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; 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.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; 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 int DEFAULT_NUM_ELEMENTS = 2;
private static final ObjectPool<RecyclableArrayDeque> RECYCLER = ObjectPool.newPool( private static final ObjectPool<RecyclableArrayDeque> RECYCLER = ObjectPool.newPool(
new ObjectCreator<RecyclableArrayDeque>() { handle -> new RecyclableArrayDeque(DEFAULT_NUM_ELEMENTS, handle));
@Override
public RecyclableArrayDeque newObject(Handle<RecyclableArrayDeque> handle) {
return new RecyclableArrayDeque(DEFAULT_NUM_ELEMENTS, handle);
}
});
public static RecyclableArrayDeque newInstance() { public static RecyclableArrayDeque newInstance() {
return RECYCLER.get(); return RECYCLER.get();

View File

@ -1351,19 +1351,16 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
if (task == null) { if (task == null) {
return null; return null;
} }
return new Runnable() { return () -> {
@Override if (isDestroyed()) {
public void run() { // The engine was destroyed in the meantime, just return.
if (isDestroyed()) { return;
// The engine was destroyed in the meantime, just return. }
return; try {
} task.run();
try { } finally {
task.run(); // The task was run, reset needTask to false so getHandshakeStatus() returns the correct value.
} finally { needTask = false;
// The task was run, reset needTask to false so getHandshakeStatus() returns the correct value.
needTask = false;
}
} }
}; };
} }

View File

@ -945,13 +945,10 @@ public class SslHandler extends ByteToMessageDecoder {
SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out); SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out);
if (result.bytesProduced() > 0) { if (result.bytesProduced() > 0) {
ctx.write(out).addListener(new ChannelFutureListener() { ctx.write(out).addListener((ChannelFutureListener) future -> {
@Override Throwable cause = future.cause();
public void operationComplete(ChannelFuture future) { if (cause != null) {
Throwable cause = future.cause(); setHandshakeFailureTransportFailure(ctx, cause);
if (cause != null) {
setHandshakeFailureTransportFailure(ctx, cause);
}
} }
}); });
if (inUnwrap) { if (inUnwrap) {

View File

@ -18,8 +18,6 @@ package io.netty.handler.flush;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.Test; import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -163,12 +161,7 @@ public class FlushConsolidationHandlerTest {
public void testResend() throws Exception { public void testResend() throws Exception {
final AtomicInteger flushCount = new AtomicInteger(); final AtomicInteger flushCount = new AtomicInteger();
final EmbeddedChannel channel = newChannel(flushCount, true); final EmbeddedChannel channel = newChannel(flushCount, true);
channel.writeAndFlush(1L).addListener(new GenericFutureListener<Future<? super Void>>() { channel.writeAndFlush(1L).addListener(future -> channel.writeAndFlush(1L));
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
channel.writeAndFlush(1L);
}
});
channel.flushOutbound(); channel.flushOutbound();
assertEquals(1L, ((Long) channel.readOutbound()).longValue()); assertEquals(1L, ((Long) channel.readOutbound()).longValue());
assertEquals(1L, ((Long) channel.readOutbound()).longValue()); assertEquals(1L, ((Long) channel.readOutbound()).longValue());

View File

@ -62,7 +62,6 @@ import java.util.List;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -100,12 +99,7 @@ public class OpenSslPrivateKeyMethodTest {
GROUP = new MultithreadEventLoopGroup(LocalHandler.newFactory()); GROUP = new MultithreadEventLoopGroup(LocalHandler.newFactory());
CERT = new SelfSignedCertificate(); CERT = new SelfSignedCertificate();
EXECUTOR = Executors.newCachedThreadPool(new ThreadFactory() { EXECUTOR = Executors.newCachedThreadPool(DelegateThread::new);
@Override
public Thread newThread(Runnable r) {
return new DelegateThread(r);
}
});
} }
@AfterClass @AfterClass

View File

@ -123,12 +123,9 @@ public class SslHandlerTest {
try { try {
final CountDownLatch writeCauseLatch = new CountDownLatch(1); final CountDownLatch writeCauseLatch = new CountDownLatch(1);
final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>(); final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>();
ch.write(Unpooled.wrappedBuffer(new byte[]{1})).addListener(new ChannelFutureListener() { ch.write(Unpooled.wrappedBuffer(new byte[]{1})).addListener((ChannelFutureListener) future -> {
@Override failureRef.compareAndSet(null, future.cause());
public void operationComplete(ChannelFuture future) { writeCauseLatch.countDown();
failureRef.compareAndSet(null, future.cause());
writeCauseLatch.countDown();
}
}); });
writeLatch.await(); writeLatch.await();

View File

@ -513,12 +513,9 @@ public class ChunkedWriteHandlerTest {
final CountDownLatch listenerInvoked = new CountDownLatch(1); final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input); ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() { writeFuture.addListener((ChannelFutureListener) future -> {
@Override inputClosedWhenListenerInvoked.set(input.isClosed());
public void operationComplete(ChannelFuture future) { listenerInvoked.countDown();
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
}); });
ch.flush(); ch.flush();
@ -537,12 +534,9 @@ public class ChunkedWriteHandlerTest {
final CountDownLatch listenerInvoked = new CountDownLatch(1); final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input); ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() { writeFuture.addListener((ChannelFutureListener) future -> {
@Override inputClosedWhenListenerInvoked.set(input.isClosed());
public void operationComplete(ChannelFuture future) { listenerInvoked.countDown();
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
}); });
ch.flush(); ch.flush();
@ -562,12 +556,9 @@ public class ChunkedWriteHandlerTest {
final CountDownLatch listenerInvoked = new CountDownLatch(1); final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input); ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() { writeFuture.addListener((ChannelFutureListener) future -> {
@Override inputClosedWhenListenerInvoked.set(input.isClosed());
public void operationComplete(ChannelFuture future) { listenerInvoked.countDown();
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
}); });
ch.close(); // close channel to make handler discard the input on subsequent flush ch.close(); // close channel to make handler discard the input on subsequent flush
ch.flush(); ch.flush();
@ -588,12 +579,9 @@ public class ChunkedWriteHandlerTest {
final CountDownLatch listenerInvoked = new CountDownLatch(1); final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input); ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() { writeFuture.addListener((ChannelFutureListener) future -> {
@Override inputClosedWhenListenerInvoked.set(input.isClosed());
public void operationComplete(ChannelFuture future) { listenerInvoked.countDown();
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
}); });
ch.close(); // close channel to make handler discard the input on subsequent flush ch.close(); // close channel to make handler discard the input on subsequent flush
ch.flush(); ch.flush();

View File

@ -37,10 +37,7 @@ import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.TearDown;
public class EpollSocketChannelBenchmark extends AbstractMicrobenchmark { public class EpollSocketChannelBenchmark extends AbstractMicrobenchmark {
private static final Runnable runnable = new Runnable() { private static final Runnable runnable = () -> { };
@Override
public void run() { }
};
private EventLoopGroup group; private EventLoopGroup group;
private Channel serverChan; private Channel serverChan;

View File

@ -1211,81 +1211,78 @@ public class DnsNameResolver extends InetNameResolver {
.group(executor()) .group(executor())
.channelFactory(socketChannelFactory) .channelFactory(socketChannelFactory)
.handler(TCP_ENCODER); .handler(TCP_ENCODER);
bs.connect(res.sender()).addListener(new ChannelFutureListener() { bs.connect(res.sender()).addListener((ChannelFutureListener) future -> {
@Override if (!future.isSuccess()) {
public void operationComplete(ChannelFuture future) { if (logger.isDebugEnabled()) {
if (!future.isSuccess()) { logger.debug("{} Unable to fallback to TCP [{}]", queryId, future.cause());
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;
} }
final Channel channel = future.channel();
Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise = // TCP fallback failed, just use the truncated response.
channel.eventLoop().newPromise(); qCtx.finish(res);
final TcpDnsQueryContext tcpCtx = new TcpDnsQueryContext(DnsNameResolver.this, channel, return;
(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<AddressedEnvelope<DnsResponse, InetSocketAddress>>() {
@Override
public void operationComplete(
Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> 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());
} }
final Channel channel = future.channel();
Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> 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<AddressedEnvelope<DnsResponse, InetSocketAddress>>() {
@Override
public void operationComplete(
Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> 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());
}); });
} }

View File

@ -2467,24 +2467,20 @@ public class DnsNameResolverTest {
final String txt1 = "some text"; final String txt1 = "some text";
final String txt2 = "some more text"; final String txt2 = "some more text";
TestDnsServer server = new TestDnsServer(new RecordStore() { TestDnsServer server = new TestDnsServer(question -> {
if (question.getDomainName().equals(hostname)) {
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt1);
@Override Map<String, Object> map2 = new HashMap<String, Object>();
public Set<ResourceRecord> getRecords(QuestionRecord question) { map2.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt2);
if (question.getDomainName().equals(hostname)) {
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt1);
Map<String, Object> map2 = new HashMap<String, Object>(); Set<ResourceRecord> records = new HashSet<ResourceRecord>();
map2.put(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt2); records.add(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.TXT, map1));
records.add(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.TXT, map2));
Set<ResourceRecord> records = new HashSet<ResourceRecord>(); return records;
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();
} }
return Collections.emptySet();
}); });
server.start(); server.start();
DnsNameResolver resolver = newResolver(ResolvedAddressTypes.IPV4_ONLY) DnsNameResolver resolver = newResolver(ResolvedAddressTypes.IPV4_ONLY)
@ -2536,26 +2532,23 @@ public class DnsNameResolverTest {
public void testNotIncludeDuplicates() throws IOException { public void testNotIncludeDuplicates() throws IOException {
final String name = "netty.io"; final String name = "netty.io";
final String ipv4Addr = "1.2.3.4"; final String ipv4Addr = "1.2.3.4";
TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { TestDnsServer dnsServer2 = new TestDnsServer(question -> {
@Override Set<ResourceRecord> records = new LinkedHashSet<ResourceRecord>(4);
public Set<ResourceRecord> getRecords(QuestionRecord question) { String qName = question.getDomainName().toLowerCase();
Set<ResourceRecord> records = new LinkedHashSet<ResourceRecord>(4); if (qName.equals(name)) {
String qName = question.getDomainName().toLowerCase(); records.add(new TestDnsServer.TestResourceRecord(
if (qName.equals(name)) { qName, RecordType.CNAME,
records.add(new TestDnsServer.TestResourceRecord( Collections.<String, Object>singletonMap(
qName, RecordType.CNAME, DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io")));
Collections.<String, Object>singletonMap( records.add(new TestDnsServer.TestResourceRecord(qName,
DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io"))); RecordType.A, Collections.<String, Object>singletonMap(
records.add(new TestDnsServer.TestResourceRecord(qName, DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr)));
RecordType.A, Collections.<String, Object>singletonMap( } else {
DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); records.add(new TestDnsServer.TestResourceRecord(qName,
} else { RecordType.A, Collections.<String, Object>singletonMap(
records.add(new TestDnsServer.TestResourceRecord(qName, DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr)));
RecordType.A, Collections.<String, Object>singletonMap(
DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr)));
}
return records;
} }
return records;
}); });
dnsServer2.start(); dnsServer2.start();
DnsNameResolver resolver = null; DnsNameResolver resolver = null;
@ -2582,19 +2575,16 @@ public class DnsNameResolverTest {
public void testIncludeDuplicates() throws IOException { public void testIncludeDuplicates() throws IOException {
final String name = "netty.io"; final String name = "netty.io";
final String ipv4Addr = "1.2.3.4"; final String ipv4Addr = "1.2.3.4";
TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { TestDnsServer dnsServer2 = new TestDnsServer(question -> {
@Override Set<ResourceRecord> records = new LinkedHashSet<ResourceRecord>(2);
public Set<ResourceRecord> getRecords(QuestionRecord question) { String qName = question.getDomainName().toLowerCase();
Set<ResourceRecord> records = new LinkedHashSet<ResourceRecord>(2); records.add(new TestDnsServer.TestResourceRecord(qName,
String qName = question.getDomainName().toLowerCase(); RecordType.A, Collections.<String, Object>singletonMap(
records.add(new TestDnsServer.TestResourceRecord(qName, DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr)));
RecordType.A, Collections.<String, Object>singletonMap( records.add(new TestDnsServer.TestResourceRecord(qName,
DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr))); RecordType.A, Collections.<String, Object>singletonMap(
records.add(new TestDnsServer.TestResourceRecord(qName, DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr)));
RecordType.A, Collections.<String, Object>singletonMap( return records;
DnsAttribute.IP_ADDRESS.toLowerCase(), ipv4Addr)));
return records;
}
}); });
dnsServer2.start(); dnsServer2.start();
DnsNameResolver resolver = null; DnsNameResolver resolver = null;
@ -2674,22 +2664,19 @@ public class DnsNameResolverTest {
@Test(timeout = 2000) @Test(timeout = 2000)
public void testDropAAAAResolveAllFast() throws IOException { public void testDropAAAAResolveAllFast() throws IOException {
final String host = "somehost.netty.io"; final String host = "somehost.netty.io";
TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { TestDnsServer dnsServer2 = new TestDnsServer(question -> {
@Override String name = question.getDomainName();
public Set<ResourceRecord> getRecords(QuestionRecord question) throws DnsException { if (name.equals(host)) {
String name = question.getDomainName(); Set<ResourceRecord> records = new HashSet<ResourceRecord>(2);
if (name.equals(host)) { records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A,
Set<ResourceRecord> records = new HashSet<ResourceRecord>(2); Collections.<String, Object>singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(),
records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, "10.0.0.1")));
Collections.<String, Object>singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A,
"10.0.0.1"))); Collections.<String, Object>singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(),
records.add(new TestDnsServer.TestResourceRecord(name, RecordType.A, "10.0.0.2")));
Collections.<String, Object>singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), return records;
"10.0.0.2")));
return records;
}
return null;
} }
return null;
}); });
dnsServer2.start(true); dnsServer2.start(true);
DnsNameResolver resolver = null; DnsNameResolver resolver = null;
@ -2756,18 +2743,15 @@ public class DnsNameResolverTest {
final String txt = "this is a txt record"; final String txt = "this is a txt record";
final AtomicReference<DnsMessage> messageRef = new AtomicReference<DnsMessage>(); final AtomicReference<DnsMessage> messageRef = new AtomicReference<DnsMessage>();
TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { TestDnsServer dnsServer2 = new TestDnsServer(question -> {
@Override String name = question.getDomainName();
public Set<ResourceRecord> getRecords(QuestionRecord question) { if (name.equals(host)) {
String name = question.getDomainName(); return Collections.<ResourceRecord>singleton(
if (name.equals(host)) { new TestDnsServer.TestResourceRecord(name, RecordType.TXT,
return Collections.<ResourceRecord>singleton( Collections.<String, Object>singletonMap(
new TestDnsServer.TestResourceRecord(name, RecordType.TXT, DnsAttribute.CHARACTER_STRING.toLowerCase(), txt)));
Collections.<String, Object>singletonMap(
DnsAttribute.CHARACTER_STRING.toLowerCase(), txt)));
}
return null;
} }
return null;
}) { }) {
@Override @Override
protected DnsMessage filterMessage(DnsMessage message) { protected DnsMessage filterMessage(DnsMessage message) {

View File

@ -24,7 +24,6 @@ import static org.ops4j.pax.exam.CoreOptions.url;
import static org.osgi.framework.Constants.FRAMEWORK_BOOTDELEGATION; import static org.osgi.framework.Constants.FRAMEWORK_BOOTDELEGATION;
import java.io.File; import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
@ -45,12 +44,8 @@ public class OsgiBundleTest {
final Set<String> links = new HashSet<String>(); final Set<String> links = new HashSet<String>();
final File directory = new File("target/generated-test-resources/alta/"); final File directory = new File("target/generated-test-resources/alta/");
File[] files = directory.listFiles(new FilenameFilter() { File[] files = directory.listFiles((dir, name) ->
@Override (name.startsWith("io.netty") || name.startsWith("com.barchart.udt")) && name.endsWith(".link"));
public boolean accept(File dir, String name) {
return (name.startsWith("io.netty") || name.startsWith("com.barchart.udt")) && name.endsWith(".link");
}
});
if (files == null) { if (files == null) {
throw new IllegalStateException(directory + " is not found or is not a directory"); throw new IllegalStateException(directory + " is not found or is not a directory");
} }

View File

@ -86,12 +86,7 @@ public abstract class AbstractSingleThreadEventLoopTest {
public void gracefulShutdownAfterStart() throws Exception { public void gracefulShutdownAfterStart() throws Exception {
EventLoop loop = new MultithreadEventLoopGroup(newIoHandlerFactory()).next(); EventLoop loop = new MultithreadEventLoopGroup(newIoHandlerFactory()).next();
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
loop.execute(new Runnable() { loop.execute(latch::countDown);
@Override
public void run() {
latch.countDown();
}
});
// Wait for the event loop thread to start. // Wait for the event loop thread to start.
latch.await(); latch.await();
@ -105,10 +100,7 @@ public abstract class AbstractSingleThreadEventLoopTest {
assertRejection(loop); assertRejection(loop);
} }
private static final Runnable NOOP = new Runnable() { private static final Runnable NOOP = () -> { };
@Override
public void run() { }
};
private static void assertRejection(EventExecutor loop) { private static void assertRejection(EventExecutor loop) {
try { try {

View File

@ -20,7 +20,6 @@ import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
@ -87,12 +86,9 @@ public abstract class AbstractSocketReuseFdTest extends AbstractSocketTest {
} }
}); });
ChannelFutureListener listener = new ChannelFutureListener() { ChannelFutureListener listener = future -> {
@Override if (!future.isSuccess()) {
public void operationComplete(ChannelFuture future) { clientDonePromise.tryFailure(future.cause());
if (!future.isSuccess()) {
clientDonePromise.tryFailure(future.cause());
}
} }
}; };

View File

@ -24,7 +24,6 @@ import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.internal.InternalThreadLocalMap; import io.netty.util.internal.InternalThreadLocalMap;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.Handle; 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.PromiseNotificationUtil;
import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLogger;
@ -788,12 +787,7 @@ public final class ChannelOutboundBuffer {
} }
static final class Entry { static final class Entry {
private static final ObjectPool<Entry> RECYCLER = ObjectPool.newPool(new ObjectCreator<Entry>() { private static final ObjectPool<Entry> RECYCLER = ObjectPool.newPool(Entry::new);
@Override
public Entry newObject(Handle<Entry> handle) {
return new Entry(handle);
}
});
private final Handle<Entry> handle; private final Handle<Entry> handle;
Entry next; Entry next;

View File

@ -966,13 +966,7 @@ final class DefaultChannelHandlerContext implements ChannelHandlerContext, Resou
static final class WriteTask extends AbstractWriteTask implements SingleThreadEventLoop.NonWakeupRunnable { static final class WriteTask extends AbstractWriteTask implements SingleThreadEventLoop.NonWakeupRunnable {
private static final ObjectPool<WriteTask> RECYCLER = ObjectPool.newPool( private static final ObjectPool<WriteTask> RECYCLER = ObjectPool.newPool(WriteTask::new);
new ObjectPool.ObjectCreator<WriteTask>() {
@Override
public WriteTask newObject(ObjectPool.Handle<WriteTask> handle) {
return new WriteTask(handle);
}
});
static WriteTask newInstance( static WriteTask newInstance(
DefaultChannelHandlerContext ctx, Object msg, ChannelPromise promise) { DefaultChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
@ -993,13 +987,7 @@ final class DefaultChannelHandlerContext implements ChannelHandlerContext, Resou
static final class WriteAndFlushTask extends AbstractWriteTask { static final class WriteAndFlushTask extends AbstractWriteTask {
private static final ObjectPool<WriteAndFlushTask> RECYCLER = ObjectPool.newPool( private static final ObjectPool<WriteAndFlushTask> RECYCLER = ObjectPool.newPool(WriteAndFlushTask::new);
new ObjectPool.ObjectCreator<WriteAndFlushTask>() {
@Override
public WriteAndFlushTask newObject(ObjectPool.Handle<WriteAndFlushTask> handle) {
return new WriteAndFlushTask(handle);
}
});
static WriteAndFlushTask newInstance( static WriteAndFlushTask newInstance(
DefaultChannelHandlerContext ctx, Object msg, ChannelPromise promise) { DefaultChannelHandlerContext ctx, Object msg, ChannelPromise promise) {

View File

@ -20,7 +20,6 @@ import static java.util.Objects.requireNonNull;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.PromiseCombiner; import io.netty.util.concurrent.PromiseCombiner;
import io.netty.util.internal.ObjectPool; import io.netty.util.internal.ObjectPool;
import io.netty.util.internal.ObjectPool.ObjectCreator;
import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; 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. * Holds all meta-data and construct the linked-list structure.
*/ */
static final class PendingWrite { static final class PendingWrite {
private static final ObjectPool<PendingWrite> RECYCLER = ObjectPool.newPool(new ObjectCreator<PendingWrite>() { private static final ObjectPool<PendingWrite> RECYCLER = ObjectPool.newPool(PendingWrite::new);
@Override
public PendingWrite newObject(ObjectPool.Handle<PendingWrite> handle) {
return new PendingWrite(handle);
}
});
private final ObjectPool.Handle<PendingWrite> handle; private final ObjectPool.Handle<PendingWrite> handle;
private PendingWrite next; private PendingWrite next;

View File

@ -1608,22 +1608,19 @@ public class DefaultChannelPipelineTest {
assertEquals(expectedNumber, pipeline.names().size()); assertEquals(expectedNumber, pipeline.names().size());
assertEquals(expectedNumber, pipeline.toMap().size()); assertEquals(expectedNumber, pipeline.toMap().size());
pipeline.executor().submit(new Runnable() { pipeline.executor().submit(() -> {
@Override DefaultChannelHandlerContext ctx = (DefaultChannelHandlerContext) pipeline.firstContext();
public void run() { int handlerNumber = 0;
DefaultChannelHandlerContext ctx = (DefaultChannelHandlerContext) pipeline.firstContext(); if (ctx != null) {
int handlerNumber = 0; for (;;) {
if (ctx != null) { handlerNumber++;
for (;;) { if (ctx == pipeline.lastContext()) {
handlerNumber++; break;
if (ctx == pipeline.lastContext()) {
break;
}
ctx = ctx.next;
} }
ctx = ctx.next;
} }
assertEquals(expectedNumber, handlerNumber);
} }
assertEquals(expectedNumber, handlerNumber);
}).syncUninterruptibly(); }).syncUninterruptibly();
} }

View File

@ -295,13 +295,10 @@ public class PendingWriteQueueTest {
}); });
ChannelPromise promise2 = channel.newPromise(); ChannelPromise promise2 = channel.newPromise();
promise2.addListener((ChannelFutureListener) future -> failOrder.add(2)); promise2.addListener((ChannelFutureListener) future -> failOrder.add(2));
channel.eventLoop().execute(new Runnable() { channel.eventLoop().execute(() -> {
@Override queue.add(1L, promise);
public void run() { queue.add(2L, promise2);
queue.add(1L, promise); queue.removeAndFailAll(new Exception());
queue.add(2L, promise2);
queue.removeAndFailAll(new Exception());
}
}); });
assertTrue(promise.isDone()); assertTrue(promise.isDone());