The advantage of using static variables in Java

Let's say I have two classes:

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 in which both of them get an instance several times, and the method method of the instances of these classes methodGetsCalledQuiteOftengets a lot of calls, is there any real advantage / disadvantage (time, memory) when using a static variable that runs Random()in class A as opposed to creating a new object Random()in each individual instance, for example, in class B?

The application is multi-threaded and has a higher level of randomness, so I think I'm going with static SecureRandom. If this is a real speed factor after profiling, I could choose something else.

+3
10

/ . , , B , , .. , .

, B? . , , . , B? , , , , A/B .

, . Random, , , Random. ... , A, , B.

+6

"" , m'kay.

. , . . . , , , -. , - - .

. , , ( , java.util.Random). see incrementing .

- ( " " " " ). , , .. .

+5

, Random (static). . SecureRandom, .

methodGetsCalledQuiteOften(), . , , , Random.

, , static, , , , .

+3

, .

private final static int SOME_CONSTANT=1;

.

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

. , . , .

+2

A (10x) , B, , 100 000 .

, , .nextInt() .next(), . .

, . A , B "" ( !). Javadoc :

Random , , .

, , Random Random java.security.SecureRandom.

+2

. / .

+1

, Random , .

AtomicLong (8 ), ( B).

, , .

+1

java.util.Random, , , . , .

+1

( , ). , , . hvgotcodes , . , .

This saves you from having to transfer references to the initiated object (A or B) to another object in order to use random

0
source

Advantages of static variables (highlights):

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

  • Access to constants is possible without instantiating the class.

Advantages of static methods:

Undefined behavior can be defined without fear of accidental interaction with an instance of the class.

-1
source

Source: https://habr.com/ru/post/1767066/


All Articles