Java 模擬數(shù)據(jù)庫連接池的實(shí)現(xiàn)代碼
前面學(xué)習(xí)過等待 - 通知機(jī)制,現(xiàn)在我們在其基礎(chǔ)上添加一個超時(shí)機(jī)制,模擬從連接池中獲取、使用和釋放連接的過程。客戶端獲取連接的過程被設(shè)定為等待超時(shí)模式,即如果在 1000 毫秒內(nèi)無法獲取到可用連接,將會返回給客戶端一個 null。設(shè)定連接池的大小為 10 個,然后通過調(diào)節(jié)客戶端的線程數(shù)來模擬無法獲取連接的場景
由于 java.sql.Connection 只是一個接口,最終實(shí)現(xiàn)是由數(shù)據(jù)庫驅(qū)動提供方來實(shí)現(xiàn),考慮到本例只是演示,我們通過動態(tài)代理構(gòu)造一個 Connection,該 Connection 的代理僅僅是在調(diào)用 commit() 方法時(shí)休眠 100 毫秒
public class ConnectionDriver {
static class ConnectionHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("commit".equals(method.getName())) {
TimeUnit.MICROSECONDS.sleep(100);
}
return null;
}
}
/**
* 創(chuàng)建一個 Connection 的代理,在 commit 時(shí)休眠 100 毫秒
*/
public static Connection createConnection() {
return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(),
new Class<?>[]{Connection.class}, new ConnectionHandler());
}
}
接下來是線程池的實(shí)現(xiàn)。本例通過一個雙向隊(duì)列來維護(hù)連接,調(diào)用方需要先調(diào)用 fetchConnection(long) 方法來指定在多少毫秒內(nèi)超時(shí)獲取連接,當(dāng)連接使用完成后,需要調(diào)用 releaseConnection(Connection) 方法將連接放回線程池
public class ConnectionPool {
private final LinkedList<Connection> pool = new LinkedList<>();
public ConnectionPool(int initialSize) {
// 初始化連接的最大上限
if (initialSize > 0) {
for (int i = 0; i < initialSize; i++) {
pool.addLast(ConnectionDriver.createConnection());
}
}
}
public void releaseConnection(Connection connection) {
if (connection != null) {
synchronized (pool) {
/* 連接釋放后需要進(jìn)行通知
* 這樣其他消費(fèi)者就能知道連接池已經(jīng)歸還了一個連接
*/
pool.addLast(connection);
pool.notifyAll();
}
}
}
/**
* 在給定毫秒時(shí)間內(nèi)獲取連接
*/
public Connection fetchConnection(long mills) throws InterruptedException {
synchronized (pool) {
// 完全超時(shí)
if (mills < 0) {
while (pool.isEmpty()) {
pool.wait();
}
return pool.removeFirst();
} else {
long future = System.currentTimeMillis() + mills;
long remaining = mills;
while (pool.isEmpty() && remaining > 0) {
pool.wait(remaining);
remaining = future - System.currentTimeMillis();
}
Connection result = null;
if (!pool.isEmpty()) {
result = pool.removeFirst();
}
return result;
}
}
}
}
最后編寫一個用于模擬客戶端獲取連接的示例,該示例將模擬多個線程同時(shí)從連接池獲取連接,并記錄總嘗試獲取數(shù)、獲取成功數(shù)和獲取失敗數(shù)
public class ConnectionPoolTest {
static ConnectionPool pool = new ConnectionPool(10);
static CountDownLatch start = new CountDownLatch(1);
static CountDownLatch end;
public static void main(String[] args) throws InterruptedException {
// 線程數(shù)量
int threadCount = 200;
end = new CountDownLatch(threadCount);
int count = 20;
AtomicInteger got = new AtomicInteger();
AtomicInteger notGot = new AtomicInteger();
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new ConnectionRunner(count, got, notGot), "ConnectionRunnerThread");
thread.start();
}
start.countDown();
end.await();
System.out.println("total invoke : " + (threadCount * count));
System.out.println("got connection : " + got);
System.out.println("not got connection : " + notGot);
}
static class ConnectionRunner implements Runnable {
int count;
AtomicInteger got;
AtomicInteger notGot;
public ConnectionRunner(int count, AtomicInteger got, AtomicInteger notGot) {
this.count = count;
this.got = got;
this.notGot = notGot;
}
@Override
public void run() {
try {
start.await();
} catch (Exception e) {
e.printStackTrace();
}
while (count > 0) {
try {
// 從線程池中獲取連接,如果 1000ms 內(nèi)無法獲取到,將返回 null
// 分別統(tǒng)計(jì)獲取連接的數(shù)量 got 和未獲取到的數(shù)量 notGot
Connection connection = pool.fetchConnection(1000);
if (connection != null) {
try {
connection.createStatement();
connection.commit();
} finally {
pool.releaseConnection(connection);
got.incrementAndGet();
}
} else {
notGot.incrementAndGet();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
count--;
}
}
end.countDown();
}
}
}
筆者設(shè)置線程數(shù)量為 200 時(shí),得出結(jié)果如下

當(dāng)設(shè)置為 500 時(shí),得出結(jié)果如下,當(dāng)然具體結(jié)果根據(jù)機(jī)器性能而異

可見,隨著客戶端線程數(shù)的增加,客戶端出現(xiàn)超時(shí)無法獲取連接的比率不斷升高。這種等待超時(shí)模式能保證程序出問題時(shí),線程不會一直運(yùn)行,而是按時(shí)返回,并告知客戶端獲取連接出現(xiàn)問題。數(shù)據(jù)庫連接池的實(shí)際也可以應(yīng)用到其他資源獲取的場景,針對昂貴資源的獲取都應(yīng)該加以限制
到此這篇關(guān)于Java 模擬數(shù)據(jù)庫連接池的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)Java 數(shù)據(jù)庫連接池內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中Json字符串直接轉(zhuǎn)換為對象的方法(包括多層List集合)
下面小編就為大家?guī)硪黄狫ava中Json字符串直接轉(zhuǎn)換為對象的方法(包括多層List集合)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
springboot集成redis哨兵集群的實(shí)現(xiàn)示例
本文主要介紹了springboot集成redis哨兵集群的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
Java中valueOf和parseInt的區(qū)別詳解
這篇文章主要介紹了Java中valueOf和parseInt的區(qū)別詳解,在編程中,遇到類型轉(zhuǎn)換,好像會經(jīng)常用到 parseInt 和 valueOf,當(dāng)然這里只拿 Integer 類型進(jìn)行陳述,其他類型也是雷同的,需要的朋友可以參考下2024-01-01
Java struts2 package元素配置及實(shí)例解析
這篇文章主要介紹了Java struts2 package元素配置及實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
springboot-dubbo cannot be cast to問題及解決
這篇文章主要介紹了springboot-dubbo cannot be cast to問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
詳解Java中使用ImageIO類對圖片進(jìn)行壓縮的方法
這篇文章主要介紹了Java中使用ImageIO類對圖片進(jìn)行壓縮的方法,能夠按指定的比例調(diào)整圖片的寬高,需要的朋友可以參考下2016-04-04
FastDFS分布式文件系統(tǒng)環(huán)境搭建及安裝過程解析
這篇文章主要介紹了FastDFS分布式文件系統(tǒng)環(huán)境搭建及安裝過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

