C3P0多数据源的死锁问题

Jun 07, 2016 pm 04:09 PM
道具 データ 情報元 デッドロック 移行する 質問

最近在写的数据迁移工具完成的差不多了,今天将连接池换成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;	    
    }
ログイン後にコピー
从上边的代码也可以看出,一个DataSource实例,只保持一个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;
        }
    }
ログイン後にコピー
再看C3P0PooledConnectionPool#checkoutPooledConnection();
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); }
    }
ログイン後にコピー
返回一个C3P0PooledConnection 实例;C3P0PooledConnection 这个类里的方法都是线程安全的。ComboPooledDataSource@getConnection的最后一站就是C3P0PooledConnection#getConnection;如下:
 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(); }
    }
ログイン後にコピー
从上边的源码分析可以看出,一个ComboPooledDataSource实例的ComboPooledDataSource@getConnection是线程安全的,可以放心调用;可以测试一下,将最开始的代码稍微修改下,如下:
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();
			}
		}
	}

}
ログイン後にコピー
将一个ComboPooledDataSource实例,传给两个线程分别getConnection,getConnection的过程没有加锁的情况下是可以运行的,完全没有问题。
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";
				}
			}

		}

	}
}
ログイン後にコピー
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

ouyi ouyi ouyi ouix ouyiグローバルステーションログインホームページ ouyi ouyi ouyi ouix ouyiグローバルステーションログインホームページ Apr 21, 2025 pm 11:57 PM

OUYI OKXは、世界をリードするデジタル資産取引プラットフォームです。 1)その開発履歴が含まれます。2017年に開始され、中国名「OUYI」は2021年に発売され、2022年にOUYI OKXと改名されます。 3)プラットフォームの特別な機能には、マーケットデータサービスとリスク制御システムが含まれます。 4)コアの利点には、技術的な強さ、セキュリティシステム、サービスサポート、市場のカバレッジが含まれます。

通貨サークルでのレバレッジされた交換のランキングは 通貨サークルでのレバレッジされた交換のランキングは Apr 21, 2025 pm 11:24 PM

2025年のレバレッジド取引、セキュリティ、ユーザーエクスペリエンスで優れたパフォーマンスを持つプラットフォームは次のとおりです。1。OKX、高周波トレーダーに適しており、最大100倍のレバレッジを提供します。 2。世界中の多通貨トレーダーに適したバイナンス、125倍の高いレバレッジを提供します。 3。Gate.io、プロのデリバティブプレーヤーに適し、100倍のレバレッジを提供します。 4。ビットゲットは、初心者やソーシャルトレーダーに適しており、最大100倍のレバレッジを提供します。 5。Kraken、安定した投資家に適しており、5倍のレバレッジを提供します。 6。Altcoinエクスプローラーに適したBybit。20倍のレバレッジを提供します。 7。低コストのトレーダーに適したKucoinは、10倍のレバレッジを提供します。 8。ビットフィネックス、シニアプレイに適しています

通貨契約関係者に推奨される必須ソフトウェア 通貨契約関係者に推奨される必須ソフトウェア Apr 21, 2025 pm 11:21 PM

2025年の上位10の暗号通貨契約交換プラットフォームは次のとおりです。1。Binance先物、2。OKX先物、3。Gate.io、4。Huobi先物、5。Bitmex、6。Bibit、7。deribit、8。Bitfinex、9。Coinflex、10。

ハイブリッドブロックチェーン取引プラットフォームとは何ですか? ハイブリッドブロックチェーン取引プラットフォームとは何ですか? Apr 21, 2025 pm 11:36 PM

暗号通貨交換を選択するための提案:1。流動性の要件については、優先度は、その順序の深さと強力なボラティリティ抵抗のため、Binance、gate.ioまたはokxです。 2。コンプライアンスとセキュリティ、Coinbase、Kraken、Geminiには厳格な規制の承認があります。 3.革新的な機能、Kucoinのソフトステーキング、Bybitのデリバティブデザインは、上級ユーザーに適しています。

Quantum Chain Exchangeランキングトップ10推奨(2025年に更新) Quantum Chain Exchangeランキングトップ10推奨(2025年に更新) Apr 21, 2025 pm 11:48 PM

量子チェーンは、次の交換で取引できます。1。Binance:大規模な取引量、豊富な通貨、高いセキュリティを備えた世界最大の交換の1つ。 2。SESAMEOpen Door(gate.io):大規模な交換、さまざまなデジタル通貨取引を提供し、取引の深さが良好です。 3。OUYI(OKX):強力な包括的な強さ、大規模なトランザクションボリューム、および完全な安全対策を備えたOKグループによって運営されています。 4。ビットゲット:高速開発、量子チェーントランザクションを提供し、セキュリティを改善します。 5。Bithumb:日本で運営され、複数の主流の仮想通貨の取引をサポートし、安全で信頼性があります。 6。抹茶交換:フレンドリーなインターフェイスを備えた有名な交換と量子チェーンの取引をサポートします。 7。Huobi:量子チェーン取引を提供する大規模な交換、

通貨サークル契約取引プラットフォーム2025ランキング 通貨サークル契約取引プラットフォーム2025ランキング Apr 21, 2025 pm 11:15 PM

世界のトップ10の暗号通貨先物交換:1。BinanceFutures:豊富な契約製品、低料金、高流動性を提供します。 2。OKX:SSL暗号化とコールドウォレットストレージを使用して、複数の通貨取引をサポートします。 3。Huobi先物:安定したプラットフォームと優れたサービスで知られる教育リソースを提供します。 4。GATE.IO:革新的な契約製品と高流動性が高いが、FTXは破産した。 5。DELIBIT:オプションと永続的な契約に焦点を当て、専門的な取引ツールを提供します。 6。Coinflex:トークン化された先物契約とガバナンストークンフレックスを提供します。 7。PHEMEX:最大100倍のレバレッジ、低い取引手数料、革新的な契約を提供します。 8。b

2025年のデジタル通貨取引プラットフォームは何ですか?トップ10のデジタル通貨アプリの最新のランキング 2025年のデジタル通貨取引プラットフォームは何ですか?トップ10のデジタル通貨アプリの最新のランキング Apr 22, 2025 pm 03:09 PM

上位10の仮想通貨視聴プラットフォームの推奨アプリ:1。OKX、2。BINANCE、3。GATE.IO、4。HUOBI、5。COINBASE、6。KRAKEN、7。BITFINEX、8。KUCOIN、9。BYBIT、10。

2025年の世界で最高の暗号通貨交換:最高の推奨事項 2025年の世界で最高の暗号通貨交換:最高の推奨事項 Apr 21, 2025 pm 10:39 PM

2025年の世界で最高の暗号通貨交換は、1。Binance、2。Coinbase、3。Okx、4。Kraken、5。Kucoin、6。Bitget、7。Bibit、8。Gemini、9。crypto.com、10。MexcMatcha交換、これら能力とグローバルなカバレッジ、およびさまざまなニーズを持つ投資家に適しています。

See all articles