Re: SoftReference operation synchronization detail
- From: "Oliver Wong" <owong@xxxxxxxxxxxxxx>
- Date: Wed, 31 May 2006 15:31:05 GMT
"Stanimir Stamenkov" <stanio@xxxxxx> wrote in message news:1149088649.996756.239730@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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 */
I don't understand your exact question, but the information I think you want is that second code is unsafe. cache.get() might return null. The first code example is better. Note that the reference called "cache" won't magically turn into null behind your back. It's only the referent within the SoftReference which may become null (which is why get() sometimes returns null). So depending on the design of the rest of your code, the check for cache != null might be unnescessary.
- Oliver
.
- Follow-Ups:
- Re: SoftReference operation synchronization detail
- From: stamenkov
- Re: SoftReference operation synchronization detail
- From: Robert Klemme
- Re: SoftReference operation synchronization detail
- References:
- SoftReference operation synchronization detail
- From: Stanimir Stamenkov
- SoftReference operation synchronization detail
- Prev by Date: SoftReference operation synchronization detail
- Next by Date: Re: EnumSet + contains: strange behavior
- Previous by thread: SoftReference operation synchronization detail
- Next by thread: Re: SoftReference operation synchronization detail
- Index(es):
Relevant Pages
|
|