Re: visibility on array elements
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx>
- Date: Wed, 31 Dec 2008 11:01:17 -0500
neuneudr@xxxxxxxx wrote:
Hi,
imagine that for whatever reason I decide *not* to use an
AtomicLongArray and go with a long[] (the reason is
actually that I want to understand what's going on).
public static final long[] ref = new long[42];
Do the following guarantee the correct visibility
when accessing the elements of the array :
From one thread :
synchronized (ref) {
ref[0] = 3;
}
and from another thread, later :
synchronized (ref) {
long val = ref[0]; // Am I guaranteed to get back '3'
here ?
}
Yes, you'll get 3L (assuming nothing else has disturbed
ref[0] in the meantime).
Basically my question is : seen that array elements cannot
be declared volatile *and* that I want to use arrays, how
should I proceed if I want thread-safe behavior when
modifying/reading my array ?
You can synchronize all accesses on the array itself, as
above, in which case no accesses will overlap and modifications
made by any thread will be visible to all others. Note that
this may create more contention than if you could somehow
synchronize on the individual elements, because it prohibits
simultaneous access to ref[0] and ref[1].
Using synchronized access (or volatile) does not in and of
itself guarantee "thread-safe behavior." A classic example is
Vector<String> v = new Vector<String>();
...
if (! v.isEmpty()) {
String s = v.remove(0);
...
This fragment is not thread-safe, even though the individual
..isEmpty() and .remove() methods are synchronized and hence
thread-safe insofar as their own operations are concerned.
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.
- Follow-Ups:
- Re: visibility on array elements
- From: neuneudr
- Re: visibility on array elements
- References:
- visibility on array elements
- From: neuneudr
- visibility on array elements
- Prev by Date: Re: HTML Correctness and Validators
- Next by Date: Re: A question related to type casting
- Previous by thread: Re: visibility on array elements
- Next by thread: Re: visibility on array elements
- Index(es):
Relevant Pages
|