class Problematic
{
static int x;
static void method(int x)
{
Problematic.x = x;
}
}
/*
This is problematic (in a multi-threaded environment) because, if two
threads call the method, there is access to
shared data (Problematic.x), and therefore, a race condition exists.
However, the simple generalization that "static methods have race
conditions" is clearly incorrect and is likely the result
of misinterpreting some document.
*/
class Fine
{
static void method(int x)
{
System.out.println(x);
}
}
/*
This is fine to call the method from multiple threads, since the
method-local x is placed on the method call stack
*/
class Problematic
{
static void method(SomeMutableType smt)
{
// change smt
}
}
/*
Again, there is access to (and altering of) shared data (the object referred
to that is passed when the method is called), and thus, a problem exists.
*/
--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
"Silvio Bierman" <sb******@idfix.nl> wrote in message
news:3f*********************@news.xs4all.nl...
"GIMME" <gi*******************@yahoo.com> wrote in message
news:3f**************************@posting.google.c om... One of my coworkers insists that one should never use
static methods because race conditions exist. Thinking
along the lines that all variable assignments are
assignments to static variables.
He's wrong. Right?
Two users in a web session could both access a static
method at the same time and never have any trouble.
Right?
Static or not has nothing to do with it. Race conditions can only occur in
multithread environments, such as in servlet code where the servlet
container could handle multiple requests through the same object instances
at the same time.
Accessing the same object from multiple threads simultaneously can be a
problem but does not have to be. If for example two threads perform
simultaneous access to an object without changing its state that would be
fine. If they do change the state and the state transition involves
instable intermediate states a problem could arise. To prevent such problems Java
has constructs like the synchronized keyword and wait/notify.
Silvio Bierman