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

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


Hanson,

If multiple threads write to the long this.timestamp concurrently,
without using synchronization, then a thread that reads it could see any
combination of the first 32 bits from any of those writes and the second
32 bits from any of those writes. This is true even if the reading
thread is one of those that performed a write.

So, yes, corruption is possible here.

My recommendation would be to make the timestamp field volatile. There
would be no corruption, and you would probably get a program that does
what you want it to do (depending on what you want it to do).

I'm less sure about what your second question is asking. From your
example, it's unclear where the clock value is being set. So I can't
tell you if every thread will have the same value for it. If it is a
call to System.currentTimeMillis or System.nanoTime then that shouldn't
be a problem.

Soft/Weak references don't have any special memory semantics (other than
those associated with GC).

                                        Jeremy

Hanson Char wrote:
> I refer to the latest jdk1.5. Just wonder what's this forum thought on the
> SoftReferece.get() method:
>
> public T get() {
> T o = super.get();
> if (o != null) this.timestamp = clock;
> return o;
> }
>
> which updates the timestamp if necessary, but not being thread-safe in
> that the timiestamp is of type long but there is no synchronization.
>
> So in theory if multiple threads get hold of the same SoftReference
> and invoke the get method,
>
> 1) Can the timestamp result in a "corrupted" state ? Or,
>
> 2) Would all the thread then have the same clock value in their
> working copies, and therefore will always update the timestamp with
> that clock value ?
>
> What's the worst case scenario when this happened ? Should one bother
> to synchronize on the SoftReference instance when this method is
> invoked ?
>
> H
> -------------------------------
> JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel

-------------------------------
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