Java 静态变量更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13511389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:02:55  来源:igfitidea点击:

Java static variable updates

javastaticstatic-members

提问by jQguru

Below you can see a static variable counterin a Java class.

您可以在下面看到counterJava 类中的静态变量。

The question is when will this variable reset? For example, when I restart the program, computer. What are the other possible scenarios it can reset?

问题是这个变量什么时候会重置?例如,当我重新启动程序时,计算机。它可以重置的其他可能场景是什么?

Another question is: what could be the reasons for this variable to increase by less than the number of times the function do() is executed? For example, could it be something with starting multiple processes of the class java Whatever? Or could it be something with multiple threads/servers, etc?

另一个问题是:这个变量增加少于函数 do() 执行次数的原因是什么?例如,是否可以启动类的多个进程java Whatever?或者它可能是具有多个线程/服务器等的东西?

class Whatever {

    static int counter = 0;

    function do() {
        counter++;
        //...
    }

}

Additional question: If multiple threads execute function do(), how will the counter variable behave? It will be less than the number of times function do() was executed?

附加问题:如果多个线程执行函数 do(),计数器变量将如何表现?它会小于函数 do() 的执行次数吗?

回答by Philipp

A static variable will be re-initialized when you restart the application.

重新启动应用程序时,将重新初始化静态变量。

回答by Jatin

According to the JLS:

根据JLS

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized

如果一个字段被声明为静态,则该字段只存在一个化身,无论最终创建了多少类的实例(可能为零)。静态字段,有时称为类变量,在类初始化时体现

So this answers your first question. i.e.e exactly when the class is loaded :)

所以这回答了你的第一个问题。iee 正是在加载类时:)

As per second question, nope. if the variable is declared private. Then the only access is via the method because of encapsulation.

根据第二个问题,不。如果变量被声明为私有。那么唯一的访问是通过该方法,因为封装。

Static variables lasts till the JVM is shutdown.

静态变量持续到 JVM 关闭。

回答by PC.

counteris not a private variable. So it is possible that this value is changed by some other class.

counter不是私有变量。所以这个值有可能被其他一些类改变了。

This variable will get reset whenever your program (or specifically the container/jvm) is restated.

每当您的程序(或特别是容器/jvm)重新启动时,此变量都会被重置。

回答by Nandkumar Tekale

The question is when will this variable reset?

问题是这个变量什么时候会重置?

static variable can be reset using custom reset()method. If You say restart program, theoretically that variable will be initialized to it's value not reinitialized as it is not same(you restart program).

静态变量可以使用自定义reset()方法重置。如果您说重新启动程序,理论上该变量将被初始化为它的值而不是重新初始化,因为它不相同(您重新启动程序)。

回答by jlordo

class Foo { // in same package
public static void main(String[] args) {
    Whatever w = new Whatever();
    for (int i = 0; i < 1000; i++) {
        w.do();
    }
    Whatever.counter = -1;
}

here do()is invoked 1000 times, but counterwill have value at the end.

这里do()被调用了 1000 次,但counter最终会有价值。

I used do()like you in your example, but note that is nota valid method name, because it's the keyword for a do while loop.

do()在你的例子中像你一样使用,但请注意,这不是一个有效的方法名称,因为它是 do while 循环的关键字。

回答by Jo?o Sim?es

A static variable means that there are only one incarnation of that field during a program execution. It is loaded when the class is initialized.

静态变量意味着在程序执行期间该字段只有一个化身。它在类初始化时加载。

For your second question, your variable isn't thread safe because multiple threads can access it at the same time. Even if your counter was volatile you would still face concurrency problem. You have three options, given your example and requirements:

对于您的第二个问题,您的变量不是线程安全的,因为多个线程可以同时访问它。即使您的计数器不稳定,您仍然会面临并发问题。根据您的示例和要求,您有三个选择:

If your only requirement is to manipulate the variable and the rest of the code won't depend of that you can use synchronize (killing a fly with a cannon) or AtomicInteger(the choice with better performance):

如果您唯一的要求是操作变量而其余代码不依赖于此,您可以使用同步(用大炮杀死苍蝇)或AtomicInteger(性能更好的选择):

static synchronize int counter = 0;
// or
static AtomicInteger counter = new AtomicInteger();

If the rest of your code is dependent of your counter, you must use a lock object or synchronize your method:

如果您的其余代码依赖于您的计数器,则您必须使用锁定对象或同步您的方法:

class Whatever {

    static int counter = 0;

    synchronize function do() {
        counter++;
        if(counter < 10){
            //  do something
        }
    }
}

//  or

class Whatever {

    static int counter = 0;
    static final Object _lock = new Object();

    function do() {
        synchronized (_lock) {
            counter++;
            if(counter < 10){
                //  do something
            }
        }
    }
}

This are the options that are in my head right now, but probably there are more.

这是我现在脑子里的选项,但可能还有更多。

回答by SJuan76

1) The variable is set(reset) when the class is loaded. Apart from shutting down the JVM, some servers load the class in different applications (v.g., the Tomcat webapps) and some of them allow restarting them.

1) 加载类时设置(重置)变量。除了关闭 JVM 之外,一些服务器在不同的应用程序(vg、Tomcat webapps)中加载类,其中一些允许重新启动它们。

2) Concurrent modification by threads. But it should be rare, unless you use it a lot. Use synchronizedfor the function/block.

2) 线程并发修改。但它应该很少见,除非你经常使用它。使用synchronized该函数/块。