由于没有使用线程池技术,需要频繁的创建和销毁线程,这无疑十分消耗和浪费系统的资源,线程池的实现参考下一篇,这里请关注下“超时等待模式”
//对当前对象枷锁
public synchronized Object get(long mills){
long future = System.currentTimeMillis();
long remaining = mills;
//当超时大于0,并且result返回值不满足要求
while (result.isEmpty() && remaining > 0){
wait(remaining);
remaining = future - System.currentTimeMillis();
}
return result;
}
链接池的实现
package chapter04.connection_pool.no_thread_pool;
import java.sql.Connection;
import java.util.LinkedList;
/**
* Created by tianjun on 2017/11/4.
*/
public class ConnectionPool {
private 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){
//链接释放后需要进行通知,这样其他消费者能够感知到连接池中已经归还了一个连接
pool.addLast(connection);
pool.notifyAll();
}
}
}
//在mills时间内无法获取链接,就会返回null
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();
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 chapter04.connection_pool.no_thread_pool;
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 tianjun on 2017/11/4.
*/
public class ConnectionDriver {
static class ConnectionHandler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
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 ConnectionHandler());
}
}
连接池测试
package chapter04.connection_pool.no_thread_pool;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by tianjun on 2017/11/4.
*/
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 InterruptedException {
int threadCount = 10;//线程数
end = new CountDownLatch(threadCount);
int count = 20;//每个线程获取数据库连接池的次数
AtomicInteger got = new AtomicInteger();
AtomicInteger nogot = new AtomicInteger();
for(int i=0;i<threadCount;i++){
Thread thread = new Thread(new ConnectionRunner(count ,got,nogot),"ConnectionRunnerThread");
thread.start();
}
start.countDown();
end.await();//main线程等待,直到end降为0.
System.out.println("total invoke: "+(threadCount*count));
System.out.println("got connection: "+got);
System.out.println("not got connection:"+nogot);
}
static class ConnectionRunner implements Runnable{
int count;
AtomicInteger got;
AtomicInteger nogot;
public ConnectionRunner(int count, AtomicInteger got, AtomicInteger nogot) {
this.count = count;
this.got = got;
this.nogot = nogot;
}
@Override
public void run() {
try {
start.await();
}catch (InterruptedException e) {
}
while (count > 0){
try {
Connection connection = pool.fetchConnection(1000);
if(connection!=null){
try {
connection.createStatement();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}finally {
pool.releaseConnection(connection);
got.incrementAndGet();
}
}else{
nogot.incrementAndGet();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
count--;
}
}
end.countDown();
}
}
}