简体   繁体   中英

Storing a value for all the instances of a given class

I have a class called Foo which in some of its methods relies on a value globalTime that depends on time. To simplify it let's say it's a long integer storing the number of seconds since the program started. Now, I want all the instances of Foo to share the exact same value for globalTime . I, of course could create another class which stores the value and make all the instances of Foo retrieve the value for that class but I was just wondering: Is there a way I could do this from within the class?

I'm looking for something like an static field but being able to change its value, although it's stored only once, not once for every instance, and thus every instance from that class would share the same value for that field.

I'm just curious about whether something like this exists in Java, I'm not saying it's a better or worse practice than any other alternative, so please do not discuss the "purpose" of wanting to do this.

As you have already been told to make a static field. The answer is right.

Note these things also to clear it:

  1. static fields are associated with the classes. Creating or destroying objects does not have any impact on static field.
  2. A static field remains for the scope of the class not the object.
  3. static fields are accessed using ClassName.fieldName .

that is why creating object does not have any impact on it.

You should use a static field for that. Value of static fields can very well be changed just as the value of usual fields.

如果在多线程中使用globalTime ,请考虑使用静态AtomicLong ,它将处理同步。

If your value depends on globalTime, use static volatile field as:

public class Foo {
    static volatile long globalTime=System.nanoTime();

}
class B{
    public static void main(String args[]){
        System.out.println(Foo.globalTime);
    }
}

Since volatile fields avoid compiler caching the values which depends on time fields. This SO answer would further help you.

Could have it as a static field wrapped around a thread that just keeps calling System.nanoTime() . I don't see a problem with that. Something like this

    private static long timer = 0;
static {
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                timer = System.nanoTime() - timer;
            }
        }
    }).start();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM