"Lee Fesperman" <> wrote in message
news:...
> Matt Humphrey wrote:
> >
> > "jim" <> wrote in message
> > news:burjl4$ki6$..
> > > Do threads make contention to method varaibles? I remember threads can
make
> > > contention to instance variables. In order to protect instance
variable
> > > integrity, I can use synchronized as a method modifier or use
synchronized
> > > block inside method body. For a method, each thread has a different
> > > allocated memory space. Is this right?
> >
> > Threads have contention for objects, not variables. It doesn't matter
if
> > the object is accessed via its reference in an instance variable or a
local
> > variable. If the object can be accessed from more than one thread,
there
> > can be synchronization problems.
>
> You are incorrect. Aside from external resources, mutable variables
(instance or class,
> but not local) are the only reason for contention/synchronization between
threads. For
> example, there are no contention problems for immutable objects (String,
Integer, ...)
> because they contain no mutable instance variables.
Thanks for pointing out that contention can occur on class variables. I
agree that contention can occur whenever more than one thread accesses a
shared data container (instance or class variable) that can change state.
However, I cite contention on objects because (other than class variables)
it can only happen when there is a shared reference and it doesn't matter
what kinds of variables the references are stored in. I often find that
people confuse the variable and the object and mistakenly believe that by
calling the methods of a typical object via a local or final variable means
the result will be threadsafe. Even calling the methods of an application's
immutable object (one with no mutable instance variables) can cause
contention if those variables ultimately refer to objects that are mutable
and shared.
Given that the goal is to eliminate contention in an application composed of
mutable objects and because objects that are not shared cannot have
contention, I recommend people consider how threads access shared objects.
Cheers,
Matt Humphrey
http://www.iviz.com/