Re: Multi threading - how small is the smallest 'unit' of code
azserrata wrote:
Say:
//CODE1
(...)
sharedVariable ++;
int i = sharedVariabel;
Eric Sosman wrote:
ITYM `sharedVariable', here and in various other spots.
azserrata wrote:
boolean test=(i==sharedVariable);
(...)
If the code is executed in multiple threads, in a non-synchronized
piece of code, it is possible that 'test' might be FALSE.
No, not true, but it is possible that 'test' might be 'false'.
Eric Sosman wrote:
Yes. Even worse, `sharedVariable' might have some completely
bizarre value, because each thread does an unsynchronized read-
modify-write on it.
azserrata wrote:
What about these, all non-synchronized.
The operative term is "all non-synchronized". This means all are
thread-unsafe and all have unpredictable outcomes.
azserrata wrote:
Eric Sosman wrote:
Same problem.
azserrata wrote:
Eric Sosman wrote:
Same problem.
azserrata wrote:
Eric Sosman wrote:
Same problem.
azserrata wrote:
Is it possible to guarantee that == is implemented (internally) as a
unique, indivisible, instruction?
Eric Sosman wrote:
The Java language has no such guarantee, since "instruction" is not
part of the definition of Java. The `volatile' qualifier may help with
what you need, but not with what you actually asked.
azserrata wrote:
Or is it possible that other thread might do its increment
(sharedVariable++) somewhere in-between and this thread's 'test' ==
FALSE [sic]?
It's possible that the other does part of its increment operation and not all
of it, as seen by the current thread. Auto-increment is not atomic.
Eric Sosman wrote:
Yes. And without synchronization (or `volatile'), there's no
telling when the other thread's modification might become visible
to this thread.
...
What problem are you trying to solve? There's probably a way
to solve it without taking so many risks.
In the meantime, buy, read and study /Java Concurrency in Practice/ by Brian
Goetz, et al. There are also good multi-threading tips in /Effective Java/ by
Joshua Bloch. The IBM Developerworks site (for Java) has many excellent
articles on concurrent Java programming available for free. Study first, act
second.
Also the Java Language Specification (JLS) describes the so-called Java
"memory model", which uses the concept of /happens-before/ to empower
reasoning about the outcome of concurrent operations. Without appropriate
synchronization ('synchronized', 'volatile', a concurrent data structure,
'Lock' classes or other mechanisms) you cannot draw any safe conclusions about
inter-thread visibility.
In particular, beware the dreaded "double-lock" broken idiom.
--
Lew
Ceci n'est pas une pipe.