享元模式-实现数据库线程池

类图

概述

简易的数据库连接池,使用享元、装饰器等设计模式。使用cas和aqs等技术使得线程安全。

自定义连接对象

//使用装饰器扩展连接对象
public class ConnectionDecorator implements Connection {

    private Connection connection;
    //状态 0代表可使用 1代表不可使用
    private AtomicInteger state;

    public ConnectionDecorator(Connection connection) {
        this.connection = connection;
        state = new AtomicInteger(0);
    }

    public Connection getConnection() {
        return connection;
    }

    public AtomicInteger getState() {
        return state;
    }

    @Override
    public Statement createStatement() throws SQLException {
        return connection.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return connection.prepareCall(sql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return connection.nativeSQL(sql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        connection.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return connection.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException {
        connection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        connection.rollback();
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return connection.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return connection.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        connection.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return connection.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        connection.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException {
        return connection.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        connection.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return connection.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return connection.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return null;
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {

    }

    @Override
    public void setHoldability(int holdability) throws SQLException {

    }

    @Override
    public int getHoldability() throws SQLException {
        return 0;
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return null;
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return null;
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {

    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return null;
    }

    @Override
    public Clob createClob() throws SQLException {
        return null;
    }

    @Override
    public Blob createBlob() throws SQLException {
        return null;
    }

    @Override
    public NClob createNClob() throws SQLException {
        return null;
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return null;
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return false;
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {

    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {

    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return null;
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return null;
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return null;
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return null;
    }

    @Override
    public void setSchema(String schema) throws SQLException {

    }

    @Override
    public String getSchema() throws SQLException {
        return null;
    }

    @Override
    public void abort(Executor executor) throws SQLException {

    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {

    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return 0;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}

线程池接口

public interface ConnectionPool {
    /**
     * 获取连接
     * @return
     */
    Connection getConnection();

    /**
     * 归还连接
     * @param connection
     */
    void giveBackConnection(Connection connection);

}

使用synchronized实现池中没有可用连接进行等待

public class ConnectionPoolImpl1 implements ConnectionPool{

    private Connection[] connections;

    private String username;

    private String password;

    private String url;
    private int capacity;

    public ConnectionPoolImpl1(String username, String password, String url, int capacity) throws SQLException {
        this.capacity = capacity;
        connections = new Connection[capacity];
        for (int i = 0; i < capacity; i++) {
            connections[i] = new ConnectionDecorator(DBUtil.getConnection(url, username, password));
        }
    }

    public Connection getConnection() {
        while (true) {
            for (int i = 0; i < connections.length; i++) {
                ConnectionDecorator connection = (ConnectionDecorator) connections[i];
                AtomicInteger state = connection.getState();
                if (state.compareAndSet(0, 1)) {
                    return connection;
                }
            }
            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void giveBackConnection(Connection connection){
        for (int i = 0; i < connections.length; i++) {
            if(connection == connections[i]){
                ConnectionDecorator connectionCast = (ConnectionDecorator)connection;
                AtomicInteger state = connectionCast.getState();
                state.set(0);
                //唤醒等待线程
                synchronized (this){
                    notify();
                }
                return;
            }
        }
        throw new RuntimeException("此连接不是本线程池中的连接");
    }

使用Semaphore实现线程池中没有可用连接进行等待

public class ConnectionPoolImpl2 implements ConnectionPool {

    private Connection[] connections;

    private String username;

    private String password;

    private String url;
    private int capacity;

    private Semaphore semaphore;

    public ConnectionPoolImpl2(String username, String password, String url, int capacity) throws SQLException {
        this.capacity = capacity;
        connections = new Connection[capacity];
        for (int i = 0; i < capacity; i++) {
            connections[i] = new ConnectionDecorator(DBUtil.getConnection(url, username, password));
        }
        semaphore = new Semaphore(capacity);
    }

    @Override
    public Connection getConnection() {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < connections.length; i++) {
            ConnectionDecorator connection = (ConnectionDecorator) connections[i];
            AtomicInteger state = connection.getState();
            if (state.compareAndSet(0, 1)) {
                return connection;
            }
        }
        return null;
    }

    @Override
    public void giveBackConnection(Connection connection) {
        for (int i = 0; i < connections.length; i++) {
            if (connection == connections[i]) {
                ConnectionDecorator connectionCast = (ConnectionDecorator) connection;
                AtomicInteger state = connectionCast.getState();
                state.set(0);
                semaphore.release();
                return;
            }
        }
        throw new RuntimeException("此连接不是本线程池中的连接");
    }


}

数据库工具类

public class DBUtil {

    private static String username;

    private static String password;

    private static String url;

    static {
        try {
            Driver driver = (Driver) Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            DriverManager.registerDriver(driver);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static Connection getConnection(String url, String username, String password) throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static void closeConnection(Connection connection) throws SQLException {
        if (Objects.nonNull(connection)) connection.close();
    }

}

客户端测试类

public class Client {
    public static void main(String[] args) throws SQLException {

        ConnectionPool connectionPoolImpl2 = new ConnectionPoolImpl2(
                "root",
                "root",
                "jdbc:mysql://localhost:3306/template?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8",
                2
        );

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    Connection connection = connectionPoolImpl2.getConnection();
                    System.out.println(Thread.currentThread().getName()+"--获取到连接:"+connection);
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+"--归还:"+connection);
                    connectionPoolImpl2.giveBackConnection(connection);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"t"+(i+1)).start();
        }

    }

    public void test1() throws SQLException {
        ConnectionPool connectionPoolImpl1 = new ConnectionPoolImpl1(
                "root",
                "root",
                "jdbc:mysql://localhost:3306/template?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8",
                2
        );


        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    Connection connection = connectionPoolImpl1.getConnection();
                    System.out.println(Thread.currentThread().getName()+"--获取到连接:"+connection);
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+"--归还:"+connection);
                    connectionPoolImpl1.giveBackConnection(connection);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"t"+(i+1)).start();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值