[concurrency-interest] Class variables and concurrency

David Holmes dholmes at dltech.com.au
Sun Nov 6 20:02:04 EST 2005

Not withstanding Dawid's responses I'd just like to address a couple of

Luís Matta writes:
> (Obvious buggy)
> class Foo {
>     public static String CONST_SQL;
>     public static String CONST_SQL1 = "select * from a where b = ";
>     public static String getA(String param) {
>        CONST_SQL = CONST_SQL1 + param;
>         ...run query and return result
>     }
> }
> ...
>     Since this method can be run by multiple threads, and we are using
> class variables, this is a theoretical bug. But is it a actual one, is
> there a pratical situation where this bug will manifest itself?
>     I ask because since the variable is not synchronized, it appears to
> me that it will get cached and will never be refreshed in any pratical
> situation.

It would be possible for the value written to CONST_SQL to be maintained as
a local or on the stack and so if a second thread changed CONST_SQL the
first thread need not notice it. But it is just as possible that the static
field will be reloaded when used to run the actual query - in which case it
could see someone else's value for CONST_SQL and so execute the wrong query.

There are many factors at play here including the source code compiler, and
the JIT. Bottom line is this code has a serious bug.

> What are the rules for concurrent access to class variables, and what
> how would the Sun JVM (version 1.4.3) behave?

The rules for accessing statics is no different to accessing instance
fields. The source compiler will issue as many or as few GETSTATIC/PUTSTATIC
bytecodes as is needed to implement the program semantics and required by
the specification. Source code compilers tend to make very conservative
assumptions about what might happen in method calls so it is likely that use
of a static field before and after a method call would result in two
GETSTATIC uses. The JIT will again do whatever it needs to implement the
program semantics but this time with more of a view on performance and
optimization. That may or may not require that the GETSTATIC bytecodes
remain as explicit loads from memory - it depends on what analysis the
compiler does of any methods called in between the accesses.

Bottom line: don't think about these things as you have no idea what will
occur at runtime. Write the code correctly as per the language

David Holmes

More information about the Concurrency-interest mailing list