我是靠谱客的博主 现代唇膏,最近开发中收集的这篇文章主要介绍Java实现数据库连接示例,觉得挺不错的,现在分享给大家,希望可以做个参考。

连接池

package javaStudy.connectionPoolDemo;
import java.sql.Connection;
import java.util.LinkedList;
/**
* Created by Clanner on 2018/2/6.
* 连接池
*/
public class ConnectionPool {
private LinkedList<Connection> pool = new LinkedList<>();
/**
* @param initialSize 连接池大小
*/
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) {
pool.addLast(connection);
pool.notifyAll();
}
}
}
/**
*
* @param mills 等待超时时间
* @return 从连接池中返回连接实例
* @throws InterruptedException
*/
public Connection fetchConnection(long mills) throws InterruptedException {
synchronized (pool) {
//完全超时
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;
}
}
}
}
返回连接实例

package javaStudy.connectionPoolDemo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.concurrent.TimeUnit;
/**
* Created by Clanner on 2018/2/6.
* 构造Connection
*/
public class ConnectionDriver {
static class ConnectionHolder implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//这里的Connection只是一个接口,最终的实现是由数据库驱动提供的,这里是示例所以先返回null
if (method.getName().equals("commit")) {
TimeUnit.MILLISECONDS.sleep(100);
}
return null;
}
}
//创建一个Connection的代理,在commit时休眠100毫秒
public static final Connection createConnection() {
return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(),
new Class<?>[]{Connection.class}, new ConnectionHolder());
}
}
测试

package javaStudy.connectionPoolDemo;
import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Clanner on 2018/2/6.
*/
public class ConnectionPoolTest {
static ConnectionPool pool = new ConnectionPool(10);
//保证所有ConnectionRunner能够同时开始
static CountDownLatch start = new CountDownLatch(1);
//main线程将会等待所有ConnectionRunner结束后才能继续执行
static CountDownLatch end;
public static void main(String[] args) throws Exception {
//线程数量
int threadCount = 50;
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内无法获取到,将会返回null
//分别统计连接获取的数量got和未获取到的数量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();
}
}
}

PS:以上内容出自《JAVA并发编程的艺术》一书


最后

以上就是现代唇膏为你收集整理的Java实现数据库连接示例的全部内容,希望文章能够帮你解决Java实现数据库连接示例所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部