Re: JavaMemoryModel: Re: SoftReference not thread-safe ?

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Wed Jan 19 2005 - 17:47:28 EST


Hanson Char wrote:
> Is it true that
>
> 1) the value of "clock" is set by the Garbage Collector,
> 2) so we can assume that this is a stop-the-world event, i.e. only the
> GC runs, and no-one else.
> 3) If we then have several threads that concurrently call get() then
> they should all be set to the same value ?
>
> H
>

Oops! I misunderstood your question. I thought you were asking about
some code of yours.

In some sense, this isn't "pure" Java, as the VM is responsible for
updating the clock variable. There is no provision in the memory model
for actions taken by the garbage collector that aren't related to
objects that are being collected / finalized / declared unreachable. It
is stated that Soft/Weak references have to obey their API.

If you are worried about the value clock might contain, you therefore
have to talk to the people who implemented the SoftReference part of the
GC. Depending on which VM you are running, some of them may be lurking
around.

In practice, every time get() is called between two GCs, it will assign
the same value to this.timestamp, because GCs tend to do a global memory
barrier.

It does become a little tricky with respect to setting this.timestamp.
Imagine what would happen if a stop-the-world GC occurred between when
the value of clock was retrieved and when this.timestamp was set. Then,
this.timestamp would get the old value. The people who write this code
should work with the GC to prevent this, of course.

Finally, let me rephrase my earlier response to your question. If a
thread reads this.timestamp without synchronization, there is nothing in
the memory model that will prevent it from seeing an earlier value. So,
for example:

Thread 1: Thread 2:
                                r1 = this.timestamp;
(GC occurs here)
this.timestamp = clock
                                r2 = this.timestamp;

Thread 2 is free to perform redundant read elimination and reuse the
value it saw for r1. However, Java code doesn't read this.timestamp
(AFAIK), so it isn't really a problem.

The long and short of it is that this is something that needs to be
dealt with in the internals of your VM / collector.

                                        Jeremy
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:01:09 EDT