[concurrency-interest] Class variables and concurrency

Dawid Kurzyniec dawidk at mathcs.emory.edu
Sat Nov 5 02:56:50 EST 2005


Luís Matta wrote:

> (corrected to)
> class Foo {
>    //speed is the priority not code beauty
>    public static String CONST_SQL1 = "select * from a where b = ";
>    //reentrant code
>    public static String getA(String param) {
>       String CONST_SQL = CONST_SQL1 + param;
>        ...run query and return result
>    }
> }

Make CONST_SQL1 final (and perhaps private), rename CONST_SQL to 
something more sensible (e.g. query), remove the comment about speed, 
and you're fine. Final fields and local variables are thread-safe (do 
not need synchronization).

>    Since this method can be run by multiple threads, and we are using 
> class variables, this is a theoretical bug. 

There is no such thing as theoretical bug. Especially when concurrency 
is involved.

>
> PS: This will run on a powerfull machine (I just know it is new and 
> runs solaris) ontop of websphere.
> PS2: I know that caching is system dependent and not especified, but I 
> am interest in the pratical side of things
>
It is very dangerous to take concurrency so lightly. It can cost your 
company a lot of money. The most subtle concurrency bugs usually do not 
appear until the application is deployed and under heavy load [I'm 
shamelessly borrowing from JCiP here]. And that is usually the worst 
possible moment to have a system failure, resulting in your clients or 
your boss wanting to hurt you and your family. It is *crucial* to design 
the code carefully and to code defensively to eliminate concurrency 
problems at the design level. Testing is simply not good enough. Even 
more so because it seems that you are unable to run tests on the target 
machine. Concurrency problems can often go unnoticed on uniprocessor 
developer machines, but come to light on powerful, multiprocessor 
application servers.

Regards,
Dawid Kurzyniec



More information about the Concurrency-interest mailing list