Search code examples
javajdbcconnection-poolingexecutorservicevirtual-threads

Managing JDBC Connections using Java Virtual Threads


We have a service in Java 17 which executes logic on our end sends request to a third party system. The response time from the third party system is around 800-1400ms. We have a ThreadPoolExecutor for this with a size of 12 (cannot further increase it due to infrastructure limitations)

Our request sending rate was 5-8 requests/S due to the response time of the 3rd party system. To increase throughput we are upgrading to Java 21 to use Virtual Threads. However, during development testing there seems to be another issue being faced.

Our request sending rate has increased to around 50 requests/s. But we are facing Exceptions related to JDBC connection request failure. My db connection pool size must be around 100.

When my service starts there are 10 connections belonging to my microservice. When sending requests using ThreadPoolExecutor: 13 additional connections so total 23. When using newVirtualThreadPerTaskExecutor: total of 94 connections

I use the following query to monitor my PostGre Database V13.9

SELECT pid, datname, usename, application_name, client_addr, client_port, backend_start, query_start, state_change, query, state
FROM pg_stat_activity where application_name ='PostgreSQL JDBC Driver';

Exceptions:

org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:466) ~[spring-orm-6.1.2.jar:6.1.2]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:531) ~[spring-tx-6.1.2.jar:6.1.2]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:405) ~[spring-tx-6.1.2.jar:6.1.2]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:610) ~[spring-tx-6.1.2.jar:6.1.2]
    at java.base/java.util.concurrent.ThreadPerTaskExecutor$TaskRunner.run(ThreadPerTaskExecutor.java:314) ~[na:na]
    at java.base/java.lang.VirtualThread.run(VirtualThread.java:309) ~[na:na]
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection [FATAL: remaining connection slots are reserved for non-replication superuser connections] [n/a]
at java.base/java.util.concurrent.ThreadPerTaskExecutor$TaskRunner.run(ThreadPerTaskExecutor.java:314) ~[na:na]
    at java.base/java.lang.VirtualThread.run(VirtualThread.java:309) ~[na:na]
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection [FATAL: remaining connection slots are reserved for non-replication superuser connections] [n/a]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:63) ~[hibernate-core-6.4.1.Final.jar:6.4.1.Final]

What I understand is when using ThreadPoolExecutor of 12 threads, each thread makes an connection and uses that. When using Virtual Threads, as soon as any Virtual Thread gets busy in response waiting, or Thread.sleep, another Virtual Thread takes lead. As soon as I initiate a load test, I notice a burst of connections, some resulting in exceptions (For example 11 requests failed out of 1500 (due to JDBC error)), and then the process going forward moves smoothly utilising the max 94 connections currently that I have.

Question is, how do I resolve this, and limit the number of processes initiated at a time. And more importantly, limit the number of connections/resuse connections created to the database. I have multiple other applications to the database, so will not be able to increase them much.

I have tried using System property "jdk.virtualThreadScheduler.maxPoolSize" by passing the VM Arugment -Djdk.virtualThreadScheduler.maxPoolSize=5

But the exception still occurs even if set -Djdk.virtualThreadScheduler.maxPoolSize=1

What am I missing? Is it that Virtual Threads should be used for basic I/O tasks, CPU tasks, rather than communications with Third Party Systems?

Some code of how my Virtual Threads are initiated:

this.executorService = Executors.newSingleThreadScheduledExecutor();
this.taskExecutorService = Executors.newVirtualThreadPerTaskExecutor();

this.executorService.scheduleAtFixedRate(this, 0L, this.pollingTime.toMillis(), TimeUnit.MILLISECONDS); //Called once when service starts

public void run() {
    this.taskExecutorService.execute(//my runnable job);
}

I also tried using counters/semaphores to restrict Virtual Threads. It reduces throughput but it still creates new connections more compared to the ThreadPoolExecutor. Is it designed this way? I suspect each virtual thread / process creates a new connection, whereas in ThreadPoolExecutor it utilises the connection allocated to its PID. Any clarification or suggestions please?

Edit: (JDBC Connection Code) I see most delete queries in open connections, as that is what is executed when sending requests via virtual threads. Following is the code.

public Optional<Job> getNextJob(String queue) {
    Optional<Job> job = Optional.empty();

    try {
        Connection connection = this.dataSource.getConnection();

        try {
            String sql = "DELETE FROM scheduler_task WHERE id = (SELECT id FROM scheduler_task WHERE queue = ? and trigger_date < now() LIMIT 1 FOR UPDATE SKIP LOCKED) RETURNING id, queue, reference_id, trigger_date";
            PreparedStatement stmt = connection.prepareStatement(sql);

            try {
                ResultSet resultSet = stmt.executeQuery();

                try {
                    if (resultSet.next()) {
                        job = Optional.of(this.mapToJob(resultSet));
                    }
                } catch (Throwable var14) {
                    if (resultSet != null) {
                        try {
                            resultSet.close();
                        } catch (Throwable var13) {
                            var14.addSuppressed(var13);
                        }
                    }
                    throw var14;
                }

                if (resultSet != null) {
                    resultSet.close();
                }
            } catch (Throwable var15) {
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (Throwable var12) {
                        var15.addSuppressed(var12);
                    }
                }

                throw var15;
            }
            if (stmt != null) {
                stmt.close();
            }
        } catch (Throwable var16) {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Throwable var11) {
                    var16.addSuppressed(var11);
                }
            }

            throw var16;
        }
        if (connection != null) {
            connection.close();
        }

        return job;
    } catch (SQLException var17) {
        log.error("error", var17);
        throw new Exception(var17);
    }
}

Solution

  • I believe the issue is with the uncountable Virtual Threads initiated which each want to create new connections. What would have been best would be that if I have 90 available db connections, I limit platform threads in use to 90 using jdk.virtualThreadScheduler.maxPoolSize. This pool size of 90 platform threads create 90 connections. Then initiate a lot of virtual threads, which don't each create new DB connections, rather reuse those 90 platform thread's connections.

    As suggested by Basil Bourque I have limited my request sending via Virtual Threads using Semaphore.

    private void executeJob(Job job) {
         semaphore.acquire();
         jobExecutor.execute(job);
         semaphore.release();
    }
    

    and to avoid blocking calls waiting on acquire, only execute above method if:

    if (semaphore.availablePermits() > 0) {
        Job = //find job
        executeJob(job);
    }
    

    This seems to work, and limit my connections in the database. Also, the throughput has increased from 8 requests/s to 70 requests/s despite the slow responses.

    Edit: As mentioned by @igor.zh and during testing available permits is an estimated value only, I have modified my method as follows. Also I was using tomcat-jdbc pool, and have switched to Hikari which seems to be more efficient with the connections.

    private void executeJob(Job job) {
        if (!semaphore.tryAcquire()) {
            //let the thread die
            return;
        }
        try {
            jobExecutor.execute(job);
        } finally {
            semaphore.release();
        }
    }