跨固定数量的线程共享数据库连接

时间:2014-01-30 09:32:02

标签: java multithreading jdbc thread-safety threadpool

public class Parser {

        ExecutorService pool = Executors.newFixedThreadPool(10);

        public void update() {

            Item item = new Item(subj.getName(), dateBuilder.toString(),
                    cobBuilder.toString(), interest, count);

            pool.submit(new ItemDispatcher(item));
        }



    } 



    public class ItemDispatcher implements Runnable {

        private Item item;

        public ItemDispatcher(Item someItem) {

            this.item = someItem;

        }


        @Override
        public void run() {

            try {
                new Database(item).writeToDb();
            } catch (SQLException e) {
                e.printStackTrace(); 

            }

        }

    }


    public class Database {

        private String name;
        private String date;
        private String cob;
        private String interest;
        private String count;

        private String _url;
        private String _userId;
        private String _password;
        private String _dbLib;
        private String _dbFile;
        private Connection _conn;
        private PreparedStatement _statement;

        public Database(Item item) {

            name = item.get_item();
            date = item.get_date();
            cob = item.get_cob();
            interest = item.get_interest();
            count = item.get_count();
        }


        public void writeToDb() {

            try {

                //statment.setString(); 
            }

            } catch (SQLException e) {
                e.printStackTrace();
            } 

    }

如何创建一个线程安全的数据库连接,而不是每个执行任务的线程初始化一个新连接。我问了一个类似的问题here,但解决方案使用了我不想使用的第三方库。有人可以告诉我一个简单的替代方案吗?

1 个答案:

答案 0 :(得分:0)

创建线程池时创建单个连接

ExecutorService pool = Executors.newFixedThreadPool(10);
final Connection c = DriverManager.getConnection(...)

然后将其传递给您创建的每个ItemDispatcher

new ItemDispatcher(item, c)

让ItemDispatcher将其保存在成员变量中。

最后,您可能需要保护对使用synchronized块的连接的访问​​

synchronized(c) {
    try {
        new Database(item).writeToDb();
    } catch (SQLException e) {
        e.printStackTrace(); 
    }
}