比赛条件“check-then-act”和“读 - 修改 - 写”和“读 - 修改 - 写” [英] Race conditions "check-then-act" and "read-modify-write"

查看:663
本文介绍了比赛条件“check-then-act”和“读 - 修改 - 写”和“读 - 修改 - 写”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我解释什么是竞争条件,如何避免它,以及如何在java代码中找到它?

Anyone can explain me about what is race condition, how to avoid it, and how to find it out in java codes?

好的,我只知道种族条件几天,我有两个例子,也许它们不够好,这就是为什么我需要你的帮助:)希望你们中的任何人都可以为我解释。

Okay, I just know "race condition" several days, I have two examples, maybe they are not good enough, that's why I need your help:) Hope any of you can explain it for me.

example1:
check then act:

example1: check then act:

if(vector.contains(e))//check
{
vector.remove(e)
}

如果有2个主题可以访问,thread1在检查向量包含e后挂起,e在向量中挂起,然后thread2访问检查然后从向量中删除e,然后thread1返回并执行删除操作,将发生错误,因为e已经被thread2删除。

if there are 2 threads can access, thread1 suspends after check vector contains e, and e does in vector, then thread2 access to check and then remove e from vector, then thread1 comes back and do remove action, error will occur, because e is already removed by thread2.

example2:
读取修改写:

example2: read modify write:

假设我们在方法中有一个计数器变量,一旦调用该方法,计数器增加1,

assume we have a counter variable in a method, once the method is called, counter increase 1,

counter++

这不是原子ic操作,它有3个步骤:
1.获得价值
2.增加价值
3.分配价值

this is not a atomic operation, it has 3 steps: 1. get the value 2. increase the value 3. assign to the value

我对种族状况的了解就在这里,希望你能与我分享你的知识:)

What I know about race condition is all here, hope you can share your knowledge with me:)

谢谢

推荐答案

什么是竞争条件?
检查此堆栈溢出问题

竞争条件主要有两种情况:read-modify-write和check-then-act。

There are primarily two scenarios for race-condition: read-modify-write and check-then-act.

对于读取 - 修改 - 写经典的例子是 counter ++ 这不是原子操作,因此导致竞争条件。

For read-modify-write classical example is of counter++ which is not an atomic operation so leads to race condition.

用于检查 - 然后-act有多个例子。一个例子是当你在ConcurrentHashMap中检查密钥存在然后在if-case中做一些工作。另一个例子是单例类代码:

For check-then-act there are multiple examples. One example is when you check for key existence in ConcurrentHashMap and then do some work in if-case. Another example is singleton class code:

public Singleton getInstance()
{
   if(_instance == null)
   { 
      _instance = new Singleton();
   }
}

您可以在互联网上阅读更多相关信息。关于并发性的一本好书是Brian Goetz的Java Concurrency in Practice。您还可以找到有用的文章

You can read more about them on internet. One good book on concurrency is Java Concurrency in Practice by Brian Goetz. You can also find this article helpful.

这篇关于比赛条件“check-then-act”和“读 - 修改 - 写”和“读 - 修改 - 写”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