简体   繁体   English

如何在数据库级别实现线程安全计数器?

[英]How to implement a thread-safe counter at database level?

I have a table named "stats" which has only one row for statistics.我有一个名为“stats”的表,它只有一行用于统计。 I want to update "totalProductCount" column of this table when a new product registered.(Increase totalProductCount by one when a new product is registered)我想在注册新产品时更新此表的“totalProductCount”列。(注册新产品时将 totalProductCount 增加一)

Problem is my application's register module is multithreaded and I think race condition is occured when I call this method from different threads.问题是我的应用程序的注册模块是多线程的,我认为当我从不同的线程调用这个方法时会发生竞争条件。 Is there any way to increase a column value from different threads?有什么办法可以增加来自不同线程的列值吗?

public void increaseProductCount(long reqId) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    Query query = em.createNativeQuery("update stats set total_product_count = total_product_count + 1 where id = 1");
    query.executeUpdate();

    transaction.commit();
}

Have you actually encountered instances of the race condition?你真的遇到过竞争条件的例子吗?

All UPDATE statements are atomic and acquire write locks on the updated data.所有UPDATE语句都是原子的,并且获取更新数据的写锁。 As long as you're using at least READ COMMITED isolation level (which you would be ill advised not to anyway), you should be fine.只要您至少使用READ COMMITED隔离级别(无论如何都不建议您不READ COMMITED ),您应该没问题。

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

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