Skip to content

Commit ebe813e

Browse files
committed
Netty: couple of optimizations to improve performance
1 parent df65c97 commit ebe813e

6 files changed

Lines changed: 99 additions & 49 deletions

File tree

‎examples/src/main/java/examples/BenchApp.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ public Message(String message) {
3737
}
3838

3939
{
40+
get("/gc", ctx -> {
41+
long before = Runtime.getRuntime().freeMemory();
42+
System.gc();
43+
long after = Runtime.getRuntime().freeMemory();
44+
return before + ":" + after + "(" + (before - after) + ")";
45+
});
4046
get("/plaintext", ctx -> {
4147
return ctx.send(MESSAGE_BYTE);
4248
});

‎jooby/src/main/java/io/jooby/internal/RouterImpl.java‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,6 @@ public Stack executor(Executor executor) {
123123

124124
private List<RadixTree> trees;
125125

126-
private RouteAnalyzer analyzer;
127-
128126
private Executor worker = new ForwardingExecutor();
129127

130128
private Map<Route, Executor> routeExecutor = new HashMap<>();
@@ -137,8 +135,6 @@ public Stack executor(Executor executor) {
137135

138136
private ServiceRegistry services = new ServiceRegistryImpl();
139137

140-
private ClassSource source;
141-
142138
private SessionStore sessionStore = SessionStore.memory();
143139

144140
private String flashName = "jooby.flash";
@@ -147,9 +143,10 @@ public Stack executor(Executor executor) {
147143

148144
private List<BeanConverter> beanConverters;
149145

146+
private ClassLoader classLoader;
147+
150148
public RouterImpl(ClassLoader loader) {
151-
this.source = new ClassSource(loader);
152-
this.analyzer = new RouteAnalyzer(source, false);
149+
this.classLoader = loader;
153150
stack.addLast(new Stack(""));
154151

155152
converters = ValueConverters.defaultConverters();
@@ -427,6 +424,9 @@ private Route defineRoute(@Nonnull String method, @Nonnull String pattern,
427424
ValueConverters.addFallbackConverters(converters);
428425
ValueConverters.addFallbackBeanConverters(beanConverters);
429426

427+
ClassSource source = new ClassSource(classLoader);
428+
RouteAnalyzer analyzer = new RouteAnalyzer(source, false);
429+
430430
ExecutionMode mode = owner.getExecutionMode();
431431
for (Route route : routes) {
432432
String executorKey = route.getExecutorKey();
@@ -487,7 +487,6 @@ private Route defineRoute(@Nonnull String method, @Nonnull String pattern,
487487
routeExecutor.clear();
488488
routeExecutor = null;
489489
source.destroy();
490-
source = null;
491490
return this;
492491
}
493492

‎jooby/src/main/java/io/jooby/internal/RouterMatch.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ public void execute(Context context) {
7878
route.getPipeline().apply(context);
7979
} catch (Throwable x) {
8080
context.sendError(x);
81+
} finally {
82+
this.handler = null;
83+
this.route = null;
84+
this.vars = null;
8185
}
8286
}
8387

‎modules/jooby-netty/src/main/java/io/jooby/internal/netty/NettyContext.java‎

Lines changed: 51 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import io.netty.channel.ChannelFutureListener;
3434
import io.netty.channel.ChannelHandlerContext;
3535
import io.netty.channel.ChannelPipeline;
36+
import io.netty.channel.ChannelPromise;
3637
import io.netty.channel.DefaultFileRegion;
3738
import io.netty.handler.codec.http.DefaultFullHttpRequest;
3839
import io.netty.handler.codec.http.DefaultFullHttpResponse;
@@ -58,7 +59,6 @@
5859
import io.netty.handler.stream.ChunkedNioStream;
5960
import io.netty.handler.stream.ChunkedStream;
6061
import io.netty.handler.stream.ChunkedWriteHandler;
61-
import io.netty.handler.timeout.IdleState;
6262
import io.netty.handler.timeout.IdleStateHandler;
6363
import io.netty.util.ReferenceCounted;
6464

@@ -73,7 +73,6 @@
7373
import java.nio.channels.FileChannel;
7474
import java.nio.channels.ReadableByteChannel;
7575
import java.nio.charset.Charset;
76-
import java.time.Duration;
7776
import java.util.ArrayList;
7877
import java.util.Collection;
7978
import java.util.Collections;
@@ -101,7 +100,7 @@
101100
public class NettyContext implements DefaultContext, ChannelFutureListener {
102101

103102
private static final HttpHeaders NO_TRAILING = EmptyHttpHeaders.INSTANCE;
104-
final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(true);
103+
DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(true);
105104
private final int bufferSize;
106105
InterfaceHttpPostRequestDecoder decoder;
107106
private Router router;
@@ -436,9 +435,9 @@ private Context send(@Nonnull ByteBuf data) {
436435
data, setHeaders, NO_TRAILING);
437436
if (ctx.channel().eventLoop().inEventLoop()) {
438437
needsFlush = true;
439-
ctx.write(response).addListener(this);
438+
ctx.write(response, promise(this));
440439
} else {
441-
ctx.writeAndFlush(response).addListener(this);
440+
ctx.writeAndFlush(response, promise(this));
442441
}
443442
return this;
444443
}
@@ -447,6 +446,11 @@ public void flush() {
447446
if (needsFlush) {
448447
needsFlush = false;
449448
ctx.flush();
449+
this.ctx = null;
450+
this.req = null;
451+
this.route = null;
452+
this.router = null;
453+
this.headers = null;
450454
}
451455
}
452456

@@ -461,7 +465,7 @@ public void flush() {
461465
// Body
462466
ctx.write(new ChunkedNioStream(channel, bufferSize), ctx.voidPromise());
463467
// Finish
464-
ctx.writeAndFlush(EMPTY_LAST_CONTENT).addListener(this);
468+
ctx.writeAndFlush(EMPTY_LAST_CONTENT, promise(this));
465469
});
466470
return this;
467471
}
@@ -486,7 +490,7 @@ public void flush() {
486490
// Body
487491
ctx.write(chunkedStream, ctx.voidPromise());
488492
// Finish
489-
ctx.writeAndFlush(EMPTY_LAST_CONTENT).addListener(this);
493+
ctx.writeAndFlush(EMPTY_LAST_CONTENT, promise(this));
490494
});
491495
return this;
492496
} catch (Exception x) {
@@ -515,7 +519,7 @@ public void flush() {
515519
// Headers
516520
ctx.write(rsp, ctx.voidPromise());
517521
// Body
518-
ctx.writeAndFlush(chunkedInput).addListener(this);
522+
ctx.writeAndFlush(chunkedInput, promise(this));
519523
});
520524
} else {
521525
ctx.channel().eventLoop().execute(() -> {
@@ -525,7 +529,7 @@ public void flush() {
525529
ctx.write(new DefaultFileRegion(file, range.getStart(), range.getEnd()),
526530
ctx.voidPromise());
527531
// Finish
528-
ctx.writeAndFlush(EMPTY_LAST_CONTENT).addListener(this);
532+
ctx.writeAndFlush(EMPTY_LAST_CONTENT, promise(this));
529533
});
530534
}
531535
} catch (IOException x) {
@@ -557,7 +561,7 @@ public void flush() {
557561
DefaultFullHttpResponse rsp = new DefaultFullHttpResponse(HTTP_1_1,
558562
HttpResponseStatus.valueOf(statusCode.value()), Unpooled.EMPTY_BUFFER, setHeaders,
559563
NO_TRAILING);
560-
ctx.writeAndFlush(rsp).addListener(this);
564+
ctx.writeAndFlush(rsp, promise(this));
561565
return this;
562566
}
563567

@@ -573,17 +577,33 @@ public void flush() {
573577
}
574578

575579
private void ifSaveSession() {
576-
Session session = (Session) getAttributes().get(Session.NAME);
577-
if (session != null && (session.isNew() || session.isModify())) {
580+
Session session = saveSession();
581+
if (session != null) {
578582
SessionStore store = router.getSessionStore();
579583
store.saveSession(this, session);
580584
}
581585
}
582586

583-
private NettyOutputStream newOutputStream() {
584-
prepareChunked();
585-
return new NettyOutputStream(ctx, bufferSize,
586-
new DefaultHttpResponse(req.protocolVersion(), status, setHeaders), this);
587+
private Session saveSession() {
588+
Session session = (Session) getAttributes().get(Session.NAME);
589+
if (session != null && (session.isNew() || session.isModify())) {
590+
return session;
591+
}
592+
return session;
593+
}
594+
595+
private ChannelPromise promise(ChannelFutureListener listener) {
596+
if (pendingTasks()) {
597+
return ctx.newPromise().addListener(listener);
598+
}
599+
return ctx.voidPromise();
600+
}
601+
602+
private boolean pendingTasks() {
603+
return (saveSession() != null) ||
604+
(files != null && files.size() > 0) ||
605+
(decoder != null) ||
606+
shouldRelease(req);
587607
}
588608

589609
void destroy(Throwable cause) {
@@ -619,6 +639,12 @@ void destroy(Throwable cause) {
619639
release(req);
620640
}
621641

642+
private NettyOutputStream newOutputStream() {
643+
prepareChunked();
644+
return new NettyOutputStream(ctx, bufferSize,
645+
new DefaultHttpResponse(req.protocolVersion(), status, setHeaders), this);
646+
}
647+
622648
private FileUpload register(FileUpload upload) {
623649
if (this.files == null) {
624650
this.files = new ArrayList<>();
@@ -653,12 +679,18 @@ private void decodeForm(HttpRequest req, Formdata form) {
653679
}
654680

655681
private static void release(HttpRequest req) {
682+
if (shouldRelease(req)) {
683+
ReferenceCounted ref = (ReferenceCounted) req;
684+
ref.release();
685+
}
686+
}
687+
688+
private static boolean shouldRelease(HttpRequest req) {
656689
if (req instanceof ReferenceCounted) {
657690
ReferenceCounted ref = (ReferenceCounted) req;
658-
if (ref.refCnt() > 0) {
659-
ref.release();
660-
}
691+
return ref.refCnt() > 0;
661692
}
693+
return false;
662694
}
663695

664696
private long responseLength() {

‎modules/jooby-netty/src/main/java/io/jooby/internal/netty/NettyHandler.java‎

Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -24,32 +24,26 @@
2424
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
2525
import io.netty.handler.codec.http.multipart.HttpPostStandardRequestDecoder;
2626
import io.netty.handler.codec.http.multipart.InterfaceHttpPostRequestDecoder;
27-
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
2827
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
2928
import io.netty.handler.timeout.IdleStateEvent;
3029
import io.netty.util.AsciiString;
31-
import io.netty.util.concurrent.FastThreadLocal;
3230
import org.slf4j.Logger;
3331

3432
import java.nio.charset.StandardCharsets;
35-
import java.text.DateFormat;
36-
import java.text.SimpleDateFormat;
37-
import java.util.Date;
33+
import java.time.ZoneOffset;
34+
import java.time.ZonedDateTime;
35+
import java.time.format.DateTimeFormatter;
3836
import java.util.concurrent.ScheduledExecutorService;
39-
40-
import static java.util.concurrent.TimeUnit.MILLISECONDS;
37+
import java.util.concurrent.TimeUnit;
38+
import java.util.concurrent.atomic.AtomicReference;
4139

4240
public class NettyHandler extends ChannelInboundHandlerAdapter {
43-
private static final FastThreadLocal<DateFormat> FORMAT = new FastThreadLocal<DateFormat>() {
44-
@Override
45-
protected DateFormat initialValue() {
46-
return new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
47-
}
48-
};
41+
private static final AtomicReference<String> cachedDateString = new AtomicReference<>();
4942

50-
private static final AsciiString server = AsciiString.cached("N");
43+
private static final Runnable INVALIDATE_TASK = () -> cachedDateString.set(null);
5144

52-
private volatile AsciiString date = new AsciiString(FORMAT.get().format(new Date()));
45+
private static final AsciiString server = AsciiString.cached("N");
46+
private final ScheduledExecutorService scheduler;
5347

5448
private static final int DATE_INTERVAL = 1000;
5549

@@ -68,27 +62,22 @@ protected DateFormat initialValue() {
6862

6963
public NettyHandler(ScheduledExecutorService scheduler, Router router, long maxRequestSize,
7064
int bufferSize, HttpDataFactory factory, boolean defaultHeaders) {
71-
scheduler
72-
.scheduleWithFixedDelay(dateSync(FORMAT.get()), DATE_INTERVAL, DATE_INTERVAL, MILLISECONDS);
65+
this.scheduler = scheduler;
7366
this.router = router;
7467
this.maxRequestSize = maxRequestSize;
7568
this.factory = factory;
7669
this.bufferSize = bufferSize;
7770
this.defaultHeaders = defaultHeaders;
7871
}
7972

80-
private Runnable dateSync(DateFormat format) {
81-
return () -> date = new AsciiString(format.format(new Date()));
82-
}
83-
8473
@Override
8574
public void channelRead(ChannelHandlerContext ctx, Object msg) {
8675
if (msg instanceof HttpRequest) {
8776
HttpRequest req = (HttpRequest) msg;
8877
context = new NettyContext(ctx, req, router, pathOnly(req.uri()), bufferSize);
8978

9079
if (defaultHeaders) {
91-
context.setHeaders.set(HttpHeaderNames.DATE, date);
80+
context.setHeaders.set(HttpHeaderNames.DATE, date(scheduler));
9281
context.setHeaders.set(HttpHeaderNames.SERVER, server);
9382
}
9483
context.setHeaders.set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
@@ -100,6 +89,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
10089
decoder = newDecoder(req, factory);
10190
} else {
10291
result.execute(context);
92+
result = null;
10393
}
10494
} else if (decoder != null && msg instanceof HttpContent) {
10595
HttpContent chunk = (HttpContent) msg;
@@ -122,6 +112,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
122112
context.decoder = decoder;
123113
resetDecoderState(false);
124114
result.execute(context);
115+
result = null;
125116
}
126117
} else if (msg instanceof WebSocketFrame) {
127118
if (context.webSocket != null) {
@@ -133,6 +124,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
133124
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
134125
if (context != null) {
135126
context.flush();
127+
context = null;
136128
}
137129
}
138130

@@ -218,5 +210,22 @@ private static long contentLength(HttpRequest req) {
218210
return -1;
219211
}
220212
}
213+
214+
private static String date(ScheduledExecutorService scheduler) {
215+
String dateString = cachedDateString.get();
216+
if (dateString == null) {
217+
//set the time and register a timer to invalidate it
218+
//note that this is racey, it does not matter if multiple threads do this
219+
//the perf cost of synchronizing would be more than the perf cost of multiple threads running it
220+
long realTime = System.currentTimeMillis();
221+
long mod = realTime % DATE_INTERVAL;
222+
long toGo = DATE_INTERVAL - mod;
223+
dateString = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneOffset.UTC));
224+
if (cachedDateString.compareAndSet(null, dateString)) {
225+
scheduler.schedule(INVALIDATE_TASK, toGo, TimeUnit.MILLISECONDS);
226+
}
227+
}
228+
return dateString;
229+
}
221230
}
222231

‎tests/src/test/kotlin/io/jooby/FeaturedKotlinTest.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import kotlinx.coroutines.delay
88
import org.junit.jupiter.api.Assertions.assertEquals
99
import org.junit.jupiter.api.Test
1010

11-
class FeaturedKotlinTest {
11+
class FeaturedKotlinTest {
1212

1313
@Test
1414
fun explicitContext() {

0 commit comments

Comments
 (0)