DJClayworth
DJClayworth

Reputation: 26876

Local caching of Java constants

Let's say I have a Java app which uses a (static) int constant from a library:

int myval = OutsideLibraryClass.CONSTANT_INT;

Now, without recompiling my app, I run it against a slightly different version of OutsideLibraryClass, in which the value of CONSTANT_INT is different.

Is my app going to see the new value (because it picks it up at runtime) or the old (because the value is compiled into the bytecode in my method)? Does it make any difference if CONSTANT_INT is final? Is there a part of the Java spec that talks about this?

Upvotes: 5

Views: 1243

Answers (4)

MeBigFatGuy
MeBigFatGuy

Reputation: 28598

Unfortunately your question is not specific enough to answer the question, because it may or may not change without recompiling. Here's an example where the constant value will change with out recompiling.

public class Const {
   public static final int CONSTANT;
   static {
      CONSTANT = 4;
   }
}

class Test
{
   int c = Const.CONSTANT;
}

And here's a case where it will not change without recompiling

public class Const {
   public static final int CONSTANT = 4;
}

class Test
{
   int c = Const.CONSTANT;
}

Upvotes: 2

chrislatimer
chrislatimer

Reputation: 3560

From the JVM spec:

A class variable is a field of a class type declared using the keyword static (§2.9.1) within a class declaration, or with or without the keyword static in an interface declaration. Class variables are created when the class or interface is loaded (§2.17.2) and are initialized on creation to default values (§2.5.1). The class variable effectively ceases to exist when its class or interface is unloaded (§2.17.8).

So when the OutsideLibraryClass is loaded by the ClassLoader, the value gets initialized. When you perform your assignment statement on myVal, the value is loaded at runtime based on the OutsideLibraryClass class file that was loaded by the ClassLoader. So if you shut down the JVM, swap the jar file that contains OutsideLibraryClass and run it again, it will get the value from the new class.

UPDATE

The above statement is true if you're talking about an instance a local variable within a method. If your myVal variable is declared at the class level then the people saying it will not change are correct.

Upvotes: 1

Yishai
Yishai

Reputation: 91921

No it will not pick up the new value. This is part of the language spec. See this question.

Upvotes: 1

Nulldevice
Nulldevice

Reputation: 4006

References to constant fields are resolved at compile time to the constant values they denote. (JLS 13.1)

Upvotes: 4

Related Questions