Answer the question
In order to leave comments, you need to log in
How to manage threads in Java when working with chains of asynchronous tasks?
For the last six months at work, I have been making a service in which I am trying to achieve the highest throughput on a bunch of java + netty + mysql + redis.
For me, it is built according to an asynchronous model and, in general, it does something like this:
it receives a request via http (or takes it from AMQP),
then polls the radish,
then takes data from the database,
based on this data it decides which service to send processing to
(and services third-party ones, you need to rely on the worst scenarios of their work),
then it can get into the database again,
then some other things along the way
and gives an http response (or lays it in another AMQP queue).
The load on the CPU is small. The time of one request consists of 1% of the CPU time (intermediate processing), 4% of the response from the base and 95% of the response time of the third-party service.
Very simplified code can be written like this:
void onRequest(Context ctx) {
// здесь тред netty-worker
Request request = parseRequest(ctx);
sqlExecutor.submit(request)
.thenCompose(model -> {
// здесь тред sqlExecutor'а, т.к. именно в том тредпуле происходит комплит фьючи
val something = doSomething(model, ctx);
switch(pickService(something)) {
case SERVICE_1: return service1.handleSomething(model);
..
case SERVICE_N: return serviceN.handleSomething(model);
}
})
.thenApply(serviceResponse -> {
// здесь тред из serviceX
val somethingElse = doSomethingElse(serviceResponse);
return toHttpResponse(somethingElse);
})
.thenAccept(httpResponse -> {
// здесь тред из serviceX
ctx.getResponse().send(httpResponse);
})
.exceptionally(e -> {
// здесь может оказаться netty-worker, sqlExecutor или тред из serviceX
log.warn(e);
ctx.getResponse().send(500, "failed");
});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question