Advantage of using static variables in Java

2019-01-25 22:14发布

Say I have two classes like this:

class A{  
    private static Random random = new Random();  

    public A(){  
        // Do something.
    }

    public Integer methodGetsCalledQuiteOften(){
        return random.nextInt();
    }
}

class B{  
     private Random random;  

     public A(){  
         random = new Random();
         // Do something.
     }

     public Integer methodGetsCalledQuiteOften(){
         return random.nextInt();
     }
}

In a scenario where both of them get instantiated multiple times and both of these classes' instances' method methodGetsCalledQuiteOften gets called a lot, is there any real advantage/disadvantage (time, memory) in using a static variable that holds Random() in class A as opposed to creating a new Random() object in every single instance, like in class B?

The application is multithreaded and higher level of randomness is so I think I am going with static SecureRandom. If that will be a real speed factor after profiling I might choose something else.

10条回答
一纸荒年 Trace。
2楼-- · 2019-01-25 22:43

In terms of time and memory I can't think of any big advantages (the static variable will be part of the class definition rather than on the heap). However static variables are useful when you know there will be accesses to the object from multiple places. hvgotcodes is right though that using static resources is not thread-safe. But if your only reading the static value then using threads for it is fine.

It'll save you from having to pass references to the initiated object (A or B) into other object in order to use random

查看更多
爷的心禁止访问
3楼-- · 2019-01-25 22:48

Just say no to mutable static, m'kay.

It's atrocious design. The usual quoted consequence is that testability fails. It will be difficult to reproduce without reloading the class. Bad design is also bad for many other reasons. Just to mention one, classes should, by default, be thread-agnostic. Add a mutable static and you are thread-hostile - a bad place to be.

Creating a new instance every time seems wasteful. Although, of course, don't optimise prematurely (if you were optimising, you wouldn't be using java.util.Random). The initial see incrementing might also cause issues.

The best approach is to pass in an instance ("Parameterise from Above" or "using constructors correctly"). Then you can test, reproduce, mock, etc. You are efficient and can flip in a different implementation.

查看更多
聊天终结者
4楼-- · 2019-01-25 22:48

If your program is single-threaded, your Random should be a class member (static). This is a bit more efficient. It is even more important when using a SecureRandom, which can take a relatively long time to seed initially.

If multiple threads will end up calling methodGetsCalledQuiteOften(), the issue is a bit more complicated. The class is thread-safe, but the overhead required to protect its state during concurrent changes might be comparable to making new, independent instances of Random.

I'd probably stick with a static member until I noticed a lot of contention among threads for the random number generator, which is likely to never happen.

查看更多
戒情不戒烟
5楼-- · 2019-01-25 22:48

If you are using java.util.Random, note that it is a linear congruential generator with well known problems related to correlation. To me, the real question is whether the application should choose from a single series or from several having different seeds.

查看更多
欢心
6楼-- · 2019-01-25 22:55

Use a static variable when the instance isn't expected to change or when you want to share it between instances.

private final static int SOME_CONSTANT=1;

is an example.

public class USA {
    private final static Map statesOfTheUnion = new HashMap();
    // etc
}

could be another. In the latter case, we don't expect that the states will change from instance to instance. Thus is makes no sense for each instance to have its own copy.

查看更多
爷、活的狠高调
7楼-- · 2019-01-25 23:01

Benefits of static variables (main points):

  1. Constants can be defined without taking additional memory (one for each class).

  2. Constants can be accessed without an instantiation of the class.

Benefits of static methods:

Instance-independent behavior can be defined without fear of accidental interaction with an instance of the class.

查看更多
登录 后发表回答