简体   繁体   English

Java:如何同步对数据库的访问?

[英]java: How to synchronize access to db?

I parse some stuff from a several urls and insert data in database. 我从几个URL解析一些东西,然后在数据库中插入数据。 I want to do this now in parallel. 我现在想并行执行此操作。 I create a thread pool and run links in separate threads. 我创建一个线程池并在单独的线程中运行链接。 But it isn't safe. 但这并不安全。 I decided synchronized method that get data from web and save it to database like this: 我决定从网络获取数据并将其保存到数据库的同步方法,如下所示:

            synchronized (this) {
                Parser parser = new Parser(link);
                feeds = parser.parse();
                model.insertFeeds(feeds, link);
            }

But this approach blocked access to web and database for other threads until current thread parse data and insert (this is 99% of his work), so it seems that they are perform more than one by one, not as a parallel. 但是这种方法阻止了其他线程访问Web和数据库,直到当前线程解析数据并插入为止(这是他工作的99%),因此似乎它们在执行一项以上的任务,而不是并行执行。

Could you tell what is the better solution for things like this? 您能告诉我什么是更好的解决方案吗?

您应该让数据库为您处理并发性,以及通过JDBC事务隔离级别进行控制的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM