SoftReference operation synchronization detail



The following may have more apparent effect when using a WeakReference.
Suppose I initialize a class member field which is a SoftReference, at
some point:

SoftReference cache = new SoftReference(obj);

Then I have the following code accessing the referenced object, in a
method body:

Object obj = null;
if (cache != null) {
obj = cache.get();
}
if (obj == null) {
obj = new Object(); /* re-initialize obj */
cache = new SoftReference(obj);
}
/* do with obj */

Is it guaranteed the 'cache' won't be cleared after the 'if (cache !=
null)' evaluates to true and prior executing the first statement in the
'if' block?

Is it guaranteed 'Reference.get()' will return a non-null result if the
corresponding SoftReference or WeakReference is not cleared yet?, so I
could go without the explicit 'obj = null' initialization in the above
example:

Object obj;
if (cache != null) {
obj = cache.get();
} else {
obj = new Object(); /* re-initialize obj */
cache = new SoftReference(obj);
}
/* do with obj */

--
Stanimir

.



Relevant Pages

  • Re: how to test cache existence
    ... Good approach but I believe there is still an issue because it is a shared function - static in C# - that is accessible by all threads. ... Since the cache is also global and available to all threads/requests within the application, the code needs to reflect this by protecting insertions and retrievals. ... statement of GetCachedItem returns valid cache entry but the cache entry ... dim obj as Object = HttpRuntime.Cache ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: SoftReference operation synchronization detail
    ... Suppose I initialize a class member field which is a SoftReference, ... SoftReference cache = new SoftReference; ... Object obj = null; ...
    (comp.lang.java.programmer)
  • Re: SoftReference operation synchronization detail
    ... Suppose I initialize a class member field which is a SoftReference, ... SoftReference cache = new SoftReference; ... Object obj = null; ...
    (comp.lang.java.programmer)
  • Re: Collaborative development on Smalltalk?
    ... > application following the general pattern, ... > application needs to build a cache of some sort inside the image, ... > Your application has an "initialize" method that resets the cache and ... > When you load a versioned component from the code repository, ...
    (comp.lang.smalltalk)
  • Re: SoftReference operation synchronization detail
    ... SoftReference which may become null sometimes returns ... thought) while playing with those Reference classes - I've got 'null' ... SoftReference cache = new SoftReference); ... So the garbage collector may decide it wants to collect that Foo object. ...
    (comp.lang.java.programmer)