C3P0多数据源的死锁问题
最近在写的数据迁移工具完成的差不多了,今天将连接池换成C3P0,发现一个问题,就是配置了多个数据源的C3P0在同时获取不同数据源的Connection时会发生死锁。 1.运行如下的代码,用JProfiler测试,会发现死锁的情况: 代码: package com.highgo.test.c3p0dea
最近在写的数据迁移工具完成的差不多了,今天将连接池换成C3P0,发现一个问题,就是配置了多个数据源的C3P0在同时获取不同数据源的Connection时会发生死锁。
1.运行如下的代码,用JProfiler测试,会发现死锁的情况:
代码:
package com.highgo.test.c3p0deadlock; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; //加锁source个postgre的ComboPooledDataSource的getConnection用一个锁 public class Test { public static void main(String[] args) throws InterruptedException { ComboPooledDataSource source = new ComboPooledDataSource("source"); ComboPooledDataSource source2 = new ComboPooledDataSource("source"); ComboPooledDataSource postgres = new ComboPooledDataSource("postgres"); ComboPooledDataSource postgres2 = new ComboPooledDataSource("postgres"); new Thread(new SourceGetConn(source), "source").start(); // new Thread(new SourceGetConn(source2), "source2").start(); // Thread.sleep(1000); new Thread(new DestGetConn(postgres), "postgres").start(); // new Thread(new DestGetConn(postgres2), "postgres2").start(); } } class SourceGetConn implements Runnable { private ComboPooledDataSource source = null; public SourceGetConn(ComboPooledDataSource source) { this.source = source; } @Override public void run() { while (true) { try { Thread.sleep(1000); source.getConnection(); System.out.println("I get a Connection! I am in " + Thread.currentThread().getName()); } catch (InterruptedException | SQLException e) { e.printStackTrace(); } } } } class DestGetConn implements Runnable { private ComboPooledDataSource postgres = null; public DestGetConn(ComboPooledDataSource source) { this.postgres = source; } @Override public void run() { while (true) { try { Thread.sleep(1000); postgres.getConnection(); System.out.println("I get a Connection! I am in " + Thread.currentThread().getName()); } catch (InterruptedException | SQLException e) { e.printStackTrace(); } } } }
死锁情况:

