java - 在并发的情况下,程序事务和数据库事务是怎么运行的?
高洛峰
高洛峰 2017-04-18 09:17:48
0
3
270
@Transactional
public void selectAndUpdate() {
    status = select ... for update;
    if(status!="初始值") {
        return;
    }
    
    //逻辑开始
    程序逻辑 ...
    举例:用户支付
    1.生成用户签名
    2.发起用户支付到第三方
    //逻辑结束
    
    update status语句...
}

如果利用这种方式来控制并发会有什么问题?另外我还想问大家的是:多个线程的话,会不会导致当一个线程执行到程序逻辑那块的时候,资源被另一个线程抢去的可能?导致另一个线程进入这个方法,发现状态还是没有被改变,然后又进入程序逻辑这块,导致两个线程都执行了一遍吗?数据库的一个事务没有完成的话,会让另外一个线程的事务进入吗?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
小葫芦

for update的缺点@Hisoka已经说了,for update除了会阻塞其它线程以外,加锁的过程对数据库的性能损耗也是很大的。
所以推荐使用乐观锁来解决,因为程序逻辑这块都是在内存中操作不涉及原始的数据,所以只需要在update statusStatement...just use optimistic locking to control the state

迷茫

This method uses pessimistic locking to achieve concurrency control. The bottleneck lies in performance. In addition, if for update does not bring nowait, the thread waiting will not fail quickly. After adding the lock, it will not be snatched by other threads. In addition, transactions have isolation level and propagation behavior configurations. Different settings have different results. It is recommended to find information to understand first

Ty80

for update is used to solve the problem of high concurrency scenarios and is implemented using a distributed lock mechanism. When the first for update statement is executed, subsequent sql statements will sleep and wait until the first sql statement commit is successfully executed and submitted before going back to execute the next statement.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template