Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


WeakReference

@Pacerier: The author of that post is simply wrong. He neglects some other usage scenarios like event subscription, his second point is nonsensical, and his third point assumes that a programmer can do things that may not be possible. His first point is reasonable, but ties in directly with what I said. If code will frequently have to build and compare large immutable objects, for example, the building part will often be cheaper if code creates new objects without regard for whether they already exist, but a comparison between an object and itself (identical references) will be...

A key point about the proper use of a WeakReference is that in places where one should be using it, the fact that one may remain valid for a little while after the reference goes out of scope may be tolerable, but is not desirable.

I'm struggling to understand what is the use of WeakHashMap if it always produces weak reference to its key value object?

Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.

Particularly useful for the explanation of when weak objects would be used.

So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.

SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].

Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.

Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


@DoctororDrive tbf the question was about java, not dalvik! :-P

@YaroslavMytkalyk, Frankly, if Android wants to rewrite the behavior of a class, it should use its own namespace, not java.lang. Such abuse of synonyms is doing no one any good.

SoftReference is designed for caches. When it is found that a WeakReference references an otherwise unreachable object, then it will get cleared immediately. SoftReference may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx). SoftReferences will be cleared before OutOfMemoryError is thrown, unless otherwise reachable.

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


WeakReference weakWidget = new WeakReference(widget);

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:

And Peter Kessler added in a comment:

SoftReferences aren't required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.

The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.

and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


@DoctororDrive tbf the question was about java, not dalvik! :-P

@YaroslavMytkalyk, Frankly, if Android wants to rewrite the behavior of a class, it should use its own namespace, not java.lang. Such abuse of synonyms is doing no one any good.

SoftReference is designed for caches. When it is found that a WeakReference references an otherwise unreachable object, then it will get cleared immediately. SoftReference may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx). SoftReferences will be cleared before OutOfMemoryError is thrown, unless otherwise reachable.

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


WeakReference weakWidget = new WeakReference(widget);

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:

And Peter Kessler added in a comment:

SoftReferences aren't required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.

The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.

and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


WeakReference

@Pacerier: The author of that post is simply wrong. He neglects some other usage scenarios like event subscription, his second point is nonsensical, and his third point assumes that a programmer can do things that may not be possible. His first point is reasonable, but ties in directly with what I said. If code will frequently have to build and compare large immutable objects, for example, the building part will often be cheaper if code creates new objects without regard for whether they already exist, but a comparison between an object and itself (identical references) will be...

A key point about the proper use of a WeakReference is that in places where one should be using it, the fact that one may remain valid for a little while after the reference goes out of scope may be tolerable, but is not desirable.

I'm struggling to understand what is the use of WeakHashMap if it always produces weak reference to its key value object?

Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.

Particularly useful for the explanation of when weak objects would be used.

So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.

SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].

Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.

Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.

Clear and concise, this is the perfect summary for previous answers.

why did you highlight that as code? is it a quote?

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.

Clear and concise, this is the perfect summary for previous answers.

why did you highlight that as code? is it a quote?

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


WeakReference

@Pacerier: The author of that post is simply wrong. He neglects some other usage scenarios like event subscription, his second point is nonsensical, and his third point assumes that a programmer can do things that may not be possible. His first point is reasonable, but ties in directly with what I said. If code will frequently have to build and compare large immutable objects, for example, the building part will often be cheaper if code creates new objects without regard for whether they already exist, but a comparison between an object and itself (identical references) will be...

A key point about the proper use of a WeakReference is that in places where one should be using it, the fact that one may remain valid for a little while after the reference goes out of scope may be tolerable, but is not desirable.

I'm struggling to understand what is the use of WeakHashMap if it always produces weak reference to its key value object?

Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.

Particularly useful for the explanation of when weak objects would be used.

So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.

SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].

Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.

Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.

Note
Rectangle 27 0

reference What's the difference between SoftReference and WeakReference in Java?


uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.

Clear and concise, this is the perfect summary for previous answers.

why did you highlight that as code? is it a quote?

Note