Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local caching of Java constants

Tags:

java

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?

like image 832
DJClayworth Avatar asked Jul 02 '10 16:07

DJClayworth


People also ask

What is caching in Java?

The Java Object Cache provides caching for expensive or frequently used Java objects when the application servers use a Java program to supply their content. Cached Java objects can contain generated pages or can provide support objects within the program to assist in creating new content.

What are the constants in Java?

A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants. A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.

How are constants declared in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.


2 Answers

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

like image 99
Nulldevice Avatar answered Oct 20 '22 18:10

Nulldevice


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;
}
like image 29
MeBigFatGuy Avatar answered Oct 20 '22 18:10

MeBigFatGuy