静态方法中变量的竞争条件 [英] Race condition in variable in a static method

查看:61
本文介绍了静态方法中变量的竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法如下:

public static void method() {

int i = 0;
i = i + 1;

}

我在静态方法中有一个 int 变量.并且该方法被多个线程访问.
我的问题是:

I have an int variable inside a static method. And the method is accessed by several Threads.
My questions are:

  1. i 变量是否进入竞争条件?
  2. 如果spring web应用中访问的方法被多个用户同时访问怎么办?
  1. Does the i variable go to race condition?
  2. What if the method accessed in spring web application and accessed by multiple users at a same time?

推荐答案

如果变量是在方法中声明的,那么它就存在于为该方法的单个调用提供的堆栈帧中.堆栈帧只能由调用该方法的线程访问.在发布的示例中没有竞争条件,该方法的每次调用都会获得它自己的变量副本.您需要共享状态才能获得竞争条件.

If the variable is declared within the method, then it lives in the stackframe provided for a single invocation of the method. The stackframe is accessed only by the thread invoking the method. There is no race condition in the posted example, every invocation of the method gets its own copy of the variable. You need shared state in order to have a race condition.

这些堆栈帧是执行递归方法时堆积起来的东西,它们会占用堆栈空间,直到某个时刻系统空间用完并发生堆栈溢出错误,因为递归导致越来越多的堆栈帧被分配,而没有一个方法调用有机会完成(这将释放它们的堆栈空间).

These stackframes are the things that pile up when executing a recursive method, and take up stack space until at some point the system runs out of space and a stackoverflow error occurs, because the recursion results in more and more stackframes getting allocated, while none of the method calls get a chance to complete (which would free up their stack space).

这篇关于静态方法中变量的竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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