druid DruidDataSource.getConnectionInternal中会丢失线程interrupt状态

34gzjxbg  于 2022-10-22  发布在  Druid
关注(0)|答案(1)|浏览(246)

try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
connectErrorCountUpdater.incrementAndGet(this);
throw new SQLException("interrupt", e);
}
如果在多线程中使用,这一块捕获了InterruptException,导致如果线程被interrupt,这一状态就丢失了,线程处理必须针对每个数据库操作中出现的异常来特殊处理。建议在throw之前再次进行interrupt

ykejflvf

ykejflvf1#

底层使用可重入锁,估计处理起来困难。

可以自己封装一下:

public class InterruptedDruidDataSource extends DruidDataSource {

    @Override
    public DruidPooledConnection getConnection() throws SQLException {
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedBeforeGettingConnectionException("获取链接之前,线程已被中断");
        }
        try {
            return super.getConnection();
        } catch (SQLException e) {
            if (e.getCause() instanceof InterruptedException) {
                if (!Thread.currentThread().isInterrupted()) {
                    Thread.currentThread().interrupt();
                }
                throw new InterruptedInGettingConnectionException("获取链接过程中,线程被中断", e);
            } else if (Thread.currentThread().isInterrupted()) {
                // shouldn't happen
                throw new InterruptedInGettingConnectionException("获取链接过程中,线程被中断(不应该发生)", e);
            }
            throw e;
        }
    }
}

相关问题