Search code examples
candroid-sourceandroid-binder

What are strong pointers and weak pointers


I am confused with the notion of "strong pointer" and "weak pointer". Diane Hackborn herself said that:

The object will remain around while there are strong pointers; it is destroyed once the last one is released. All you can do with a weak pointer is comparison and attempting to promote to a strong pointer; the latter will fail if there are no other strong pointers on the object.

Which is quite unclear to me. Is a strong pointer an equivalent of a (boost::)shared pointer? And what is the role of a weak pointer if it is there just to attempt to promote itself to a strong pointer? Like, when do we need weak and strong pointers?

Update:

Thank you everyone, but I'm asking specifically about android's kernel sp and wp, and they have nothing to do with Java's references at all.

Basically I'm trying to crack the code here http://www.androidenea.com/2010/03/share-memory-using-ashmem-and-binder-in.html And don't really understand the use of sp and wp

Update:

The actual answer lies in the comments of the accepted answer. Thanks to Gabe Sechan:

Strong and weak pointers are different smart pointer implementations and do about the same thing- when a pointer goes out of scope, so long as at least one strong pointer references it it will not be freed. If only weak pointers (or nothing) references it will be. The check is done whenever a strong or weak reference to it is descoped.

if I have 10 weak pointers referencing the same object, and one of those 10 goes out of scope, the object will be destroyed? Whereas with strong pointers, only when all 10 of them go out of scope will the object be destroyed?

Yes, almost. If all you have is 10 weak pointers, it would probably have gone out of scope already, when the last strong pointer went out of scope. The implementation may allow it to stick around a little while longer if there's spare memory, but it will be chopped if you go into a low memory condition and it doesn't sound like their implementation is that advanced from her quote. And the use of this is still mainly caching- it is roughly equivalent to a boost shared_ptr and boost weak_ptr. So basically, a weak pointer can have the object it references go away at any time.


Solution

  • Android is meant to be programmed in Java, not C. Any documentation from the Android team would reference that language. In Java there are strong and weak references. A weak reference doesn't stop the garbage collector from cleaning it up, a strong reference does. They're used for caching on some OSes, but on Android as of 3.0 holding only weak references to an object means it will be collected immediately.

    C has no equivalent of a weak reference, as it has no garbage collection.