【问题标题】:Best way to make a function that accesses a database table threadsafe? [closed]使访问数据库表线程安全的函数的最佳方法是什么? [关闭]
【发布时间】:2018-10-01 13:34:54
【问题描述】:

基本上就是标题所说的。我们有一些将在同一个函数中读取和更新的关键数据,我们必须确保我们可以避免竞争条件。 @Transactional 注释会解决这个问题吗?

// Both threads call this function
void someMethod() {
    int value = EntityObject.getSomeField();
    int newValue = modifyValue(value);

    // PROBLEM: The other thread read "someField" before the database was  updated, 
    // and we end up with the wrong value when both threads are done

    EntityObject.setSomeField(newValue);
    EntityObjectService.save(EntityObject);
}

我们正在使用 MySQL

【问题讨论】:

标签: java spring hibernate tomcat jpa


【解决方案1】:

@Transactional 注释将帮助您在数据库级别,而不是您的应用程序线程。如果担心旧数据在更新时不应该被其他线程读取,我会使用ReentrantReadWriteLock:

在您的配置之一中定义:

@Bean
public ReentrantReadWriteLock lock(){
    return new ReentrantReadWriteLock();
}

在类中更新时:

@Autowired private ReentrantReadWriteLock lock;

public void someMethod() {

    try {
        lock.writeLock().lock();

        // Do your read & lengthy update here

    } finally {
        lock.writeLock().unlock();
    }   
}

而当其他线程访问只读时:

@Autowired private ReentrantReadWriteLock lock;

public void someMethodThatReads() {

    try {
        lock.readLock().lock();

        // Do your reading here

    } finally {
        lock.readLock().unlock();
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多