1

I have created a restful API of the following where I have attempted to allow maximum connections asynchronously without blocking the HTTP thread.

@GET
@Path("sites")
@Produces(value = MediaType.APPLICATION_JSON)
public void getSites(@Suspended AsyncResponse response) {
    System.out.println("calling sites");
    CompletableFuture
            .supplyAsync(() -> DatabaseManager.getInstance().getSites())
            .exceptionally(this::handel)
            .thenAccept(response::resume);
}

However, the problem occurs once the DatabaseManager method is called. Because a new thread is created for every HTTP connection. This in turn creates a new database connection to the database server.

This then causes the database to error "Too many connections"

So what I am trying to create is some kind of blocking function that will hold the new threads in a waiting state until the DatabaseManager is idle and only allow a single database connection at any time.

1 Answer 1

3

Sounds like a bad design to me.

You should be using a database connection pool to manage connections.

It's important that you check out a connection, use it, and close it in the narrowest scope possible.

You need to pay close attention to transactions and isolation.

It's common for a single connection used in this way to handle many requests without issue. You can deal with 100 simultaneous users with a 10 connection pool if you do it right.

Take a look at Spring JDBC and TransactionManager to see how it can be done.

Writing multithreaded code is hard even for smart people. It's usually left to Java EE app servers, Netty, or vert.x to manage incoming requests. I'd advise you to not reinvent that wheel.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I thought it would be something like that after I posted the question. I have to wait 10 minutes before I can mark this as correct :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.