美文网首页
简单动态代理连接

简单动态代理连接

作者: 会飞的蜗牛66666 | 来源:发表于2019-02-26 15:25 被阅读0次

ConnectionDriver 获取驱动
public class ConnectionDriver {
static class ConnectionHandler implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String commit = "commit";
        if (commit.equals(method.getName())) {
            TimeUnit.MILLISECONDS.sleep(100);
        }
        return null;
    }
}

/**
 * 通过动态代理来获取一个Connection实例,在commit时休眠10秒
 *
 * @return
 */
public static final Connection createConnection() {
    return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(), new Class<?>[]{Connection.class}, new ConnectionHandler());
}

}

简单连接池
public class ConnectionPool {

private LinkedList<Connection> pool = new LinkedList<Connection>();

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();
        }
    }
}

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;
        }
    }
}

}

测试
public class ConnectionPoolTest {

private static ConnectionPool pool = new ConnectionPool(10);
//保证所有ConnectionRunner能同时开始
private static CountDownLatch start = new CountDownLatch(1);
//main线程将会等待所有ConnectionRunner结束后才能继续执行
private static CountDownLatch end;

public static void main(String[] args) {
    //线程数量,可以修改线程数量进行观察
    int threadCount = 10;
    end = new CountDownLatch(threadCount);
    int count = 20;
    AtomicInteger got = new AtomicInteger();
    AtomicInteger notGot = new AtomicInteger();
    for (int i = 0; i < threadCount; i++) {
        final Thread thread = new Thread(new ConnctionRunner(count, got, notGot), "ConnctionRunnerThread");
    }
}

static class ConnctionRunner implements Runnable {

    int count;
    AtomicInteger got;
    AtomicInteger notGot;

    public ConnctionRunner(int count, AtomicInteger got, AtomicInteger notGot) {
        this.count = count;
        this.got = got;
        this.notGot = notGot;
    }

    @Override
    public void run() {
        try {
            start.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (count > 0) {
            try {
                //从线程池中获取连接,如果1000ms内无法获取到,将会返回null
                //分别统计连接获取的数量got和为获取的数量notGot
                final 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 {
                    notGot.incrementAndGet();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                count--;
            }
        }
        end.countDown();
    }
}

}

public class Test2 {
public static void main(String[] args) {
AtomicReferenceArray<String> referenceArray = new AtomicReferenceArray<String>(3);
final String s1 = referenceArray.getAndSet(0, "xiaofei");
System.out.println(s1);
referenceArray.set(1, "jiandong");
final String s2 = referenceArray.get(0);
System.out.println(s2);

    final AtomicInteger atomicInteger = new AtomicInteger();
    final int i1 = atomicInteger.incrementAndGet();
    System.out.println(i1);
    final int i2 = atomicInteger.getAndIncrement();
    System.out.println(i2);
    final int i3 = atomicInteger.intValue();
    System.out.println(i3);
    
}

}

相关文章

网友评论

      本文标题:简单动态代理连接

      本文链接:https://www.haomeiwen.com/subject/fswayqtx.html