use of io.netty.channel.EventLoop in project LanternServer by LanternPowered.
the class NetworkSession method sendWithFuture.
/**
* Sends a iterable of {@link Message}s.
*
* @param messages The messages
*/
public ChannelFuture sendWithFuture(Iterable<Message> messages) {
checkNotNull(messages, "messages");
final Iterator<Message> it = messages.iterator();
checkArgument(it.hasNext(), "messages cannot be empty");
final ChannelPromise promise = this.channel.newPromise();
if (!this.channel.isActive()) {
return promise;
}
promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
Message message = it.next();
// there is only one message.
if (!it.hasNext()) {
this.channel.writeAndFlush(message, promise);
} else {
final EventLoop eventLoop = this.channel.eventLoop();
final ChannelPromise voidPromise = this.channel.voidPromise();
if (eventLoop.inEventLoop()) {
while (true) {
final boolean next = it.hasNext();
// Only use a normal channel promise for the last message
this.channel.writeAndFlush(message, next ? voidPromise : promise);
if (!next) {
break;
}
message = it.next();
ReferenceCountUtil.retain(message);
}
} else {
// If there are more then one message, combine them inside the
// event loop to reduce overhead of wakeup calls and object creation
// Create a copy of the list, to avoid concurrent modifications
final List<Message> messages0 = ImmutableList.copyOf(messages);
messages0.forEach(ReferenceCountUtil::retain);
eventLoop.submit(() -> {
final Iterator<Message> it0 = messages0.iterator();
do {
final Message message0 = it0.next();
// Only use a normal channel promise for the last message
this.channel.writeAndFlush(message0, it0.hasNext() ? voidPromise : promise);
} while (it0.hasNext());
});
}
}
return promise;
}
use of io.netty.channel.EventLoop in project LanternServer by LanternPowered.
the class NetworkSession method send.
/**
* Sends a array of {@link Message}s.
*
* @param messages The messages
*/
public void send(Message... messages) {
checkNotNull(messages, "messages");
checkArgument(messages.length != 0, "messages cannot be empty");
if (!this.channel.isActive()) {
return;
}
final ChannelPromise voidPromise = this.channel.voidPromise();
if (messages.length == 1) {
this.channel.writeAndFlush(messages[0], voidPromise);
} else {
final EventLoop eventLoop = this.channel.eventLoop();
if (eventLoop.inEventLoop()) {
for (Message message : messages) {
ReferenceCountUtil.retain(message);
this.channel.writeAndFlush(message, voidPromise);
}
} else {
// If there are more then one message, combine them inside the
// event loop to reduce overhead of wakeup calls and object creation
// Create a copy of the list, to avoid concurrent modifications
final List<Message> messages0 = ImmutableList.copyOf(messages);
messages0.forEach(ReferenceCountUtil::retain);
eventLoop.submit(() -> {
for (Message message0 : messages0) {
this.channel.writeAndFlush(message0, voidPromise);
}
});
}
}
}
use of io.netty.channel.EventLoop in project activemq-artemis by apache.
the class NettyConnection method write.
@Override
public final void write(ActiveMQBuffer buffer, final boolean flush, final boolean batched, final ChannelFutureListener futureListener) {
final int readableBytes = buffer.readableBytes();
if (logger.isDebugEnabled()) {
final int remainingBytes = this.writeBufferHighWaterMark - readableBytes;
if (remainingBytes < 0) {
logger.debug("a write request is exceeding by " + (-remainingBytes) + " bytes the writeBufferHighWaterMark size [ " + this.writeBufferHighWaterMark + " ] : consider to set it at least of " + readableBytes + " bytes");
}
}
// no need to lock because the Netty's channel is thread-safe
// and the order of write is ensured by the order of the write calls
final EventLoop eventLoop = channel.eventLoop();
final boolean inEventLoop = eventLoop.inEventLoop();
if (!inEventLoop) {
writeNotInEventLoop(buffer, flush, batched, futureListener);
} else {
// OLD COMMENT:
// create a task which will be picked up by the eventloop and trigger the write.
// This is mainly needed as this method is triggered by different threads for the same channel.
// if we not do this we may produce out of order writes.
// NOTE:
// the submitted task does not effect in any way the current written size in the batch
// until the loop will process it, leading to a longer life for the ActiveMQBuffer buffer!!!
// To solve it, will be necessary to manually perform the count of the current batch instead of rely on the
// Channel:Config::writeBufferHighWaterMark value.
this.pendingWritesOnEventLoop += readableBytes;
this.pendingWritesOnEventLoopView.lazySet(pendingWritesOnEventLoop);
eventLoop.execute(() -> {
this.pendingWritesOnEventLoop -= readableBytes;
this.pendingWritesOnEventLoopView.lazySet(pendingWritesOnEventLoop);
writeInEventLoop(buffer, flush, batched, futureListener);
});
}
}
use of io.netty.channel.EventLoop in project cassandra by apache.
the class HandshakeTest method handshake.
private Result handshake(int req, AcceptVersions acceptOutbound, AcceptVersions acceptInbound) throws ExecutionException, InterruptedException {
InboundSockets inbound = new InboundSockets(new InboundConnectionSettings().withAcceptMessaging(acceptInbound));
try {
inbound.open();
InetAddressAndPort endpoint = inbound.sockets().stream().map(s -> s.settings.bindAddress).findFirst().get();
EventLoop eventLoop = factory.defaultGroup().next();
Future<Result<MessagingSuccess>> future = initiateMessaging(eventLoop, SMALL_MESSAGES, new OutboundConnectionSettings(endpoint).withAcceptVersions(acceptOutbound).withDefaults(ConnectionCategory.MESSAGING), req, AsyncPromise.withExecutor(eventLoop));
return future.get();
} finally {
inbound.close().await(1L, TimeUnit.SECONDS);
}
}
use of io.netty.channel.EventLoop in project zipkin by openzipkin.
the class ScribeInboundHandler method channelRead.
@Override
public void channelRead(ChannelHandlerContext ctx, Object payload) {
assert payload instanceof ByteBuf;
HttpRequest request = HttpRequest.of(THRIFT_HEADERS, HttpData.wrap((ByteBuf) payload));
ServiceRequestContextBuilder requestContextBuilder = ServiceRequestContext.builder(request).service(scribeService).alloc(ctx.alloc());
if (ctx.executor() instanceof EventLoop) {
requestContextBuilder.eventLoop((EventLoop) ctx.executor());
}
ServiceRequestContext requestContext = requestContextBuilder.build();
final HttpResponse response;
try (SafeCloseable unused = requestContext.push()) {
response = HttpResponse.of(scribeService.serve(requestContext, request));
} catch (Throwable t) {
propagateIfFatal(t);
exceptionCaught(ctx, t);
return;
}
int responseIndex = nextResponseIndex++;
response.aggregateWithPooledObjects(ctx.executor(), ctx.alloc()).handle((msg, t) -> {
if (t != null) {
exceptionCaught(ctx, t);
return null;
}
try (HttpData content = msg.content()) {
ByteBuf returned = ctx.alloc().buffer(content.length() + 4);
returned.writeInt(content.length());
returned.writeBytes(content.byteBuf());
if (responseIndex == previouslySentResponseIndex + 1) {
ctx.writeAndFlush(returned);
previouslySentResponseIndex++;
flushResponses(ctx);
} else {
pendingResponses.put(responseIndex, returned);
}
}
return null;
});
}
Aggregations