Re: SoftReference operation synchronization detail
- From: Robert Klemme <bob.news@xxxxxxx>
- Date: Wed, 31 May 2006 17:48:51 +0200
Oliver Wong wrote:
"Stanimir Stamenkov" <stanio@xxxxxx> wrote in message news:1149088649.996756.239730@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxThe 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.
Adding to that, here's what I'd do assuming that "cache" is an instance variable: make sure cache is always initialized with a SoftReference. If you do not have a referent initially just use new SoftReference(null). Then you can simplify your code to
Object o = cache.get();
if ( o == null ) {
o = new Object();
cache = new SoftReference(o);
}
// work with o
The only downside of this is one additional object creation (the initial SoftReference) which usually only makes a difference if you have a lot of them.
Kind regards
robert
.
- Follow-Ups:
- Re: SoftReference operation synchronization detail
- From: Thomas Hawtin
- Re: SoftReference operation synchronization detail
- References:
- SoftReference operation synchronization detail
- From: Stanimir Stamenkov
- Re: SoftReference operation synchronization detail
- From: Oliver Wong
- SoftReference operation synchronization detail
- Prev by Date: Re: subclassing and generics
- Next by Date: Re: Debugger and function calls
- Previous by thread: Re: SoftReference operation synchronization detail
- Next by thread: Re: SoftReference operation synchronization detail
- Index(es):
Relevant Pages
|