可以看到source和postgre两个进程都被一个没有记录的对象锁住了。
2.将上边的代码的Thread.sleep注释去掉,在运行,是不会有死锁问题的,于是查看C3P0的源代码,ComboPooledDataSource@getConnection是继承自AbstractPoolBackedDataSource#getConnection,代码如下:
public Connection getConnection() throws SQLException { PooledConnection pc = getPoolManager().getPool().checkoutPooledConnection(); return pc.getConnection(); } public Connection getConnection(String username, String password) throws SQLException { PooledConnection pc = getPoolManager().getPool(username, password).checkoutPooledConnection(); return pc.getConnection(); }
先看这个PoolManager,AbstractPoolBackedDataSource#getPoolManager方法的实现如下,是线程安全的
private synchronized C3P0PooledConnectionPoolManager getPoolManager() throws SQLException { if (poolManager == null) { ConnectionPoolDataSource cpds = assertCpds(); poolManager = new C3P0PooledConnectionPoolManager(cpds, null, null, this.getNumHelperThreads(), this.getIdentityToken(), this.getDataSourceName()); if (logger.isLoggable(MLevel.INFO)) logger.info("Initializing c3p0 pool... " + this.toString( true ) /* + "; using pool manager: " + poolManager */); } return poolManager; }
再接着看getPool方法,也是线程安全的;
public synchronized C3P0PooledConnectionPool getPool(String username, String password, boolean create) throws SQLException { if (create) return getPool( username, password ); else { DbAuth checkAuth = new DbAuth( username, password ); C3P0PooledConnectionPool out = (C3P0PooledConnectionPool) authsToPools.get(checkAuth); if (out == null) throw new SQLException("No pool has been initialized for databse user '" + username + "' with the specified password."); else return out; } }
public PooledConnection checkoutPooledConnection() throws SQLException { //System.err.println(this + " -- CHECKOUT"); try { PooledConnection pc = (PooledConnection) this.checkoutAndMarkConnectionInUse(); pc.addConnectionEventListener( cl ); return pc; } catch (TimeoutException e) { throw SqlUtils.toSQLException("An attempt by a client to checkout a Connection has timed out.", e); } catch (CannotAcquireResourceException e) { throw SqlUtils.toSQLException("Connections could not be acquired from the underlying database!", "08001", e); } catch (Exception e) { throw SqlUtils.toSQLException(e); } }
public synchronized Connection getConnection() throws SQLException { if ( exposedProxy != null) { //DEBUG //System.err.println("[DOUBLE_GET_TESTER] -- double getting a Connection from " + this ); //new Exception("[DOUBLE_GET_TESTER] -- Double-Get Stack Trace").printStackTrace(); //origGet.printStackTrace(); // System.err.println("c3p0 -- Uh oh... getConnection() was called on a PooledConnection when " + // "it had already provided a client with a Connection that has not yet been " + // "closed. This probably indicates a bug in the connection pool!!!"); logger.warning("c3p0 -- Uh oh... getConnection() was called on a PooledConnection when " + "it had already provided a client with a Connection that has not yet been " + "closed. This probably indicates a bug in the connection pool!!!"); return exposedProxy; } else { return getCreateNewConnection(); } }
package com.highgo.test.c3p0deadlock; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; //加锁source个postgre的ComboPooledDataSource的getConnection用一个锁 public class Test { public static void main(String[] args) throws InterruptedException { ComboPooledDataSource source = new ComboPooledDataSource("source"); // ComboPooledDataSource source2 = new ComboPooledDataSource("source"); ComboPooledDataSource postgres = new ComboPooledDataSource("postgres"); // ComboPooledDataSource postgres2 = new ComboPooledDataSource("postgres"); new Thread(new SourceGetConn(source), "source").start(); new Thread(new SourceGetConn(source), "source2").start(); // Thread.sleep(1000); // new Thread(new DestGetConn(postgres), "postgres").start(); // new Thread(new DestGetConn(postgres2), "postgres2").start(); } } class SourceGetConn implements Runnable { private ComboPooledDataSource source = null; public SourceGetConn(ComboPooledDataSource source) { this.source = source; } @Override public void run() { while (true) { try { Thread.sleep(1000); source.getConnection(); System.out.println("I get a Connection! I am in " + Thread.currentThread().getName()); } catch (InterruptedException | SQLException e) { e.printStackTrace(); } } } } class DestGetConn implements Runnable { private ComboPooledDataSource postgres = null; public DestGetConn(ComboPooledDataSource source) { this.postgres = source; } @Override public void run() { while (true) { try { Thread.sleep(1000); postgres.getConnection(); System.out.println("I get a Connection! I am in " + Thread.currentThread().getName()); } catch (InterruptedException | SQLException e) { e.printStackTrace(); } } } }
3.经过测试发现同一个数据源的两个ComboPooledDataSource实例,getConnection方法不加锁的情况下,也是没有问题的。
稍微总结一下:
C3P0在一个ComboPooledDataSource实例的getConnection方法是线程安全的
C3P0在一个数据源的多个ComboPooledDataSource实例的getConnection方法也是线程安全的
C3P0在多个数据源的多个ComboPooledDataSource不同时调用getConnection的情况下,不会发生死锁(基于概率,若干时间之后,肯定会发生死锁)
C3P0在多个数据源的多个ComboPooledDataSource实例的getConnection方法同时(相邻的两行代码)调用时,会发生死锁现象,如1中所述
4.总结:
属于不同数据源的多个ComboPooledDataSource实例的getConnection方法调用要互斥
测试代码如下:
package com.highgo.test.c3p0deadlock; import java.sql.SQLException; import java.util.concurrent.locks.ReentrantLock; import com.mchange.v2.c3p0.ComboPooledDataSource; //加锁source个postgre的ComboPooledDataSource的getConnection用一个锁 public class Test2 { public static void main(String[] args) throws InterruptedException { ComboPooledDataSource source = new ComboPooledDataSource("source"); ComboPooledDataSource source2 = new ComboPooledDataSource("source"); ComboPooledDataSource postgres = new ComboPooledDataSource("postgres"); ComboPooledDataSource postgres2 = new ComboPooledDataSource("postgres"); ReentrantLock lock = new ReentrantLock(); new Thread(new SourceGetConn2(source, lock), "source").start(); new Thread(new SourceGetConn2(source2, lock), "source2").start(); Thread.sleep(1000); new Thread(new DestGetConn2(postgres, lock), "postgres").start(); new Thread(new DestGetConn2(postgres2, lock), "postgres2").start(); } } class SourceGetConn2 implements Runnable { private ComboPooledDataSource source = null; private ReentrantLock lock; public SourceGetConn2(ComboPooledDataSource source, ReentrantLock lock) { this.source = source; this.lock = lock; } @Override public void run() { while (true) { try { Thread.sleep(1000); lock.lock(); source.getConnection(); lock.unlock(); System.out.println("I get a Connection! I am in " + Thread.currentThread().getName()); } catch (InterruptedException | SQLException e) { e.printStackTrace(); } } } } class DestGetConn2 implements Runnable { private ComboPooledDataSource postgres = null; private ReentrantLock lock; public DestGetConn2(ComboPooledDataSource source, ReentrantLock lock) { this.postgres = source; this.lock = lock; } @Override public void run() { while (true) { try { Thread.sleep(1000); lock.lock(); postgres.getConnection(); lock.unlock(); System.out.println("I get a Connection! I am in " + Thread.currentThread().getName()); } catch (InterruptedException | SQLException e) { e.printStackTrace(); } } } }
5.最后总结一个效率还可以的工具类
package com.highgo.hgdbadmin.myutil; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Util { public static String SOURCE = "source"; public static String POSTGRES = "postgres"; private ComboPooledDataSource source = null; private ComboPooledDataSource postgres = null; private static C3P0Util instance = null; private C3P0Util() { source = new ComboPooledDataSource("source"); postgres = new ComboPooledDataSource("postgres"); } public static final synchronized C3P0Util getInstance() { if (instance == null) { instance = new C3P0Util(); } return instance; } public synchronized Connection getConnection(String dataSource) throws SQLException { if ("source".equals(dataSource)) { return source.getConnection(); } else if ("postgres".equals(dataSource)) { return postgres.getConnection(); } return null; } public synchronized void close(Connection conn) { try { if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { } } public synchronized void close(Statement stat) { try { if (stat != null) { stat.close(); stat = null; } } catch (SQLException e) { } } public synchronized void close(ResultSet rest) { try { if (rest != null) { rest.close(); rest = null; } } catch (SQLException e) { } } public static void main(String[] args) { new Thread(new TestThread(), "test").start(); } private static class TestThread implements Runnable { private String dataSource = "source"; @Override public void run() { while (true) { try { Connection conn = C3P0Util.getInstance().getConnection(""); System.out.println("hello,this is " + dataSource); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ("source".equals(dataSource)) { dataSource = "postgres"; } else { dataSource = "source"; } } } } }

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











밈 동전 거래에 가장 적합한 플랫폼은 다음과 같습니다. 1. 유동성이 높은 세계 최대의 Binance, 높은 유동성과 낮은 취급 수수료; 2. 다양한 밈 동전을 지원하는 효율적인 거래 엔진 인 OKX; 3. Xbit, 분산, 교차 체인 거래 지원; 4. 혈청 주문서와 결합 된 저렴한 비용, 저렴한 비용; 5. Pancakeswap (BSC DEX), 낮은 거래 수수료 및 빠른 속도; 6. Orca (Solana Dex), 사용자 경험 최적화; 7. 코인베이스, 높은 보안, 초보자에게 적합한; 8. 아시아에서 잘 알려진 Huobi, 풍부한 거래 쌍; 9. Dexrabbit, 지능

초보자에게 적합한 cryptocurrency 데이터 플랫폼에는 CoinmarketCap 및 비소 트럼펫이 포함됩니다. 1. CoinmarketCap은 초보자 및 기본 분석 요구에 대한 글로벌 실시간 가격, 시장 가치 및 거래량 순위를 제공합니다. 2. 비소 인용문은 중국 사용자가 저 위험 잠재적 프로젝트를 신속하게 선별하는 데 적합한 중국 친화적 인 인터페이스를 제공합니다.

통화 서클의 상위 3 개 무료 시장보기 소프트웨어는 OKX, Binance 및 Gate.io입니다. 1. OKX는 다양한 차트 및 시장 분석을 지원하는 간단한 인터페이스 및 실시간 데이터를 제공합니다. 2. Binance는 강력한 기능, 정확한 데이터를 가지고 있으며 모든 종류의 거래자에게 적합합니다. 3. Gate.io는 안정성과 포괄적 성으로 유명하며 장기 및 단기 투자자에게 적합합니다.

상위 10 개 가상 통화 시청 플랫폼에 대한 권장 앱 : 1. OKX, 2. BINANCE, 3. GATE.IO, 4. HUOBI, 5. COINBASE, 6. KRAKE, 7. BITFINEX, 8. KUCOIN, 9. BITSTAMP, 실시간 시장 트렌드, 기술적 인 분석 및 사용자 제공 기준을 제공하는 데 도움이됩니다.

상위 10 개 디지털 가상 통화 앱은 다음과 같습니다. 1. OKX, 2. BINANCE, 3. GATE.IO, 4. COINBASE, 5. KRAKEN, 6. HUOBI, 7. KUCOIN, 8. BITFINEX, 9. BITSTAMP, 10. POLONIEX. 이러한 거래소는 거래량, 사용자 경험 및 보안과 같은 요소를 기반으로 선택되며 모두 다양한 디지털 통화 거래 서비스 및 효율적인 거래 경험을 제공합니다.

상위 10 개 디지털 환전 교환에서 권장되는 앱 : 1. OKX, 2. BINANCE, 3. GATE.IO, 4. HUOBI, 5. COINBASE, 6. KUCOIN, 7. KRAKEN, 8. BITFINEX, 9. BITSTAMP, 이러한 앱은 실시간 시장 동향, 기술 분석 및 가격 리마 닉을 제공하는 데 도움이됩니다.

초보자에게 적합한 디지털 통화 거래 플랫폼을 선택할 때는 보안, 사용 편의성, 교육 자원 및 비용 투명성을 고려해야합니다. 1. 냉장 저장, 2 요인 검증 및 자산 보험을 제공하는 플랫폼에 우선 순위가 부여됩니다. 2. 간단한 인터페이스와 명확한 작동이있는 앱은 초보자에게 더 적합합니다. 3. 플랫폼은 튜토리얼 및 시장 분석과 같은 학습 도구를 제공해야합니다. 4. 거래 수수료 및 현금 인출 수수료와 같은 숨겨진 비용에주의하십시오.

신뢰할 수 있고 사용하기 쉬운 가상 환전 앱은 다음과 같습니다. 1. Binance, 2. OKX, 3. Gate.io, 4. Coinbase, 5. Kraken, 6. Huobi Global, 7. Bitfinex, 8. Kucoin, 9. Poloniex. 이 플랫폼은 거래량, 사용자 경험 및 보안에 가장 적합한 것으로 선정되었으며 모두 등록, 확인, 입금, 인출 및 거래 운영을 제공합니다.
