Reputation: 1679
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.
Upvotes: 0
Views: 113
Reputation: 2959
As you have already been told to make a static field. The answer is right.
Note these things also to clear it:
static
fields are associated with the classes. Creating or
destroying objects does not have any impact on static field. static
field remains for the scope of the class not the object.ClassName.fieldName
.that is why creating object does not have any impact on it.
Upvotes: 2
Reputation: 11205
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.
Upvotes: 1
Reputation: 6870
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();
}
Upvotes: 0
Reputation: 7957
If you use globalTime
in a multi-threading consider using a static AtomicLong, that will handle synchronization.
Upvotes: 1
Reputation: 4588
You should use a static field for that. Value of static fields can very well be changed just as the value of usual fields.
Upvotes: 1