为什么我的 ScheduledExecutorService 这样工作?

我的线程程序不起作用,因为我希望它起作用。


首先是我的主类,从那里开始我的线程:


import static java.lang.Thread.currentThread;


public class Main {


public static void main(String[] args) throws IOException, NamingException, ClassNotFoundException {


    Properties property = new Properties();


    property.load(new FileReader(new File(args[0])));


    DataSource ds = DataSource.newInstance(property);

    Class.forName("org.postgresql.Driver");


    ConnectionPool connectionPool = new ConnectionPool();

    System.out.println(currentThread().getName());

    ConnectionPoolManager manager = new ConnectionPoolManager(connectionPool, ds);

    manager.start();


    }


}

这是我的 ConnectionPool 类


package com.telbook.connectionPooling;


import java.sql.Connection;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;


public class ConnectionPool {


private List<PoolObject> poolObjects = new ArrayList<>();


public List<PoolObject> getPoolObjects() {

    return poolObjects;

}


public void setPoolObjects(List<PoolObject> poolObjects) {

    this.poolObjects = poolObjects;

}


public void put(Connection connection) {

    PoolObject poolObject = new PoolObject();

    poolObject.setConnection(connection);

    poolObjects.add(poolObject);

}


public Connection getConnection() throws SQLException {

    for (PoolObject object: poolObjects) {

        if (!object.getInUse() && object.getConnection()!=null) {

            if (!object.getConnection().isClosed()) {

                if (object.getConnection().isValid(50)) {

                    object.setInUse(true);

                    return object.getConnection();

                }

            }

        }

    }


    return null;

}


}


catspeake
浏览 475回答 1
1回答

aluckdog

ArrayList不是线程安全的,调度线程池中的线程可能无法获取最新元素,请尝试使用线程安全版本List:private&nbsp;List<PoolObject>&nbsp;poolObjects&nbsp;=&nbsp;Collections.synchronizedList(new&nbsp;ArrayList<PoolObject>());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java