[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Joseph Earl
Suppose you had a long list of images. As the user scrolled down you
load the images from the net, and then display them.
To avoid having to reload the images again if the user scrolls back
up, you put the images in a cache (probably something like a
Map)

However because it is a long list you don't want to run into an out of
memory situation if the user scrolls very far down and lots of images
are put in the cache.
So instead of storing the Drawables directly in the map, you create a
Map> (although I would use SoftReference
for the purpose described here).
This means that if Android is going to encounter an out of memory
situation it will clear all of the Soft/Weak references (and thus
hopefully avoid running out of memory). You will have to load the
images again since your cache has been cleared, but this is far better
than your application running out of memory and crashing.

So you do something like:

// caching an image
Map cache = new HashMap>();
cache.put("http://mysite.com/images/1.jpg";, new
SoftReference.put(myDrawable));

// retrieve an image
if (cache.containsKey(url)) {
   // looks like we have this image cached
   Drawable drawable = cache.get(url).get();
   if (drawable == null) {
   // the softreference has been cleared by the GC, reload the
image
   } else {
   // softreference is still valid, got our image
   }
}


Essentially a weak reference is a weaker reference than a soft
reference - the GC should free weak references to regain memory before
soft references.

I think that's (mostly) correct, hope it helps.

On Jul 22, 6:48 pm, GodsMoon  wrote:
> Google just posted a new blog post 
> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> I understand the AsyncTask and I'm even using one in a list with
> images already.
>
> But I don't understand what a WeakReference is. I gather is is a
> garbage collector directive, but I thought I didn't need to manage
> garbage collection on Android.
>
> http://developer.android.com/reference/java/lang/ref/WeakReference.html
> isn't as helpful as I was hoping it would be.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread DanH
The real Java doc is a bit better:
http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/ref/WeakReference.html

A WeakReference is an object that contains within it a reference to
another object.  The reference is treated specially by the garbage
collector in that its existence doesn't prevent the object from being
deleted (though any other "real" reference will).  But, if the object
IS deleted, the garbage collector nulls the pointer in the
WeakReference.

You can examine the actual object reference using the ref() method.

You might, eg, create a cache (say, of URLs resolved to IP addresses
by network name lookup) by using a hashtable of String -
>WeakReference.  When you want to reference something you look it up
in the hashtable and, if not found, create it.  Later, when you look
again and find the hashtable entry you check ref() and treat it as
"not found" if the ref() is null, otherwise use the ref() value to
reference the object.  Garbage collection will preferentially not
delete objects referenced from WeakReferences, but may eventually
delete them, after several GC cycles of being otherwise unreferenced.

On Jul 22, 12:48 pm, GodsMoon  wrote:
> Google just posted a new blog post 
> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> I understand the AsyncTask and I'm even using one in a list with
> images already.
>
> But I don't understand what a WeakReference is. I gather is is a
> garbage collector directive, but I thought I didn't need to manage
> garbage collection on Android.
>
> http://developer.android.com/reference/java/lang/ref/WeakReference.html
> isn't as helpful as I was hoping it would be.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread DanH
I partly got the roles of SoftReference and WeakReference mixed up.
For the cache you would more likely use SoftReference, and it's the
one that is preferentially not deleted by GC.  WeakReferences don't
slow deletion at all (well, hardly any -- there's the whole queue
thing, but that's for the graduate level class).  So a WeakReference
would be used where you want to have a reference to an object if it
exists, but not prevent its deletion.

Let's say that you have a Department object that tracks all of the
members (Employees) of a department in BigBlueCompany.  But you also
have, of course, a Payroll object that knows all of the employees for
the entire company, and when someone gets cut from the Payroll that's
it -- they're kaput, gone, vanished.  If a WeakReference to the
Employee is used in the Department object, as soon as the Employee ref
is stomped in the Payroll object (and a GC cycle done) the Employee is
suitably disappeared, without having to remove it from the Department.

(In real life this is especially handy if you're keeping refs into
another structure where the manager of that structure does't know
about your refs and the need to remove them.  With normal refs vs
WeakReferences this would lead to a storage leak, since objects the
manager thought were deleted were still referenced by you and were not
getting cleaned up.  And you'd not know when an object was considered
deleted by the structure's manager.)

On Jul 22, 1:21 pm, DanH  wrote:
> The real Java doc is a bit 
> better:http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/l...
>
> A WeakReference is an object that contains within it a reference to
> another object.  The reference is treated specially by the garbage
> collector in that its existence doesn't prevent the object from being
> deleted (though any other "real" reference will).  But, if the object
> IS deleted, the garbage collector nulls the pointer in the
> WeakReference.
>
> You can examine the actual object reference using the ref() method.
>
> You might, eg, create a cache (say, of URLs resolved to IP addresses
> by network name lookup) by using a hashtable of String ->WeakReference.  When 
> you want to reference something you look it up
>
> in the hashtable and, if not found, create it.  Later, when you look
> again and find the hashtable entry you check ref() and treat it as
> "not found" if the ref() is null, otherwise use the ref() value to
> reference the object.  Garbage collection will preferentially not
> delete objects referenced from WeakReferences, but may eventually
> delete them, after several GC cycles of being otherwise unreferenced.
>
> On Jul 22, 12:48 pm, GodsMoon  wrote:
>
> > Google just posted a new blog post 
> > onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > I understand the AsyncTask and I'm even using one in a list with
> > images already.
>
> > But I don't understand what a WeakReference is. I gather is is a
> > garbage collector directive, but I thought I didn't need to manage
> > garbage collection on Android.
>
> >http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > isn't as helpful as I was hoping it would be.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Joseph Earl
Thanks for the info. I was unsure as to exactly how weak
WeakReferences were, since I have never had a use for them yet.

On Jul 22, 7:26 pm, Romain Guy  wrote:
> You definitely do NOT want to use a WeakReference to cache object. If
> you do so, as soon as your data is put in the cache and not used
> outside of the cache, it gets garbage collected.
>
>
>
> On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  wrote:
> > Suppose you had a long list of images. As the user scrolled down you
> > load the images from the net, and then display them.
> > To avoid having to reload the images again if the user scrolls back
> > up, you put the images in a cache (probably something like a
> > Map)
>
> > However because it is a long list you don't want to run into an out of
> > memory situation if the user scrolls very far down and lots of images
> > are put in the cache.
> > So instead of storing the Drawables directly in the map, you create a
> > Map> (although I would use SoftReference
> > for the purpose described here).
> > This means that if Android is going to encounter an out of memory
> > situation it will clear all of the Soft/Weak references (and thus
> > hopefully avoid running out of memory). You will have to load the
> > images again since your cache has been cleared, but this is far better
> > than your application running out of memory and crashing.
>
> > So you do something like:
>
> > // caching an image
> > Map cache = new HashMap > SoftReference>();
> > cache.put("http://mysite.com/images/1.jpg";, new
> > SoftReference.put(myDrawable));
>
> > // retrieve an image
> > if (cache.containsKey(url)) {
> >   // looks like we have this image cached
> >   Drawable drawable = cache.get(url).get();
> >   if (drawable == null) {
> >       // the softreference has been cleared by the GC, reload the
> > image
> >   } else {
> >       // softreference is still valid, got our image
> >   }
> > }
>
> > Essentially a weak reference is a weaker reference than a soft
> > reference - the GC should free weak references to regain memory before
> > soft references.
>
> > I think that's (mostly) correct, hope it helps.
>
> > On Jul 22, 6:48 pm, GodsMoon  wrote:
> >> Google just posted a new blog post 
> >> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> >> I understand the AsyncTask and I'm even using one in a list with
> >> images already.
>
> >> But I don't understand what a WeakReference is. I gather is is a
> >> garbage collector directive, but I thought I didn't need to manage
> >> garbage collection on Android.
>
> >>http://developer.android.com/reference/java/lang/ref/WeakReference.html
> >> isn't as helpful as I was hoping it would be.
>
> > --
> > You received this message because you are subscribed to the Google
> > Groups "Android Developers" group.
> > To post to this group, send email to android-developers@googlegroups.com
> > To unsubscribe from this group, send email to
> > android-developers+unsubscr...@googlegroups.com
> > For more options, visit this group at
> >http://groups.google.com/group/android-developers?hl=en
>
> --
> Romain Guy
> Android framework engineer
> romain...@android.com
>
> Note: please don't send private questions to me, as I don't have time
> to provide private support.  All such questions should be posted on
> public forums, where I and others can see and answer them

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread GodsMoon
So you'd only want to use WeakReference when you think your activity
might run out of memory?
But a list view already does efficient memory management for you
right?

You'd saying if I were create a large array or something like that
then it would be good to use WeakReference. right?

Thanks for the help guys,
David Shellabarger
www.nightshadelabs.com

On Jul 22, 2:26 pm, Romain Guy  wrote:
> You definitely do NOT want to use a WeakReference to cache object. If
> you do so, as soon as your data is put in the cache and not used
> outside of the cache, it gets garbage collected.
>
>
>
>
>
> On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  wrote:
> > Suppose you had a long list of images. As the user scrolled down you
> > load the images from the net, and then display them.
> > To avoid having to reload the images again if the user scrolls back
> > up, you put the images in a cache (probably something like a
> > Map)
>
> > However because it is a long list you don't want to run into an out of
> > memory situation if the user scrolls very far down and lots of images
> > are put in the cache.
> > So instead of storing the Drawables directly in the map, you create a
> > Map> (although I would use SoftReference
> > for the purpose described here).
> > This means that if Android is going to encounter an out of memory
> > situation it will clear all of the Soft/Weak references (and thus
> > hopefully avoid running out of memory). You will have to load the
> > images again since your cache has been cleared, but this is far better
> > than your application running out of memory and crashing.
>
> > So you do something like:
>
> > // caching an image
> > Map cache = new HashMap > SoftReference>();
> > cache.put("http://mysite.com/images/1.jpg";, new
> > SoftReference.put(myDrawable));
>
> > // retrieve an image
> > if (cache.containsKey(url)) {
> >   // looks like we have this image cached
> >   Drawable drawable = cache.get(url).get();
> >   if (drawable == null) {
> >       // the softreference has been cleared by the GC, reload the
> > image
> >   } else {
> >       // softreference is still valid, got our image
> >   }
> > }
>
> > Essentially a weak reference is a weaker reference than a soft
> > reference - the GC should free weak references to regain memory before
> > soft references.
>
> > I think that's (mostly) correct, hope it helps.
>
> > On Jul 22, 6:48 pm, GodsMoon  wrote:
> >> Google just posted a new blog post 
> >> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> >> I understand the AsyncTask and I'm even using one in a list with
> >> images already.
>
> >> But I don't understand what a WeakReference is. I gather is is a
> >> garbage collector directive, but I thought I didn't need to manage
> >> garbage collection on Android.
>
> >>http://developer.android.com/reference/java/lang/ref/WeakReference.html
> >> isn't as helpful as I was hoping it would be.
>
> > --
> > You received this message because you are subscribed to the Google
> > Groups "Android Developers" group.
> > To post to this group, send email to android-developers@googlegroups.com
> > To unsubscribe from this group, send email to
> > android-developers+unsubscr...@googlegroups.com
> > For more options, visit this group at
> >http://groups.google.com/group/android-developers?hl=en
>
> --
> Romain Guy
> Android framework engineer
> romain...@android.com
>
> Note: please don't send private questions to me, as I don't have time
> to provide private support.  All such questions should be posted on
> public forums, where I and others can see and answer them

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Joseph Earl
No. I'm unsure as to what to use a WeakReference for exactly - as
Romain Guy said above it is too weak for this purpose, but I think
(hopefully Romain will correct me if I'm wrong) that a SoftReference
could be suitable for this purpose.

A ListView already does efficient management of your Views by
recycling. This means that you must ensure the correct details are set
in the view each time getView is called, even if you do not inflate a
view or call findViewById that time. Recycling does not mean that the
ListView caches all your items or their content.

Suppose you had a list of 10 items, all of the same type but only 5
will fit on the screen at a time. The ListView only really needs 5
views to show the rows since the other 5 won't be visible.
Thus at the top of the list the ListView might use 'View 1' for the
first item, but scroll down to the bottom and 'View 1' would now
contain item 6. As far as I understand it this is recycling.

Recycling does not take care of the amount time of it takes to get
content and set it to the view - thus if it takes a long time to get a
piece of information and display it in a list item (such as
downloading an image from the web), you will want to cache the result
in a way that does not adversely affect memory usage (as much as
possible). In this case you will also want to use a Thread or Async
task to download/get the info off the UI thread.

On Jul 22, 7:36 pm, GodsMoon  wrote:
> So you'd only want to use WeakReference when you think your activity
> might run out of memory?
> But a list view already does efficient memory management for you
> right?
>
> You'd saying if I were create a large array or something like that
> then it would be good to use WeakReference. right?
>
> Thanks for the help guys,
> David Shellabargerwww.nightshadelabs.com
>
> On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > You definitely do NOT want to use a WeakReference to cache object. If
> > you do so, as soon as your data is put in the cache and not used
> > outside of the cache, it gets garbage collected.
>
> > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  
> > wrote:
> > > Suppose you had a long list of images. As the user scrolled down you
> > > load the images from the net, and then display them.
> > > To avoid having to reload the images again if the user scrolls back
> > > up, you put the images in a cache (probably something like a
> > > Map)
>
> > > However because it is a long list you don't want to run into an out of
> > > memory situation if the user scrolls very far down and lots of images
> > > are put in the cache.
> > > So instead of storing the Drawables directly in the map, you create a
> > > Map> (although I would use SoftReference
> > > for the purpose described here).
> > > This means that if Android is going to encounter an out of memory
> > > situation it will clear all of the Soft/Weak references (and thus
> > > hopefully avoid running out of memory). You will have to load the
> > > images again since your cache has been cleared, but this is far better
> > > than your application running out of memory and crashing.
>
> > > So you do something like:
>
> > > // caching an image
> > > Map cache = new HashMap > > SoftReference>();
> > > cache.put("http://mysite.com/images/1.jpg";, new
> > > SoftReference.put(myDrawable));
>
> > > // retrieve an image
> > > if (cache.containsKey(url)) {
> > >   // looks like we have this image cached
> > >   Drawable drawable = cache.get(url).get();
> > >   if (drawable == null) {
> > >       // the softreference has been cleared by the GC, reload the
> > > image
> > >   } else {
> > >       // softreference is still valid, got our image
> > >   }
> > > }
>
> > > Essentially a weak reference is a weaker reference than a soft
> > > reference - the GC should free weak references to regain memory before
> > > soft references.
>
> > > I think that's (mostly) correct, hope it helps.
>
> > > On Jul 22, 6:48 pm, GodsMoon  wrote:
> > >> Google just posted a new blog post 
> > >> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > >> I understand the AsyncTask and I'm even using one in a list with
> > >> images already.
>
> > >> But I don't understand what a WeakReference is. I gather is is a
> > >> garbage collector directive, but I thought I didn't need to manage
> > >> garbage collection on Android.
>
> > >>http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > >> isn't as helpful as I was hoping it would be.
>
> > > --
> > > You received this message because you are subscribed to the Google
> > > Groups "Android Developers" group.
> > > To post to this group, send email to android-developers@googlegroups.com
> > > To unsubscribe from this group, send email to
> > > android-developers+unsubscr...@googlegroups.com
> > > For more options, visit this group at
> > >http://groups.google.com/group/android-developers?hl=en
>
> > --
> > Romain Guy
> > Android framework engineer
> > romain...@android.com
>
> > N

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread GodsMoon
The blog post is confusing.
"Note that this ImageView is stored as a WeakReference, so that a
download in progress does not prevent a killed activity's ImageView
from being garbage collected."
I didn't know that would cause a memory leak. I thought the garbage
collector would clean up ImageView if its activity gets killed.
Am I wrong?

David Shellabarger
www.nightshadelabs.com

On Jul 22, 3:06 pm, Joseph Earl  wrote:
> No. I'm unsure as to what to use a WeakReference for exactly - as
> Romain Guy said above it is too weak for this purpose, but I think
> (hopefully Romain will correct me if I'm wrong) that a SoftReference
> could be suitable for this purpose.
>
> A ListView already does efficient management of your Views by
> recycling. This means that you must ensure the correct details are set
> in the view each time getView is called, even if you do not inflate a
> view or call findViewById that time. Recycling does not mean that the
> ListView caches all your items or their content.
>
> Suppose you had a list of 10 items, all of the same type but only 5
> will fit on the screen at a time. The ListView only really needs 5
> views to show the rows since the other 5 won't be visible.
> Thus at the top of the list the ListView might use 'View 1' for the
> first item, but scroll down to the bottom and 'View 1' would now
> contain item 6. As far as I understand it this is recycling.
>
> Recycling does not take care of the amount time of it takes to get
> content and set it to the view - thus if it takes a long time to get a
> piece of information and display it in a list item (such as
> downloading an image from the web), you will want to cache the result
> in a way that does not adversely affect memory usage (as much as
> possible). In this case you will also want to use a Thread or Async
> task to download/get the info off the UI thread.
>
> On Jul 22, 7:36 pm, GodsMoon  wrote:
>
>
>
> > So you'd only want to use WeakReference when you think your activity
> > might run out of memory?
> > But a list view already does efficient memory management for you
> > right?
>
> > You'd saying if I were create a large array or something like that
> > then it would be good to use WeakReference. right?
>
> > Thanks for the help guys,
> > David Shellabargerwww.nightshadelabs.com
>
> > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > You definitely do NOT want to use a WeakReference to cache object. If
> > > you do so, as soon as your data is put in the cache and not used
> > > outside of the cache, it gets garbage collected.
>
> > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  
> > > wrote:
> > > > Suppose you had a long list of images. As the user scrolled down you
> > > > load the images from the net, and then display them.
> > > > To avoid having to reload the images again if the user scrolls back
> > > > up, you put the images in a cache (probably something like a
> > > > Map)
>
> > > > However because it is a long list you don't want to run into an out of
> > > > memory situation if the user scrolls very far down and lots of images
> > > > are put in the cache.
> > > > So instead of storing the Drawables directly in the map, you create a
> > > > Map> (although I would use SoftReference
> > > > for the purpose described here).
> > > > This means that if Android is going to encounter an out of memory
> > > > situation it will clear all of the Soft/Weak references (and thus
> > > > hopefully avoid running out of memory). You will have to load the
> > > > images again since your cache has been cleared, but this is far better
> > > > than your application running out of memory and crashing.
>
> > > > So you do something like:
>
> > > > // caching an image
> > > > Map cache = new HashMap > > > SoftReference>();
> > > > cache.put("http://mysite.com/images/1.jpg";, new
> > > > SoftReference.put(myDrawable));
>
> > > > // retrieve an image
> > > > if (cache.containsKey(url)) {
> > > >   // looks like we have this image cached
> > > >   Drawable drawable = cache.get(url).get();
> > > >   if (drawable == null) {
> > > >       // the softreference has been cleared by the GC, reload the
> > > > image
> > > >   } else {
> > > >       // softreference is still valid, got our image
> > > >   }
> > > > }
>
> > > > Essentially a weak reference is a weaker reference than a soft
> > > > reference - the GC should free weak references to regain memory before
> > > > soft references.
>
> > > > I think that's (mostly) correct, hope it helps.
>
> > > > On Jul 22, 6:48 pm, GodsMoon  wrote:
> > > >> Google just posted a new blog post 
> > > >> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > > >> I understand the AsyncTask and I'm even using one in a list with
> > > >> images already.
>
> > > >> But I don't understand what a WeakReference is. I gather is is a
> > > >> garbage collector directive, but I thought I didn't need to manage
> > > >> garbage collection on Android.
>
> > > >>http://developer.android.com/re

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Joseph Earl
When your UI activity is killed as far as I am aware the GC will
collect your Views. The problem is (I think) if the GC closes your UI
thread while the downloader is still running - in this case your
downloader thread maintains a reference to the ImageView so the GC
cannot collect it - hence memory leak - the downloader thread cannot
actually do anything to the ImageView since the UI thread no longer
exists.
Thus the downloader thread should only store a weak reference to the
ImageView so that if the UI thread is killed the GC may reclaim the
memory associated with the ImageView.

On Jul 22, 8:34 pm, GodsMoon  wrote:
> The blog post is confusing.
> "Note that this ImageView is stored as a WeakReference, so that a
> download in progress does not prevent a killed activity's ImageView
> from being garbage collected."
> I didn't know that would cause a memory leak. I thought the garbage
> collector would clean up ImageView if its activity gets killed.
> Am I wrong?
>
> David Shellabargerwww.nightshadelabs.com
>
> On Jul 22, 3:06 pm, Joseph Earl  wrote:
>
> > No. I'm unsure as to what to use a WeakReference for exactly - as
> > Romain Guy said above it is too weak for this purpose, but I think
> > (hopefully Romain will correct me if I'm wrong) that a SoftReference
> > could be suitable for this purpose.
>
> > A ListView already does efficient management of your Views by
> > recycling. This means that you must ensure the correct details are set
> > in the view each time getView is called, even if you do not inflate a
> > view or call findViewById that time. Recycling does not mean that the
> > ListView caches all your items or their content.
>
> > Suppose you had a list of 10 items, all of the same type but only 5
> > will fit on the screen at a time. The ListView only really needs 5
> > views to show the rows since the other 5 won't be visible.
> > Thus at the top of the list the ListView might use 'View 1' for the
> > first item, but scroll down to the bottom and 'View 1' would now
> > contain item 6. As far as I understand it this is recycling.
>
> > Recycling does not take care of the amount time of it takes to get
> > content and set it to the view - thus if it takes a long time to get a
> > piece of information and display it in a list item (such as
> > downloading an image from the web), you will want to cache the result
> > in a way that does not adversely affect memory usage (as much as
> > possible). In this case you will also want to use a Thread or Async
> > task to download/get the info off the UI thread.
>
> > On Jul 22, 7:36 pm, GodsMoon  wrote:
>
> > > So you'd only want to use WeakReference when you think your activity
> > > might run out of memory?
> > > But a list view already does efficient memory management for you
> > > right?
>
> > > You'd saying if I were create a large array or something like that
> > > then it would be good to use WeakReference. right?
>
> > > Thanks for the help guys,
> > > David Shellabargerwww.nightshadelabs.com
>
> > > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > > You definitely do NOT want to use a WeakReference to cache object. If
> > > > you do so, as soon as your data is put in the cache and not used
> > > > outside of the cache, it gets garbage collected.
>
> > > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  
> > > > wrote:
> > > > > Suppose you had a long list of images. As the user scrolled down you
> > > > > load the images from the net, and then display them.
> > > > > To avoid having to reload the images again if the user scrolls back
> > > > > up, you put the images in a cache (probably something like a
> > > > > Map)
>
> > > > > However because it is a long list you don't want to run into an out of
> > > > > memory situation if the user scrolls very far down and lots of images
> > > > > are put in the cache.
> > > > > So instead of storing the Drawables directly in the map, you create a
> > > > > Map> (although I would use SoftReference
> > > > > for the purpose described here).
> > > > > This means that if Android is going to encounter an out of memory
> > > > > situation it will clear all of the Soft/Weak references (and thus
> > > > > hopefully avoid running out of memory). You will have to load the
> > > > > images again since your cache has been cleared, but this is far better
> > > > > than your application running out of memory and crashing.
>
> > > > > So you do something like:
>
> > > > > // caching an image
> > > > > Map cache = new HashMap > > > > SoftReference>();
> > > > > cache.put("http://mysite.com/images/1.jpg";, new
> > > > > SoftReference.put(myDrawable));
>
> > > > > // retrieve an image
> > > > > if (cache.containsKey(url)) {
> > > > >   // looks like we have this image cached
> > > > >   Drawable drawable = cache.get(url).get();
> > > > >   if (drawable == null) {
> > > > >       // the softreference has been cleared by the GC, reload the
> > > > > image
> > > > >   } else {
> > > > >       // softreference is still valid, go

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread GodsMoon
I have done something like that and got a null pointer reference.
I was starting a AsyncTask and if you backed out of the activity
before the AsyncTask was finished I would get a null pointer when I
tried to refer to the activities elements (force close).
So I just check to see if the views are null first. I thought that if
it returned null then it must have been GCed.
But that's not the case?

David Shellabarger
www.nightshadelabs.com

On Jul 22, 3:49 pm, Joseph Earl  wrote:
> When your UI activity is killed as far as I am aware the GC will
> collect your Views. The problem is (I think) if the GC closes your UI
> thread while the downloader is still running - in this case your
> downloader thread maintains a reference to the ImageView so the GC
> cannot collect it - hence memory leak - the downloader thread cannot
> actually do anything to the ImageView since the UI thread no longer
> exists.
> Thus the downloader thread should only store a weak reference to the
> ImageView so that if the UI thread is killed the GC may reclaim the
> memory associated with the ImageView.
>
> On Jul 22, 8:34 pm, GodsMoon  wrote:
>
>
>
> > The blog post is confusing.
> > "Note that this ImageView is stored as a WeakReference, so that a
> > download in progress does not prevent a killed activity's ImageView
> > from being garbage collected."
> > I didn't know that would cause a memory leak. I thought the garbage
> > collector would clean up ImageView if its activity gets killed.
> > Am I wrong?
>
> > David Shellabargerwww.nightshadelabs.com
>
> > On Jul 22, 3:06 pm, Joseph Earl  wrote:
>
> > > No. I'm unsure as to what to use a WeakReference for exactly - as
> > > Romain Guy said above it is too weak for this purpose, but I think
> > > (hopefully Romain will correct me if I'm wrong) that a SoftReference
> > > could be suitable for this purpose.
>
> > > A ListView already does efficient management of your Views by
> > > recycling. This means that you must ensure the correct details are set
> > > in the view each time getView is called, even if you do not inflate a
> > > view or call findViewById that time. Recycling does not mean that the
> > > ListView caches all your items or their content.
>
> > > Suppose you had a list of 10 items, all of the same type but only 5
> > > will fit on the screen at a time. The ListView only really needs 5
> > > views to show the rows since the other 5 won't be visible.
> > > Thus at the top of the list the ListView might use 'View 1' for the
> > > first item, but scroll down to the bottom and 'View 1' would now
> > > contain item 6. As far as I understand it this is recycling.
>
> > > Recycling does not take care of the amount time of it takes to get
> > > content and set it to the view - thus if it takes a long time to get a
> > > piece of information and display it in a list item (such as
> > > downloading an image from the web), you will want to cache the result
> > > in a way that does not adversely affect memory usage (as much as
> > > possible). In this case you will also want to use a Thread or Async
> > > task to download/get the info off the UI thread.
>
> > > On Jul 22, 7:36 pm, GodsMoon  wrote:
>
> > > > So you'd only want to use WeakReference when you think your activity
> > > > might run out of memory?
> > > > But a list view already does efficient memory management for you
> > > > right?
>
> > > > You'd saying if I were create a large array or something like that
> > > > then it would be good to use WeakReference. right?
>
> > > > Thanks for the help guys,
> > > > David Shellabargerwww.nightshadelabs.com
>
> > > > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > > > You definitely do NOT want to use a WeakReference to cache object. If
> > > > > you do so, as soon as your data is put in the cache and not used
> > > > > outside of the cache, it gets garbage collected.
>
> > > > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl 
> > > > >  wrote:
> > > > > > Suppose you had a long list of images. As the user scrolled down you
> > > > > > load the images from the net, and then display them.
> > > > > > To avoid having to reload the images again if the user scrolls back
> > > > > > up, you put the images in a cache (probably something like a
> > > > > > Map)
>
> > > > > > However because it is a long list you don't want to run into an out 
> > > > > > of
> > > > > > memory situation if the user scrolls very far down and lots of 
> > > > > > images
> > > > > > are put in the cache.
> > > > > > So instead of storing the Drawables directly in the map, you create 
> > > > > > a
> > > > > > Map> (although I would use SoftReference
> > > > > > for the purpose described here).
> > > > > > This means that if Android is going to encounter an out of memory
> > > > > > situation it will clear all of the Soft/Weak references (and thus
> > > > > > hopefully avoid running out of memory). You will have to load the
> > > > > > images again since your cache has been cleared, but this is far 
> > > > > > b

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Joseph Earl
I am confused somewhat about the issue myself now. Hopefully someone
else it will clear it up once and for all.

On Jul 22, 9:01 pm, GodsMoon  wrote:
> I have done something like that and got a null pointer reference.
> I was starting a AsyncTask and if you backed out of the activity
> before the AsyncTask was finished I would get a null pointer when I
> tried to refer to the activities elements (force close).
> So I just check to see if the views are null first. I thought that if
> it returned null then it must have been GCed.
> But that's not the case?
>
> David Shellabargerwww.nightshadelabs.com
>
> On Jul 22, 3:49 pm, Joseph Earl  wrote:
>
> > When your UI activity is killed as far as I am aware the GC will
> > collect your Views. The problem is (I think) if the GC closes your UI
> > thread while the downloader is still running - in this case your
> > downloader thread maintains a reference to the ImageView so the GC
> > cannot collect it - hence memory leak - the downloader thread cannot
> > actually do anything to the ImageView since the UI thread no longer
> > exists.
> > Thus the downloader thread should only store a weak reference to the
> > ImageView so that if the UI thread is killed the GC may reclaim the
> > memory associated with the ImageView.
>
> > On Jul 22, 8:34 pm, GodsMoon  wrote:
>
> > > The blog post is confusing.
> > > "Note that this ImageView is stored as a WeakReference, so that a
> > > download in progress does not prevent a killed activity's ImageView
> > > from being garbage collected."
> > > I didn't know that would cause a memory leak. I thought the garbage
> > > collector would clean up ImageView if its activity gets killed.
> > > Am I wrong?
>
> > > David Shellabargerwww.nightshadelabs.com
>
> > > On Jul 22, 3:06 pm, Joseph Earl  wrote:
>
> > > > No. I'm unsure as to what to use a WeakReference for exactly - as
> > > > Romain Guy said above it is too weak for this purpose, but I think
> > > > (hopefully Romain will correct me if I'm wrong) that a SoftReference
> > > > could be suitable for this purpose.
>
> > > > A ListView already does efficient management of your Views by
> > > > recycling. This means that you must ensure the correct details are set
> > > > in the view each time getView is called, even if you do not inflate a
> > > > view or call findViewById that time. Recycling does not mean that the
> > > > ListView caches all your items or their content.
>
> > > > Suppose you had a list of 10 items, all of the same type but only 5
> > > > will fit on the screen at a time. The ListView only really needs 5
> > > > views to show the rows since the other 5 won't be visible.
> > > > Thus at the top of the list the ListView might use 'View 1' for the
> > > > first item, but scroll down to the bottom and 'View 1' would now
> > > > contain item 6. As far as I understand it this is recycling.
>
> > > > Recycling does not take care of the amount time of it takes to get
> > > > content and set it to the view - thus if it takes a long time to get a
> > > > piece of information and display it in a list item (such as
> > > > downloading an image from the web), you will want to cache the result
> > > > in a way that does not adversely affect memory usage (as much as
> > > > possible). In this case you will also want to use a Thread or Async
> > > > task to download/get the info off the UI thread.
>
> > > > On Jul 22, 7:36 pm, GodsMoon  wrote:
>
> > > > > So you'd only want to use WeakReference when you think your activity
> > > > > might run out of memory?
> > > > > But a list view already does efficient memory management for you
> > > > > right?
>
> > > > > You'd saying if I were create a large array or something like that
> > > > > then it would be good to use WeakReference. right?
>
> > > > > Thanks for the help guys,
> > > > > David Shellabargerwww.nightshadelabs.com
>
> > > > > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > > > > You definitely do NOT want to use a WeakReference to cache object. 
> > > > > > If
> > > > > > you do so, as soon as your data is put in the cache and not used
> > > > > > outside of the cache, it gets garbage collected.
>
> > > > > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl 
> > > > > >  wrote:
> > > > > > > Suppose you had a long list of images. As the user scrolled down 
> > > > > > > you
> > > > > > > load the images from the net, and then display them.
> > > > > > > To avoid having to reload the images again if the user scrolls 
> > > > > > > back
> > > > > > > up, you put the images in a cache (probably something like a
> > > > > > > Map)
>
> > > > > > > However because it is a long list you don't want to run into an 
> > > > > > > out of
> > > > > > > memory situation if the user scrolls very far down and lots of 
> > > > > > > images
> > > > > > > are put in the cache.
> > > > > > > So instead of storing the Drawables directly in the map, you 
> > > > > > > create a
> > > > > > > Map> (although I would use 
> > > > > > > SoftReference
> > 

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread GodsMoon
Perhaps the difference was because I was declaring my view in the
onCreate method instead of in the onPostExecute method of the
AsyncTask?

If I declare the view in my activity, maybe it gets GCed when my
activity is killed, but in the blog post example he tries to declare
it in the AsyncTask even though the activity is long gone.

Am I on the right track here?

David Shellabarger
www.nightshadelabs.com

On Jul 22, 4:09 pm, Joseph Earl  wrote:
> I am confused somewhat about the issue myself now. Hopefully someone
> else it will clear it up once and for all.
>
> On Jul 22, 9:01 pm, GodsMoon  wrote:
>
>
>
> > I have done something like that and got a null pointer reference.
> > I was starting a AsyncTask and if you backed out of the activity
> > before the AsyncTask was finished I would get a null pointer when I
> > tried to refer to the activities elements (force close).
> > So I just check to see if the views are null first. I thought that if
> > it returned null then it must have been GCed.
> > But that's not the case?
>
> > David Shellabargerwww.nightshadelabs.com
>
> > On Jul 22, 3:49 pm, Joseph Earl  wrote:
>
> > > When your UI activity is killed as far as I am aware the GC will
> > > collect your Views. The problem is (I think) if the GC closes your UI
> > > thread while the downloader is still running - in this case your
> > > downloader thread maintains a reference to the ImageView so the GC
> > > cannot collect it - hence memory leak - the downloader thread cannot
> > > actually do anything to the ImageView since the UI thread no longer
> > > exists.
> > > Thus the downloader thread should only store a weak reference to the
> > > ImageView so that if the UI thread is killed the GC may reclaim the
> > > memory associated with the ImageView.
>
> > > On Jul 22, 8:34 pm, GodsMoon  wrote:
>
> > > > The blog post is confusing.
> > > > "Note that this ImageView is stored as a WeakReference, so that a
> > > > download in progress does not prevent a killed activity's ImageView
> > > > from being garbage collected."
> > > > I didn't know that would cause a memory leak. I thought the garbage
> > > > collector would clean up ImageView if its activity gets killed.
> > > > Am I wrong?
>
> > > > David Shellabargerwww.nightshadelabs.com
>
> > > > On Jul 22, 3:06 pm, Joseph Earl  wrote:
>
> > > > > No. I'm unsure as to what to use a WeakReference for exactly - as
> > > > > Romain Guy said above it is too weak for this purpose, but I think
> > > > > (hopefully Romain will correct me if I'm wrong) that a SoftReference
> > > > > could be suitable for this purpose.
>
> > > > > A ListView already does efficient management of your Views by
> > > > > recycling. This means that you must ensure the correct details are set
> > > > > in the view each time getView is called, even if you do not inflate a
> > > > > view or call findViewById that time. Recycling does not mean that the
> > > > > ListView caches all your items or their content.
>
> > > > > Suppose you had a list of 10 items, all of the same type but only 5
> > > > > will fit on the screen at a time. The ListView only really needs 5
> > > > > views to show the rows since the other 5 won't be visible.
> > > > > Thus at the top of the list the ListView might use 'View 1' for the
> > > > > first item, but scroll down to the bottom and 'View 1' would now
> > > > > contain item 6. As far as I understand it this is recycling.
>
> > > > > Recycling does not take care of the amount time of it takes to get
> > > > > content and set it to the view - thus if it takes a long time to get a
> > > > > piece of information and display it in a list item (such as
> > > > > downloading an image from the web), you will want to cache the result
> > > > > in a way that does not adversely affect memory usage (as much as
> > > > > possible). In this case you will also want to use a Thread or Async
> > > > > task to download/get the info off the UI thread.
>
> > > > > On Jul 22, 7:36 pm, GodsMoon  wrote:
>
> > > > > > So you'd only want to use WeakReference when you think your activity
> > > > > > might run out of memory?
> > > > > > But a list view already does efficient memory management for you
> > > > > > right?
>
> > > > > > You'd saying if I were create a large array or something like that
> > > > > > then it would be good to use WeakReference. right?
>
> > > > > > Thanks for the help guys,
> > > > > > David Shellabargerwww.nightshadelabs.com
>
> > > > > > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > > > > > You definitely do NOT want to use a WeakReference to cache 
> > > > > > > object. If
> > > > > > > you do so, as soon as your data is put in the cache and not used
> > > > > > > outside of the cache, it gets garbage collected.
>
> > > > > > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl 
> > > > > > >  wrote:
> > > > > > > > Suppose you had a long list of images. As the user scrolled 
> > > > > > > > down you
> > > > > > > > load the images from the net, and then display them.

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread DanH
" So you'd only want to use WeakReference when you think your activity
might run out of memory?"

Not exactly.  If you use poor programming techniques just about any
long-running operation can run out of memory.  WeakReference is an aid
to keep you from having to use much more complex techniques (like
reference chains) while still having "good" programming practices.

On Jul 22, 1:36 pm, GodsMoon  wrote:
> So you'd only want to use WeakReference when you think your activity
> might run out of memory?
> But a list view already does efficient memory management for you
> right?
>
> You'd saying if I were create a large array or something like that
> then it would be good to use WeakReference. right?
>
> Thanks for the help guys,
> David Shellabargerwww.nightshadelabs.com
>
> On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > You definitely do NOT want to use a WeakReference to cache object. If
> > you do so, as soon as your data is put in the cache and not used
> > outside of the cache, it gets garbage collected.
>
> > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  
> > wrote:
> > > Suppose you had a long list of images. As the user scrolled down you
> > > load the images from the net, and then display them.
> > > To avoid having to reload the images again if the user scrolls back
> > > up, you put the images in a cache (probably something like a
> > > Map)
>
> > > However because it is a long list you don't want to run into an out of
> > > memory situation if the user scrolls very far down and lots of images
> > > are put in the cache.
> > > So instead of storing the Drawables directly in the map, you create a
> > > Map> (although I would use SoftReference
> > > for the purpose described here).
> > > This means that if Android is going to encounter an out of memory
> > > situation it will clear all of the Soft/Weak references (and thus
> > > hopefully avoid running out of memory). You will have to load the
> > > images again since your cache has been cleared, but this is far better
> > > than your application running out of memory and crashing.
>
> > > So you do something like:
>
> > > // caching an image
> > > Map cache = new HashMap > > SoftReference>();
> > > cache.put("http://mysite.com/images/1.jpg";, new
> > > SoftReference.put(myDrawable));
>
> > > // retrieve an image
> > > if (cache.containsKey(url)) {
> > >   // looks like we have this image cached
> > >   Drawable drawable = cache.get(url).get();
> > >   if (drawable == null) {
> > >       // the softreference has been cleared by the GC, reload the
> > > image
> > >   } else {
> > >       // softreference is still valid, got our image
> > >   }
> > > }
>
> > > Essentially a weak reference is a weaker reference than a soft
> > > reference - the GC should free weak references to regain memory before
> > > soft references.
>
> > > I think that's (mostly) correct, hope it helps.
>
> > > On Jul 22, 6:48 pm, GodsMoon  wrote:
> > >> Google just posted a new blog post 
> > >> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > >> I understand the AsyncTask and I'm even using one in a list with
> > >> images already.
>
> > >> But I don't understand what a WeakReference is. I gather is is a
> > >> garbage collector directive, but I thought I didn't need to manage
> > >> garbage collection on Android.
>
> > >>http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > >> isn't as helpful as I was hoping it would be.
>
> > > --
> > > You received this message because you are subscribed to the Google
> > > Groups "Android Developers" group.
> > > To post to this group, send email to android-developers@googlegroups.com
> > > To unsubscribe from this group, send email to
> > > android-developers+unsubscr...@googlegroups.com
> > > For more options, visit this group at
> > >http://groups.google.com/group/android-developers?hl=en
>
> > --
> > Romain Guy
> > Android framework engineer
> > romain...@android.com
>
> > Note: please don't send private questions to me, as I don't have time
> > to provide private support.  All such questions should be posted on
> > public forums, where I and others can see and answer them

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Joseph Earl
Ah, you may well be.

On Jul 22, 10:26 pm, GodsMoon  wrote:
> Perhaps the difference was because I was declaring my view in the
> onCreate method instead of in the onPostExecute method of the
> AsyncTask?
>
> If I declare the view in my activity, maybe it gets GCed when my
> activity is killed, but in the blog post example he tries to declare
> it in the AsyncTask even though the activity is long gone.
>
> Am I on the right track here?
>
> David Shellabargerwww.nightshadelabs.com
>
> On Jul 22, 4:09 pm, Joseph Earl  wrote:
>
> > I am confused somewhat about the issue myself now. Hopefully someone
> > else it will clear it up once and for all.
>
> > On Jul 22, 9:01 pm, GodsMoon  wrote:
>
> > > I have done something like that and got a null pointer reference.
> > > I was starting a AsyncTask and if you backed out of the activity
> > > before the AsyncTask was finished I would get a null pointer when I
> > > tried to refer to the activities elements (force close).
> > > So I just check to see if the views are null first. I thought that if
> > > it returned null then it must have been GCed.
> > > But that's not the case?
>
> > > David Shellabargerwww.nightshadelabs.com
>
> > > On Jul 22, 3:49 pm, Joseph Earl  wrote:
>
> > > > When your UI activity is killed as far as I am aware the GC will
> > > > collect your Views. The problem is (I think) if the GC closes your UI
> > > > thread while the downloader is still running - in this case your
> > > > downloader thread maintains a reference to the ImageView so the GC
> > > > cannot collect it - hence memory leak - the downloader thread cannot
> > > > actually do anything to the ImageView since the UI thread no longer
> > > > exists.
> > > > Thus the downloader thread should only store a weak reference to the
> > > > ImageView so that if the UI thread is killed the GC may reclaim the
> > > > memory associated with the ImageView.
>
> > > > On Jul 22, 8:34 pm, GodsMoon  wrote:
>
> > > > > The blog post is confusing.
> > > > > "Note that this ImageView is stored as a WeakReference, so that a
> > > > > download in progress does not prevent a killed activity's ImageView
> > > > > from being garbage collected."
> > > > > I didn't know that would cause a memory leak. I thought the garbage
> > > > > collector would clean up ImageView if its activity gets killed.
> > > > > Am I wrong?
>
> > > > > David Shellabargerwww.nightshadelabs.com
>
> > > > > On Jul 22, 3:06 pm, Joseph Earl  wrote:
>
> > > > > > No. I'm unsure as to what to use a WeakReference for exactly - as
> > > > > > Romain Guy said above it is too weak for this purpose, but I think
> > > > > > (hopefully Romain will correct me if I'm wrong) that a SoftReference
> > > > > > could be suitable for this purpose.
>
> > > > > > A ListView already does efficient management of your Views by
> > > > > > recycling. This means that you must ensure the correct details are 
> > > > > > set
> > > > > > in the view each time getView is called, even if you do not inflate 
> > > > > > a
> > > > > > view or call findViewById that time. Recycling does not mean that 
> > > > > > the
> > > > > > ListView caches all your items or their content.
>
> > > > > > Suppose you had a list of 10 items, all of the same type but only 5
> > > > > > will fit on the screen at a time. The ListView only really needs 5
> > > > > > views to show the rows since the other 5 won't be visible.
> > > > > > Thus at the top of the list the ListView might use 'View 1' for the
> > > > > > first item, but scroll down to the bottom and 'View 1' would now
> > > > > > contain item 6. As far as I understand it this is recycling.
>
> > > > > > Recycling does not take care of the amount time of it takes to get
> > > > > > content and set it to the view - thus if it takes a long time to 
> > > > > > get a
> > > > > > piece of information and display it in a list item (such as
> > > > > > downloading an image from the web), you will want to cache the 
> > > > > > result
> > > > > > in a way that does not adversely affect memory usage (as much as
> > > > > > possible). In this case you will also want to use a Thread or Async
> > > > > > task to download/get the info off the UI thread.
>
> > > > > > On Jul 22, 7:36 pm, GodsMoon  wrote:
>
> > > > > > > So you'd only want to use WeakReference when you think your 
> > > > > > > activity
> > > > > > > might run out of memory?
> > > > > > > But a list view already does efficient memory management for you
> > > > > > > right?
>
> > > > > > > You'd saying if I were create a large array or something like that
> > > > > > > then it would be good to use WeakReference. right?
>
> > > > > > > Thanks for the help guys,
> > > > > > > David Shellabargerwww.nightshadelabs.com
>
> > > > > > > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > > > > > > You definitely do NOT want to use a WeakReference to cache 
> > > > > > > > object. If
> > > > > > > > you do so, as soon as your data is put in the cache and not used
> > > > > > > > outside of

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread fadden
On Jul 22, 12:57 pm, Kostya Vasilyev  wrote:
> I remember seeing somewhere that Dalvik didn't initially support Soft /
> Weak references, and this was implemented at some point.
>
> Can someone clarify: starting with what version of Dalvik / Android
> these are available?

Soft, weak, and phantom references have always been available in
Dalvik.

JNI "weak global" references are a recent addition, but very few
people have reason to use those.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread DanH
It's very likely that the garbage collector has gone through several
turns of the crank trying to get these correct.  The weak reference
stuff is very hard to get right the first time, from a GC perspective.

On Jul 22, 6:25 pm, fadden  wrote:
> On Jul 22, 12:57 pm, Kostya Vasilyev  wrote:
>
> > I remember seeing somewhere that Dalvik didn't initially support Soft /
> > Weak references, and this was implemented at some point.
>
> > Can someone clarify: starting with what version of Dalvik / Android
> > these are available?
>
> Soft, weak, and phantom references have always been available in
> Dalvik.
>
> JNI "weak global" references are a recent addition, but very few
> people have reason to use those.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Indicator Veritatis
Look: I know it is tedious reading, but the reference given earlier in
this thread, to Sun's own documentation of the class, answers your
question concerning when to use a WeakReference -- as well as when to
use the other kinds. Then there are IBM Java articles/tutorials on the
same topic (e.g. http://www.ibm.com/developerworks/library/j-refs/).

Since it is answered there, it should be clear that this is a Java
question, not an Android one. So why are you belaboring the point
here?

On Jul 22, 12:06 pm, Joseph Earl  wrote:
> No. I'm unsure as to what to use a WeakReference for exactly - as
> Romain Guy said above it is too weak for this purpose, but I think
> (hopefully Romain will correct me if I'm wrong) that a SoftReference
> could be suitable for this purpose.
>
> A ListView already does efficient management of your Views by
> recycling. This means that you must ensure the correct details are set
> in the view each time getView is called, even if you do not inflate a
> view or call findViewById that time. Recycling does not mean that the
> ListView caches all your items or their content.
>
> Suppose you had a list of 10 items, all of the same type but only 5
> will fit on the screen at a time. The ListView only really needs 5
> views to show the rows since the other 5 won't be visible.
> Thus at the top of the list the ListView might use 'View 1' for the
> first item, but scroll down to the bottom and 'View 1' would now
> contain item 6. As far as I understand it this is recycling.
>
> Recycling does not take care of the amount time of it takes to get
> content and set it to the view - thus if it takes a long time to get a
> piece of information and display it in a list item (such as
> downloading an image from the web), you will want to cache the result
> in a way that does not adversely affect memory usage (as much as
> possible). In this case you will also want to use a Thread or Async
> task to download/get the info off the UI thread.
>
> On Jul 22, 7:36 pm, GodsMoon  wrote:> So you'd only want 
> to use WeakReference when you think your activity
> > might run out of memory?
> > But a list view already does efficient memory management for you
> > right?
>
> > You'd saying if I were create a large array or something like that
> > then it would be good to use WeakReference. right?
>
> > Thanks for the help guys,
> > David Shellabargerwww.nightshadelabs.com
>
> > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > You definitely do NOT want to use a WeakReference to cache object. If
> > > you do so, as soon as your data is put in the cache and not used
> > > outside of the cache, it gets garbage collected.
>
> > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  
> > > wrote:
> > > > Suppose you had a long list of images. As the user scrolled down you
> > > > load the images from the net, and then display them.
> > > > To avoid having to reload the images again if the user scrolls back
> > > > up, you put the images in a cache (probably something like a
> > > > Map)
>
> > > > However because it is a long list you don't want to run into an out of
> > > > memory situation if the user scrolls very far down and lots of images
> > > > are put in the cache.
> > > > So instead of storing the Drawables directly in the map, you create a
> > > > Map> (although I would use SoftReference
> > > > for the purpose described here).
> > > > This means that if Android is going to encounter an out of memory
> > > > situation it will clear all of the Soft/Weak references (and thus
> > > > hopefully avoid running out of memory). You will have to load the
> > > > images again since your cache has been cleared, but this is far better
> > > > than your application running out of memory and crashing.
>
> > > > So you do something like:
>
> > > > // caching an image
> > > > Map cache = new HashMap > > > SoftReference>();
> > > > cache.put("http://mysite.com/images/1.jpg";, new
> > > > SoftReference.put(myDrawable));
>
> > > > // retrieve an image
> > > > if (cache.containsKey(url)) {
> > > >   // looks like we have this image cached
> > > >   Drawable drawable = cache.get(url).get();
> > > >   if (drawable == null) {
> > > >       // the softreference has been cleared by the GC, reload the
> > > > image
> > > >   } else {
> > > >       // softreference is still valid, got our image
> > > >   }
> > > > }
>
> > > > Essentially a weak reference is a weaker reference than a soft
> > > > reference - the GC should free weak references to regain memory before
> > > > soft references.
>
> > > > I think that's (mostly) correct, hope it helps.
>
> > > > On Jul 22, 6:48 pm, GodsMoon  wrote:
> > > >> Google just posted a new blog post 
> > > >> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > > >> I understand the AsyncTask and I'm even using one in a list with
> > > >> images already.
>
> > > >> But I don't understand what a WeakReference is. I gather is is a
> > > >> garbage collector directive, but I thought I 

[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Matt
On Jul 22, 4:09 pm, Joseph Earl  wrote:
> I am confused somewhat about the issue myself now. Hopefully someone
> else it will clear it up once and for all.
>
A great explanation is here: http://jnb.ociweb.com/jnb/archive/jnbJune2000.html

Use weak references when you are creating a reference to an object
somewhere (usually a collection or another thread) but you don't want
that reference to prevent it from being GC'd, or "deleted".  The
reason they use weak references in the example you looked at is that
they are creating a separate thread from the main app thread.

If the main thread doesn't need those objects any more, they would
normally be deleted.  But if you've got a background thread going,
with references to those objects, then they won't be deleted until the
background thread is finished.  Since, in the given example's case,
the background threads are "useless" without the main thread, we don't
want the background thread to prevent those objects from being
deleted, so they are created with weak references.

NOTE: If you never used weak references, just regular "strong"
references, in the scenario with a main app thread and a background
thread, then everything would still work.  When the main thread ends,
but the background thread is still going, the background thread's
objects aren't deleted yet.  But when the background thread dies, then
they are deleted.  What you gain by using weak references is just a
quicker way to delete those objects on the background thread when the
main thread ends. I would guess that, in a typical "background
download" scenario, by using weak references instead of regular
"strong" references all you're doing is keeping the memory from being
reclaimed for at most 30 seconds.  The amount of time depends on
what's going on in the background, and the amount of memory depends on
your app.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-22 Thread Indicator Veritatis
You left out something very important: the code hidden under "//
reload the image" must not assume that it is not itself interrupted by
yet another call to the garbage collector. That is, instead of simply
continuing to use the soft/weak reference, it should make a strong
reference to the same object, allowing this latter reference to either
go out of scope or be set to null when it is done.

But if we are making this strong reference, what was the point of
using the weak/soft reference in the first place? Ah, that is the
tricky thing about using them. Depending on when you can make and
release the strong reference, they might not buy you much; they might
not buy you anything at all. That is why they are not recommended for
much outside of caches and normalized mappings.

On Jul 22, 11:07 am, Joseph Earl  wrote:
> Suppose you had a long list of images. As the user scrolled down you
> load the images from the net, and then display them.
> To avoid having to reload the images again if the user scrolls back
> up, you put the images in a cache (probably something like a
> Map)
>
> However because it is a long list you don't want to run into an out of
> memory situation if the user scrolls very far down and lots of images
> are put in the cache.
> So instead of storing the Drawables directly in the map, you create a
> Map> (although I would use SoftReference
> for the purpose described here).
> This means that if Android is going to encounter an out of memory
> situation it will clear all of the Soft/Weak references (and thus
> hopefully avoid running out of memory). You will have to load the
> images again since your cache has been cleared, but this is far better
> than your application running out of memory and crashing.
>
> So you do something like:
>
> // caching an image
> Map cache = new HashMap SoftReference>();
> cache.put("http://mysite.com/images/1.jpg";, new
> SoftReference.put(myDrawable));
>
> // retrieve an image
> if (cache.containsKey(url)) {
>    // looks like we have this image cached
>    Drawable drawable = cache.get(url).get();
>    if (drawable == null) {
>        // the softreference has been cleared by the GC, reload the
> image
>    } else {
>        // softreference is still valid, got our image
>    }
>
> }
>
> Essentially a weak reference is a weaker reference than a soft
> reference - the GC should free weak references to regain memory before
> soft references.
>
> I think that's (mostly) correct, hope it helps.
>
> On Jul 22, 6:48 pm, GodsMoon  wrote:
>
> > Google just posted a new blog post 
> > onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > I understand the AsyncTask and I'm even using one in a list with
> > images already.
>
> > But I don't understand what a WeakReference is. I gather is is a
> > garbage collector directive, but I thought I didn't need to manage
> > garbage collection on Android.
>
> >http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > isn't as helpful as I was hoping it would be.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-23 Thread DanH
Yes, you must "guard" any use of the WeakReference by taking the ref()
of it, testing that for null, and then proceeding to use the result of
the ref() if not null.  The size of the "guarded" sections is up to
the programmer -- if too large then the object will never get deleted,
if too small then the code gets chopped up.

On Jul 23, 1:37 am, Indicator Veritatis  wrote:
> You left out something very important: the code hidden under "//
> reload the image" must not assume that it is not itself interrupted by
> yet another call to the garbage collector. That is, instead of simply
> continuing to use the soft/weak reference, it should make a strong
> reference to the same object, allowing this latter reference to either
> go out of scope or be set to null when it is done.
>
> But if we are making this strong reference, what was the point of
> using the weak/soft reference in the first place? Ah, that is the
> tricky thing about using them. Depending on when you can make and
> release the strong reference, they might not buy you much; they might
> not buy you anything at all. That is why they are not recommended for
> much outside of caches and normalized mappings.
>
> On Jul 22, 11:07 am, Joseph Earl  wrote:
>
> > Suppose you had a long list of images. As the user scrolled down you
> > load the images from the net, and then display them.
> > To avoid having to reload the images again if the user scrolls back
> > up, you put the images in a cache (probably something like a
> > Map)
>
> > However because it is a long list you don't want to run into an out of
> > memory situation if the user scrolls very far down and lots of images
> > are put in the cache.
> > So instead of storing the Drawables directly in the map, you create a
> > Map> (although I would use SoftReference
> > for the purpose described here).
> > This means that if Android is going to encounter an out of memory
> > situation it will clear all of the Soft/Weak references (and thus
> > hopefully avoid running out of memory). You will have to load the
> > images again since your cache has been cleared, but this is far better
> > than your application running out of memory and crashing.
>
> > So you do something like:
>
> > // caching an image
> > Map cache = new HashMap > SoftReference>();
> > cache.put("http://mysite.com/images/1.jpg";, new
> > SoftReference.put(myDrawable));
>
> > // retrieve an image
> > if (cache.containsKey(url)) {
> >    // looks like we have this image cached
> >    Drawable drawable = cache.get(url).get();
> >    if (drawable == null) {
> >        // the softreference has been cleared by the GC, reload the
> > image
> >    } else {
> >        // softreference is still valid, got our image
> >    }
>
> > }
>
> > Essentially a weak reference is a weaker reference than a soft
> > reference - the GC should free weak references to regain memory before
> > soft references.
>
> > I think that's (mostly) correct, hope it helps.
>
> > On Jul 22, 6:48 pm, GodsMoon  wrote:
>
> > > Google just posted a new blog post 
> > > onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > > I understand the AsyncTask and I'm even using one in a list with
> > > images already.
>
> > > But I don't understand what a WeakReference is. I gather is is a
> > > garbage collector directive, but I thought I didn't need to manage
> > > garbage collection on Android.
>
> > >http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > > isn't as helpful as I was hoping it would be.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-23 Thread GodsMoon
I think the difference in the code I've written in the past was I was
referring to a window progress bar and not an independent view in the
onPostExecute.
That's why I was getting a Null Pointer when the activity was killed.

I'm starting to get a grasp on this stuff. Clearly I don't know how
the GC works.

Thanks for the links guys. I'll keep reading.

David Shellabarger
www.nightshadelabs.com

On Jul 22, 5:26 pm, GodsMoon  wrote:
> Perhaps the difference was because I was declaring my view in the
> onCreate method instead of in the onPostExecute method of the
> AsyncTask?
>
> If I declare the view in my activity, maybe it gets GCed when my
> activity is killed, but in the blog post example he tries to declare
> it in the AsyncTask even though the activity is long gone.
>
> Am I on the right track here?
>
> David Shellabargerwww.nightshadelabs.com
>
> On Jul 22, 4:09 pm, Joseph Earl  wrote:
>
>
>
> > I am confused somewhat about the issue myself now. Hopefully someone
> > else it will clear it up once and for all.
>
> > On Jul 22, 9:01 pm, GodsMoon  wrote:
>
> > > I have done something like that and got a null pointer reference.
> > > I was starting a AsyncTask and if you backed out of the activity
> > > before the AsyncTask was finished I would get a null pointer when I
> > > tried to refer to the activities elements (force close).
> > > So I just check to see if the views are null first. I thought that if
> > > it returned null then it must have been GCed.
> > > But that's not the case?
>
> > > David Shellabargerwww.nightshadelabs.com
>
> > > On Jul 22, 3:49 pm, Joseph Earl  wrote:
>
> > > > When your UI activity is killed as far as I am aware the GC will
> > > > collect your Views. The problem is (I think) if the GC closes your UI
> > > > thread while the downloader is still running - in this case your
> > > > downloader thread maintains a reference to the ImageView so the GC
> > > > cannot collect it - hence memory leak - the downloader thread cannot
> > > > actually do anything to the ImageView since the UI thread no longer
> > > > exists.
> > > > Thus the downloader thread should only store a weak reference to the
> > > > ImageView so that if the UI thread is killed the GC may reclaim the
> > > > memory associated with the ImageView.
>
> > > > On Jul 22, 8:34 pm, GodsMoon  wrote:
>
> > > > > The blog post is confusing.
> > > > > "Note that this ImageView is stored as a WeakReference, so that a
> > > > > download in progress does not prevent a killed activity's ImageView
> > > > > from being garbage collected."
> > > > > I didn't know that would cause a memory leak. I thought the garbage
> > > > > collector would clean up ImageView if its activity gets killed.
> > > > > Am I wrong?
>
> > > > > David Shellabargerwww.nightshadelabs.com
>
> > > > > On Jul 22, 3:06 pm, Joseph Earl  wrote:
>
> > > > > > No. I'm unsure as to what to use a WeakReference for exactly - as
> > > > > > Romain Guy said above it is too weak for this purpose, but I think
> > > > > > (hopefully Romain will correct me if I'm wrong) that a SoftReference
> > > > > > could be suitable for this purpose.
>
> > > > > > A ListView already does efficient management of your Views by
> > > > > > recycling. This means that you must ensure the correct details are 
> > > > > > set
> > > > > > in the view each time getView is called, even if you do not inflate 
> > > > > > a
> > > > > > view or call findViewById that time. Recycling does not mean that 
> > > > > > the
> > > > > > ListView caches all your items or their content.
>
> > > > > > Suppose you had a list of 10 items, all of the same type but only 5
> > > > > > will fit on the screen at a time. The ListView only really needs 5
> > > > > > views to show the rows since the other 5 won't be visible.
> > > > > > Thus at the top of the list the ListView might use 'View 1' for the
> > > > > > first item, but scroll down to the bottom and 'View 1' would now
> > > > > > contain item 6. As far as I understand it this is recycling.
>
> > > > > > Recycling does not take care of the amount time of it takes to get
> > > > > > content and set it to the view - thus if it takes a long time to 
> > > > > > get a
> > > > > > piece of information and display it in a list item (such as
> > > > > > downloading an image from the web), you will want to cache the 
> > > > > > result
> > > > > > in a way that does not adversely affect memory usage (as much as
> > > > > > possible). In this case you will also want to use a Thread or Async
> > > > > > task to download/get the info off the UI thread.
>
> > > > > > On Jul 22, 7:36 pm, GodsMoon  wrote:
>
> > > > > > > So you'd only want to use WeakReference when you think your 
> > > > > > > activity
> > > > > > > might run out of memory?
> > > > > > > But a list view already does efficient memory management for you
> > > > > > > right?
>
> > > > > > > You'd saying if I were create a large array or something like that
> > > > > > > then it would be good to use WeakRe

[android-developers] Re: What is a WeakReference?

2010-07-23 Thread Matt Quigley
On Jul 23, 2:37 am, Indicator Veritatis  wrote:
> You left out something very important: the code hidden under "//
> reload the image" must not assume that it is not itself interrupted by
> yet another call to the garbage collector. That is, instead of simply
> continuing to use the soft/weak reference, it should make a strong
> reference to the same object, allowing this latter reference to either
> go out of scope or be set to null when it is done.

You are referring to the code that Joseph Earl wrote above.  That code
snippet is NOT a proper way to use weak references; that cache should
be using soft references.

On the other hand, in the example blog post referred to by the OP,
which uses weak references, that IS a proper way to use weak
references.  The main Activity already has a strong reference to the
objects.  The secondary thread does not need to create a strong
reference; in fact, that would make the weak reference useless.

> But if we are making this strong reference, what was the point of
> using the weak/soft reference in the first place? Ah, that is the
> tricky thing about using them. Depending on when you can make and
> release the strong reference, they might not buy you much; they might
> not buy you anything at all. That is why they are not recommended for
> much outside of caches and normalized mappings.

You are referring to a soft reference, not a weak reference.  Soft
references are good for caches.  Weak references are definitely
recommended for the idea given in the article, where the main thread
has a strong reference, and the background thread has a weak
reference.  That way if the main thread is killed (i.e. the app is
finished), if the background thread is still running then it won't
prevent the weakly referenced objects from being destroyed.


I also hate to throw this bit of information into the mix, but it
should be known that Android will kill your process, and hence
background threads anyways, when all your main threads have been
destroyed (i.e. all your activities are finished, and there aren't any
services running).  This means that, even if you did have a background
thread running, it would be killed, implying that weak references
wouldn't help because everything is going to get killed anyways.  That
being said, there are still circumstances where the weak references
matter: just because one activity is finished, doesn't mean all of
your app's activities are necessarily finished.  So it would be good
if you went from your main activity into another sub-activity which
began a download.  But then the user presses back, because they don't
want to bother waiting on the download.  In that case your main
activity is still alive, but the background thread is working on the
sub-activity that was already finished.  If that background thread had
weak references, then that background thread would no longer be
holding on to the resources of the sub-activity with strong
references, and the system could GC those resources already, before
the background thread dies.

-Matt

-Matt

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-23 Thread DanH
" The main Activity already has a strong reference to the
objects.  The secondary thread does not need to create a strong
reference; in fact, that would make the weak reference useless."

It should be noted, though, that one shouldn't use weak references (or
soft ones) willy-nilly.  A weak/soft reference is more expensive in
terms of both your program execution time and GC overhead than a
normal reference (plus of course using them is more complicated), so
they should only be used where the behavior of allowing an object to
"be deleted out from under you" is the desired behavior.  If, eg, you
have a secondary thread that will be killed when the primary one goes
away, using the weak reference between the two is just useless
overhead.

This is not like some C++ paradigms where there is only one "owner"
pointer and multiple copies.

On Jul 23, 10:25 am, Matt Quigley  wrote:
> On Jul 23, 2:37 am, Indicator Veritatis  wrote:
>
> > You left out something very important: the code hidden under "//
> > reload the image" must not assume that it is not itself interrupted by
> > yet another call to the garbage collector. That is, instead of simply
> > continuing to use the soft/weak reference, it should make a strong
> > reference to the same object, allowing this latter reference to either
> > go out of scope or be set to null when it is done.
>
> You are referring to the code that Joseph Earl wrote above.  That code
> snippet is NOT a proper way to use weak references; that cache should
> be using soft references.
>
> On the other hand, in the example blog post referred to by the OP,
> which uses weak references, that IS a proper way to use weak
> references.  The main Activity already has a strong reference to the
> objects.  The secondary thread does not need to create a strong
> reference; in fact, that would make the weak reference useless.
>
> > But if we are making this strong reference, what was the point of
> > using the weak/soft reference in the first place? Ah, that is the
> > tricky thing about using them. Depending on when you can make and
> > release the strong reference, they might not buy you much; they might
> > not buy you anything at all. That is why they are not recommended for
> > much outside of caches and normalized mappings.
>
> You are referring to a soft reference, not a weak reference.  Soft
> references are good for caches.  Weak references are definitely
> recommended for the idea given in the article, where the main thread
> has a strong reference, and the background thread has a weak
> reference.  That way if the main thread is killed (i.e. the app is
> finished), if the background thread is still running then it won't
> prevent the weakly referenced objects from being destroyed.
>
> I also hate to throw this bit of information into the mix, but it
> should be known that Android will kill your process, and hence
> background threads anyways, when all your main threads have been
> destroyed (i.e. all your activities are finished, and there aren't any
> services running).  This means that, even if you did have a background
> thread running, it would be killed, implying that weak references
> wouldn't help because everything is going to get killed anyways.  That
> being said, there are still circumstances where the weak references
> matter: just because one activity is finished, doesn't mean all of
> your app's activities are necessarily finished.  So it would be good
> if you went from your main activity into another sub-activity which
> began a download.  But then the user presses back, because they don't
> want to bother waiting on the download.  In that case your main
> activity is still alive, but the background thread is working on the
> sub-activity that was already finished.  If that background thread had
> weak references, then that background thread would no longer be
> holding on to the resources of the sub-activity with strong
> references, and the system could GC those resources already, before
> the background thread dies.
>
> -Matt
>
> -Matt

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-23 Thread Joseph Earl
Thanks for clearing it up somewhat.

On Jul 23, 4:25 pm, Matt Quigley  wrote:
> On Jul 23, 2:37 am, Indicator Veritatis  wrote:
>
> > You left out something very important: the code hidden under "//
> > reload the image" must not assume that it is not itself interrupted by
> > yet another call to the garbage collector. That is, instead of simply
> > continuing to use the soft/weak reference, it should make a strong
> > reference to the same object, allowing this latter reference to either
> > go out of scope or be set to null when it is done.
>
> You are referring to the code that Joseph Earl wrote above.  That code
> snippet is NOT a proper way to use weak references; that cache should
> be using soft references.
>
> On the other hand, in the example blog post referred to by the OP,
> which uses weak references, that IS a proper way to use weak
> references.  The main Activity already has a strong reference to the
> objects.  The secondary thread does not need to create a strong
> reference; in fact, that would make the weak reference useless.
>
> > But if we are making this strong reference, what was the point of
> > using the weak/soft reference in the first place? Ah, that is the
> > tricky thing about using them. Depending on when you can make and
> > release the strong reference, they might not buy you much; they might
> > not buy you anything at all. That is why they are not recommended for
> > much outside of caches and normalized mappings.
>
> You are referring to a soft reference, not a weak reference.  Soft
> references are good for caches.  Weak references are definitely
> recommended for the idea given in the article, where the main thread
> has a strong reference, and the background thread has a weak
> reference.  That way if the main thread is killed (i.e. the app is
> finished), if the background thread is still running then it won't
> prevent the weakly referenced objects from being destroyed.
>
> I also hate to throw this bit of information into the mix, but it
> should be known that Android will kill your process, and hence
> background threads anyways, when all your main threads have been
> destroyed (i.e. all your activities are finished, and there aren't any
> services running).  This means that, even if you did have a background
> thread running, it would be killed, implying that weak references
> wouldn't help because everything is going to get killed anyways.  That
> being said, there are still circumstances where the weak references
> matter: just because one activity is finished, doesn't mean all of
> your app's activities are necessarily finished.  So it would be good
> if you went from your main activity into another sub-activity which
> began a download.  But then the user presses back, because they don't
> want to bother waiting on the download.  In that case your main
> activity is still alive, but the background thread is working on the
> sub-activity that was already finished.  If that background thread had
> weak references, then that background thread would no longer be
> holding on to the resources of the sub-activity with strong
> references, and the system could GC those resources already, before
> the background thread dies.
>
> -Matt
>
> -Matt

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-24 Thread AlanLawrence
Sorry to go back to this:

On Jul 22, 7:26 pm, Romain Guy  wrote:
> You definitely do NOT want to use a WeakReference to cache object. If
> you do so, as soon as your data is put in the cache and not used
> outside of the cache, it gets garbage collected.

as I hope I'm merely nitpicking, but - isn't the idea that the object
*may* be GC'd anytime after/while you've discarded the last strong
(non-weak) reference to it, _perhaps_ arbitrarily later? (I say
"while" as until it is GC'd, you could make it strongly reachable
again by calling ref() on a Weak/SoftReference). I mean, I'd _guess_
it's more likely the GC will run if/when you do a lot of allocation,
and/or have a lot of idle time, or some such, tho obviously this is
not a requirement/ in the spec! Or does Dalvik use a refcounting-plus-
cycle-detection scheme, a la Bacon's "Recycler", or something like
that?

--Alan

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-24 Thread Joseph Earl
I did say '(although I would use SoftReference for the purpose
described here).' But it wasn't clear enough I agree (and because I
admittedly wasn't sure enough about the differences)

On Jul 23, 4:25 pm, Matt Quigley  wrote:
> On Jul 23, 2:37 am, Indicator Veritatis  wrote:
>
> > You left out something very important: the code hidden under "//
> > reload the image" must not assume that it is not itself interrupted by
> > yet another call to the garbage collector. That is, instead of simply
> > continuing to use the soft/weak reference, it should make a strong
> > reference to the same object, allowing this latter reference to either
> > go out of scope or be set to null when it is done.
>
> You are referring to the code that Joseph Earl wrote above.  That code
> snippet is NOT a proper way to use weak references; that cache should
> be using soft references.
>
> On the other hand, in the example blog post referred to by the OP,
> which uses weak references, that IS a proper way to use weak
> references.  The main Activity already has a strong reference to the
> objects.  The secondary thread does not need to create a strong
> reference; in fact, that would make the weak reference useless.
>
> > But if we are making this strong reference, what was the point of
> > using the weak/soft reference in the first place? Ah, that is the
> > tricky thing about using them. Depending on when you can make and
> > release the strong reference, they might not buy you much; they might
> > not buy you anything at all. That is why they are not recommended for
> > much outside of caches and normalized mappings.
>
> You are referring to a soft reference, not a weak reference.  Soft
> references are good for caches.  Weak references are definitely
> recommended for the idea given in the article, where the main thread
> has a strong reference, and the background thread has a weak
> reference.  That way if the main thread is killed (i.e. the app is
> finished), if the background thread is still running then it won't
> prevent the weakly referenced objects from being destroyed.
>
> I also hate to throw this bit of information into the mix, but it
> should be known that Android will kill your process, and hence
> background threads anyways, when all your main threads have been
> destroyed (i.e. all your activities are finished, and there aren't any
> services running).  This means that, even if you did have a background
> thread running, it would be killed, implying that weak references
> wouldn't help because everything is going to get killed anyways.  That
> being said, there are still circumstances where the weak references
> matter: just because one activity is finished, doesn't mean all of
> your app's activities are necessarily finished.  So it would be good
> if you went from your main activity into another sub-activity which
> began a download.  But then the user presses back, because they don't
> want to bother waiting on the download.  In that case your main
> activity is still alive, but the background thread is working on the
> sub-activity that was already finished.  If that background thread had
> weak references, then that background thread would no longer be
> holding on to the resources of the sub-activity with strong
> references, and the system could GC those resources already, before
> the background thread dies.
>
> -Matt
>
> -Matt

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-24 Thread DanH
Yeah, a weak reference is fair game as soon as there are no "strong"
references to the object.  A soft reference is kept until it's "aged"
a little.  Different platforms have different algorithms for "aging
out" soft references, but the idea is to let them persist for a few GC
cycles at least.

On Jul 24, 4:56 pm, Agus  wrote:
> GC can reclaim WeakReference even memory is still plenty, but
> SoftReferences will only be cleared when the system is just about to
> starve out of memory..
>
> On Sat, Jul 24, 2010 at 2:25 PM, Joseph Earl  wrote:
> > I did say '(although I would use SoftReference for the purpose
> > described here).' But it wasn't clear enough I agree (and because I
> > admittedly wasn't sure enough about the differences)
>
> > On Jul 23, 4:25 pm, Matt Quigley  wrote:
> >> On Jul 23, 2:37 am, Indicator Veritatis  wrote:
>
> >> > You left out something very important: the code hidden under "//
> >> > reload the image" must not assume that it is not itself interrupted by
> >> > yet another call to the garbage collector. That is, instead of simply
> >> > continuing to use the soft/weak reference, it should make a strong
> >> > reference to the same object, allowing this latter reference to either
> >> > go out of scope or be set to null when it is done.
>
> >> You are referring to the code that Joseph Earl wrote above.  That code
> >> snippet is NOT a proper way to use weak references; that cache should
> >> be using soft references.
>
> >> On the other hand, in the example blog post referred to by the OP,
> >> which uses weak references, that IS a proper way to use weak
> >> references.  The main Activity already has a strong reference to the
> >> objects.  The secondary thread does not need to create a strong
> >> reference; in fact, that would make the weak reference useless.
>
> >> > But if we are making this strong reference, what was the point of
> >> > using the weak/soft reference in the first place? Ah, that is the
> >> > tricky thing about using them. Depending on when you can make and
> >> > release the strong reference, they might not buy you much; they might
> >> > not buy you anything at all. That is why they are not recommended for
> >> > much outside of caches and normalized mappings.
>
> >> You are referring to a soft reference, not a weak reference.  Soft
> >> references are good for caches.  Weak references are definitely
> >> recommended for the idea given in the article, where the main thread
> >> has a strong reference, and the background thread has a weak
> >> reference.  That way if the main thread is killed (i.e. the app is
> >> finished), if the background thread is still running then it won't
> >> prevent the weakly referenced objects from being destroyed.
>
> >> I also hate to throw this bit of information into the mix, but it
> >> should be known that Android will kill your process, and hence
> >> background threads anyways, when all your main threads have been
> >> destroyed (i.e. all your activities are finished, and there aren't any
> >> services running).  This means that, even if you did have a background
> >> thread running, it would be killed, implying that weak references
> >> wouldn't help because everything is going to get killed anyways.  That
> >> being said, there are still circumstances where the weak references
> >> matter: just because one activity is finished, doesn't mean all of
> >> your app's activities are necessarily finished.  So it would be good
> >> if you went from your main activity into another sub-activity which
> >> began a download.  But then the user presses back, because they don't
> >> want to bother waiting on the download.  In that case your main
> >> activity is still alive, but the background thread is working on the
> >> sub-activity that was already finished.  If that background thread had
> >> weak references, then that background thread would no longer be
> >> holding on to the resources of the sub-activity with strong
> >> references, and the system could GC those resources already, before
> >> the background thread dies.
>
> >> -Matt
>
> >> -Matt
>
> > --
> > You received this message because you are subscribed to the Google
> > Groups "Android Developers" group.
> > To post to this group, send email to android-developers@googlegroups.com
> > To unsubscribe from this group, send email to
> > android-developers+unsubscr...@googlegroups.com
> > For more options, visit this group at
> >http://groups.google.com/group/android-developers?hl=en

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-25 Thread Indicator Veritatis
You are correct. My wording did not make it clear: soft references are
useful for "memory-sensitive" caches, weak references for
canonicalized mappings.

But as you point out, in the weak reference example that started this
thread, weak references really do not buy you much, since the memory
is going to get GC'd when the process is killed, anyway. So only in
yet rarer cases, when that moment is too long postponed, will weak
references be worth the effort.

On Jul 23, 8:25 am, Matt Quigley  wrote:
> On Jul 23, 2:37 am, Indicator Veritatis  wrote:
>
> > You left out something very important: the code hidden under "//
> > reload the image" must not assume that it is not itself interrupted by
> > yet another call to the garbage collector. That is, instead of simply
> > continuing to use the soft/weak reference, it should make a strong
> > reference to the same object, allowing this latter reference to either
> > go out of scope or be set to null when it is done.
>
> You are referring to the code that Joseph Earl wrote above.  That code
> snippet is NOT a proper way to use weak references; that cache should
> be using soft references.
>
> On the other hand, in the example blog post referred to by the OP,
> which uses weak references, that IS a proper way to use weak
> references.  The main Activity already has a strong reference to the
> objects.  The secondary thread does not need to create a strong
> reference; in fact, that would make the weak reference useless.
>
> > But if we are making this strong reference, what was the point of
> > using the weak/soft reference in the first place? Ah, that is the
> > tricky thing about using them. Depending on when you can make and
> > release the strong reference, they might not buy you much; they might
> > not buy you anything at all. That is why they are not recommended for
> > much outside of caches and normalized mappings.
>
> You are referring to a soft reference, not a weak reference.  Soft
> references are good for caches.  Weak references are definitely
> recommended for the idea given in the article, where the main thread
> has a strong reference, and the background thread has a weak
> reference.  That way if the main thread is killed (i.e. the app is
> finished), if the background thread is still running then it won't
> prevent the weakly referenced objects from being destroyed.
>
> I also hate to throw this bit of information into the mix, but it
> should be known that Android will kill your process, and hence
> background threads anyways, when all your main threads have been
> destroyed (i.e. all your activities are finished, and there aren't any
> services running).  This means that, even if you did have a background
> thread running, it would be killed, implying that weak references
> wouldn't help because everything is going to get killed anyways.  That
> being said, there are still circumstances where the weak references
> matter: just because one activity is finished, doesn't mean all of
> your app's activities are necessarily finished.  So it would be good
> if you went from your main activity into another sub-activity which
> began a download.  But then the user presses back, because they don't
> want to bother waiting on the download.  In that case your main
> activity is still alive, but the background thread is working on the
> sub-activity that was already finished.  If that background thread had
> weak references, then that background thread would no longer be
> holding on to the resources of the sub-activity with strong
> references, and the system could GC those resources already, before
> the background thread dies.
>
> -Matt
>
> -Matt

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-25 Thread Indicator Veritatis
As the author of the IBM Developerworks article I referenced mentions,
that is not good enough. The Garbage Collector runs on a different
thread, you have no control over when it will be called. It is quite
possible that just after you test for null, the GC is called, and it
is no longer valid. Not likely, but possible.

If instead you create a strong reference and use that, discarding it
when done, then you have shut the door on a really nasty transient
bug.

Or perhaps the version of 'ref()' you found did this for you? What
package did you find it it?

On Jul 23, 5:21 am, DanH  wrote:
> Yes, you must "guard" any use of the WeakReference by taking the ref()
> of it, testing that for null, and then proceeding to use the result of
> the ref() if not null.  The size of the "guarded" sections is up to
> the programmer -- if too large then the object will never get deleted,
> if too small then the code gets chopped up.
>
> On Jul 23, 1:37 am, Indicator Veritatis  wrote:
>
> > You left out something very important: the code hidden under "//
> > reload the image" must not assume that it is not itself interrupted by
> > yet another call to the garbage collector. That is, instead of simply
> > continuing to use the soft/weak reference, it should make a strong
> > reference to the same object, allowing this latter reference to either
> > go out of scope or be set to null when it is done.
>
> > But if we are making this strong reference, what was the point of
> > using the weak/soft reference in the first place? Ah, that is the
> > tricky thing about using them. Depending on when you can make and
> > release the strong reference, they might not buy you much; they might
> > not buy you anything at all. That is why they are not recommended for
> > much outside of caches and normalized mappings.
>
> > On Jul 22, 11:07 am, Joseph Earl  wrote:
>
> > > Suppose you had a long list of images. As the user scrolled down you
> > > load the images from the net, and then display them.
> > > To avoid having to reload the images again if the user scrolls back
> > > up, you put the images in a cache (probably something like a
> > > Map)
>
> > > However because it is a long list you don't want to run into an out of
> > > memory situation if the user scrolls very far down and lots of images
> > > are put in the cache.
> > > So instead of storing the Drawables directly in the map, you create a
> > > Map> (although I would use SoftReference
> > > for the purpose described here).
> > > This means that if Android is going to encounter an out of memory
> > > situation it will clear all of the Soft/Weak references (and thus
> > > hopefully avoid running out of memory). You will have to load the
> > > images again since your cache has been cleared, but this is far better
> > > than your application running out of memory and crashing.
>
> > > So you do something like:
>
> > > // caching an image
> > > Map cache = new HashMap > > SoftReference>();
> > > cache.put("http://mysite.com/images/1.jpg";, new
> > > SoftReference.put(myDrawable));
>
> > > // retrieve an image
> > > if (cache.containsKey(url)) {
> > >    // looks like we have this image cached
> > >    Drawable drawable = cache.get(url).get();
> > >    if (drawable == null) {
> > >        // the softreference has been cleared by the GC, reload the
> > > image
> > >    } else {
> > >        // softreference is still valid, got our image
> > >    }
>
> > > }
>
> > > Essentially a weak reference is a weaker reference than a soft
> > > reference - the GC should free weak references to regain memory before
> > > soft references.
>
> > > I think that's (mostly) correct, hope it helps.
>
> > > On Jul 22, 6:48 pm, GodsMoon  wrote:
>
> > > > Google just posted a new blog post 
> > > > onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > > > I understand the AsyncTask and I'm even using one in a list with
> > > > images already.
>
> > > > But I don't understand what a WeakReference is. I gather is is a
> > > > garbage collector directive, but I thought I didn't need to manage
> > > > garbage collection on Android.
>
> > > >http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > > > isn't as helpful as I was hoping it would be.
>
>

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-25 Thread DanH
If the garbage collector deletes an object I have a "hard" reference
to, it's broken.  Doesn't matter if it runs in a different thread or a
different country.  Once I have executed ref() and stored the result
somewhere in my VM (in stack or in another object) that object cannot
be deleted until I overwrite the value.

On Jul 25, 7:19 pm, Indicator Veritatis  wrote:
> As the author of the IBM Developerworks article I referenced mentions,
> that is not good enough. The Garbage Collector runs on a different
> thread, you have no control over when it will be called. It is quite
> possible that just after you test for null, the GC is called, and it
> is no longer valid. Not likely, but possible.
>
> If instead you create a strong reference and use that, discarding it
> when done, then you have shut the door on a really nasty transient
> bug.
>
> Or perhaps the version of 'ref()' you found did this for you? What
> package did you find it it?
>
> On Jul 23, 5:21 am, DanH  wrote:
>
> > Yes, you must "guard" any use of the WeakReference by taking the ref()
> > of it, testing that for null, and then proceeding to use the result of
> > the ref() if not null.  The size of the "guarded" sections is up to
> > the programmer -- if too large then the object will never get deleted,
> > if too small then the code gets chopped up.
>
> > On Jul 23, 1:37 am, Indicator Veritatis  wrote:
>
> > > You left out something very important: the code hidden under "//
> > > reload the image" must not assume that it is not itself interrupted by
> > > yet another call to the garbage collector. That is, instead of simply
> > > continuing to use the soft/weak reference, it should make a strong
> > > reference to the same object, allowing this latter reference to either
> > > go out of scope or be set to null when it is done.
>
> > > But if we are making this strong reference, what was the point of
> > > using the weak/soft reference in the first place? Ah, that is the
> > > tricky thing about using them. Depending on when you can make and
> > > release the strong reference, they might not buy you much; they might
> > > not buy you anything at all. That is why they are not recommended for
> > > much outside of caches and normalized mappings.
>
> > > On Jul 22, 11:07 am, Joseph Earl  wrote:
>
> > > > Suppose you had a long list of images. As the user scrolled down you
> > > > load the images from the net, and then display them.
> > > > To avoid having to reload the images again if the user scrolls back
> > > > up, you put the images in a cache (probably something like a
> > > > Map)
>
> > > > However because it is a long list you don't want to run into an out of
> > > > memory situation if the user scrolls very far down and lots of images
> > > > are put in the cache.
> > > > So instead of storing the Drawables directly in the map, you create a
> > > > Map> (although I would use SoftReference
> > > > for the purpose described here).
> > > > This means that if Android is going to encounter an out of memory
> > > > situation it will clear all of the Soft/Weak references (and thus
> > > > hopefully avoid running out of memory). You will have to load the
> > > > images again since your cache has been cleared, but this is far better
> > > > than your application running out of memory and crashing.
>
> > > > So you do something like:
>
> > > > // caching an image
> > > > Map cache = new HashMap > > > SoftReference>();
> > > > cache.put("http://mysite.com/images/1.jpg";, new
> > > > SoftReference.put(myDrawable));
>
> > > > // retrieve an image
> > > > if (cache.containsKey(url)) {
> > > >    // looks like we have this image cached
> > > >    Drawable drawable = cache.get(url).get();
> > > >    if (drawable == null) {
> > > >        // the softreference has been cleared by the GC, reload the
> > > > image
> > > >    } else {
> > > >        // softreference is still valid, got our image
> > > >    }
>
> > > > }
>
> > > > Essentially a weak reference is a weaker reference than a soft
> > > > reference - the GC should free weak references to regain memory before
> > > > soft references.
>
> > > > I think that's (mostly) correct, hope it helps.
>
> > > > On Jul 22, 6:48 pm, GodsMoon  wrote:
>
> > > > > Google just posted a new blog post 
> > > > > onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > > > > I understand the AsyncTask and I'm even using one in a list with
> > > > > images already.
>
> > > > > But I don't understand what a WeakReference is. I gather is is a
> > > > > garbage collector directive, but I thought I didn't need to manage
> > > > > garbage collection on Android.
>
> > > > >http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > > > > isn't as helpful as I was hoping it would be.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this grou

[android-developers] Re: What is a WeakReference?

2010-07-25 Thread DanH
(The key is to assign ref() to a variable and test the variable, vs
testing ref().)

On Jul 25, 7:19 pm, Indicator Veritatis  wrote:
> As the author of the IBM Developerworks article I referenced mentions,
> that is not good enough. The Garbage Collector runs on a different
> thread, you have no control over when it will be called. It is quite
> possible that just after you test for null, the GC is called, and it
> is no longer valid. Not likely, but possible.
>
> If instead you create a strong reference and use that, discarding it
> when done, then you have shut the door on a really nasty transient
> bug.
>
> Or perhaps the version of 'ref()' you found did this for you? What
> package did you find it it?
>
> On Jul 23, 5:21 am, DanH  wrote:
>
> > Yes, you must "guard" any use of the WeakReference by taking the ref()
> > of it, testing that for null, and then proceeding to use the result of
> > the ref() if not null.  The size of the "guarded" sections is up to
> > the programmer -- if too large then the object will never get deleted,
> > if too small then the code gets chopped up.
>
> > On Jul 23, 1:37 am, Indicator Veritatis  wrote:
>
> > > You left out something very important: the code hidden under "//
> > > reload the image" must not assume that it is not itself interrupted by
> > > yet another call to the garbage collector. That is, instead of simply
> > > continuing to use the soft/weak reference, it should make a strong
> > > reference to the same object, allowing this latter reference to either
> > > go out of scope or be set to null when it is done.
>
> > > But if we are making this strong reference, what was the point of
> > > using the weak/soft reference in the first place? Ah, that is the
> > > tricky thing about using them. Depending on when you can make and
> > > release the strong reference, they might not buy you much; they might
> > > not buy you anything at all. That is why they are not recommended for
> > > much outside of caches and normalized mappings.
>
> > > On Jul 22, 11:07 am, Joseph Earl  wrote:
>
> > > > Suppose you had a long list of images. As the user scrolled down you
> > > > load the images from the net, and then display them.
> > > > To avoid having to reload the images again if the user scrolls back
> > > > up, you put the images in a cache (probably something like a
> > > > Map)
>
> > > > However because it is a long list you don't want to run into an out of
> > > > memory situation if the user scrolls very far down and lots of images
> > > > are put in the cache.
> > > > So instead of storing the Drawables directly in the map, you create a
> > > > Map> (although I would use SoftReference
> > > > for the purpose described here).
> > > > This means that if Android is going to encounter an out of memory
> > > > situation it will clear all of the Soft/Weak references (and thus
> > > > hopefully avoid running out of memory). You will have to load the
> > > > images again since your cache has been cleared, but this is far better
> > > > than your application running out of memory and crashing.
>
> > > > So you do something like:
>
> > > > // caching an image
> > > > Map cache = new HashMap > > > SoftReference>();
> > > > cache.put("http://mysite.com/images/1.jpg";, new
> > > > SoftReference.put(myDrawable));
>
> > > > // retrieve an image
> > > > if (cache.containsKey(url)) {
> > > >    // looks like we have this image cached
> > > >    Drawable drawable = cache.get(url).get();
> > > >    if (drawable == null) {
> > > >        // the softreference has been cleared by the GC, reload the
> > > > image
> > > >    } else {
> > > >        // softreference is still valid, got our image
> > > >    }
>
> > > > }
>
> > > > Essentially a weak reference is a weaker reference than a soft
> > > > reference - the GC should free weak references to regain memory before
> > > > soft references.
>
> > > > I think that's (mostly) correct, hope it helps.
>
> > > > On Jul 22, 6:48 pm, GodsMoon  wrote:
>
> > > > > Google just posted a new blog post 
> > > > > onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
> > > > > I understand the AsyncTask and I'm even using one in a list with
> > > > > images already.
>
> > > > > But I don't understand what a WeakReference is. I gather is is a
> > > > > garbage collector directive, but I thought I didn't need to manage
> > > > > garbage collection on Android.
>
> > > > >http://developer.android.com/reference/java/lang/ref/WeakReference.html
> > > > > isn't as helpful as I was hoping it would be.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-26 Thread Bob Kerns
Um, slightly too strong a statement.

As soon as it's not used outside the cache, it's ELIGIBLE for garbage
collection, which is likely to happen soon.

There are times this is appropriate for a cache. If the objects you're
likely to look up again, are also likely to still be live, but
expensive to find, but can be expected to eventually drop out of use
(and liveness), then WeakReference is the right choice.

Or when your cached object is so big, you want them to go away as soon
as possible, but sometimes you reference them again before they've
gone dead, or before the GC actually got a chance to collect them.
Typically such a cache might only hold the one or two latest objects.

Not your typical general-purpose cache scenarios, however.

My main concern with your statement is that it would imply that
there's some mechanism that instantly nulls out the reference as soon
as the last live reference is dropped. It's not instant -- but that
WOULD be the ideal behavior for a GC, and one benefit of good GC
techniques is that they improve the odds of early collection of short-
lived garbage.

WeakReferences are more useful for associating an object for as long
as it exist, without prolonging that existence. I find it harder to
explain what that means, than to actually decide when they're needed.


On Jul 22, 11:26 am, Romain Guy  wrote:
> You definitely do NOT want to use a WeakReference to cache object. If
> you do so, as soon as your data is put in the cache and not used
> outside of the cache, it gets garbage collected.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-26 Thread Bob Kerns
Actually, I would disagree with this characterization.

In many cases, it's completely infeasible to maintain the information
you'd need. For example, if you provide an API that accepts objects,
and you maintain some internal information about them -- you have no
opportunity to track the client's use of the API. You COULD warp the
API to require the client track this information for you -- but they'd
get it wrong, and  the result would be a less-efficient and more
unreliable package.

It's also inefficient to track that. Especially in cases with circular
references, where simple reference counting cannot work.

In many cases, what you end up having to do is to implement your own
GC of these objects. Using WeakReference means you don't have to do
that; the GC itself informs you.

So it's not just an easier way to avoid poor programming. It's far
more valuable and essential than that implies.

Let's say I have a persistence package, that maintains a huge mass of
information for immediate real-time access about a player. It streams
in from a database, and stays around in memory.

Now, let's say I have a client of that, that's one node in a grid.
Players come and go from grid to grid, join the game, leave the game,
even permanently.

And not just players -- objects come, go, are changed. you have a rich
mix of lightweight objects, and heavy-weight back-end data in support
of them.

A WeakReference is really the only sane way to manage this. The back-
end can associate its data with the Player and Object's using a
WeakReference. When a Player disappears from memory, perhaps moving on
to another realm, the back end can then persist any changes and free
the storage. (It can even arrange to be notified of this, or it can do
it as a background sweep when not busy).

I cast that as an MMO game to grab your interest, but it could also be
something much more mundane, like a shopper's web session, and loaded
product description objects. If no shoppers are browsing a product, it
can be GC'd. In this case, you might use a map with a WeakReference
for the key, and a SoftReference for the data. The WeakReference
allows you to drop the mapping when the shopper goes away; the
SoftReference allows you to reclaim the storage if you're running low
on memory. Without the WeakReference, you'd continue to hold onto the
shopper or player AND the mapping, just by remembering the association
in a table.

On Jul 22, 3:36 pm, DanH  wrote:
> " So you'd only want to use WeakReference when you think your activity
> might run out of memory?"
>
> Not exactly.  If you use poor programming techniques just about any
> long-running operation can run out of memory.  WeakReference is an aid
> to keep you from having to use much more complex techniques (like
> reference chains) while still having "good" programming practices.
>
> On Jul 22, 1:36 pm, GodsMoon  wrote:
>
>
>
> > So you'd only want to use WeakReference when you think your activity
> > might run out of memory?
> > But a list view already does efficient memory management for you
> > right?
>
> > You'd saying if I were create a large array or something like that
> > then it would be good to use WeakReference. right?
>
> > Thanks for the help guys,
> > David Shellabargerwww.nightshadelabs.com
>
> > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > You definitely do NOT want to use a WeakReference to cache object. If
> > > you do so, as soon as your data is put in the cache and not used
> > > outside of the cache, it gets garbage collected.
>
> > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  
> > > wrote:
> > > > Suppose you had a long list of images. As the user scrolled down you
> > > > load the images from the net, and then display them.
> > > > To avoid having to reload the images again if the user scrolls back
> > > > up, you put the images in a cache (probably something like a
> > > > Map)
>
> > > > However because it is a long list you don't want to run into an out of
> > > > memory situation if the user scrolls very far down and lots of images
> > > > are put in the cache.
> > > > So instead of storing the Drawables directly in the map, you create a
> > > > Map> (although I would use SoftReference
> > > > for the purpose described here).
> > > > This means that if Android is going to encounter an out of memory
> > > > situation it will clear all of the Soft/Weak references (and thus
> > > > hopefully avoid running out of memory). You will have to load the
> > > > images again since your cache has been cleared, but this is far better
> > > > than your application running out of memory and crashing.
>
> > > > So you do something like:
>
> > > > // caching an image
> > > > Map cache = new HashMap > > > SoftReference>();
> > > > cache.put("http://mysite.com/images/1.jpg";, new
> > > > SoftReference.put(myDrawable));
>
> > > > // retrieve an image
> > > > if (cache.containsKey(url)) {
> > > >   // looks like we have this image cached
> > > >   Drawable drawable = cache.get(url).get();
>

[android-developers] Re: What is a WeakReference?

2010-07-26 Thread DanH
That's odd, because Qt can do almost exactly the same stuff, without
weak references or implicit garbage collection, using reference chains
that the average user never has to think about.

On Jul 26, 4:20 am, Bob Kerns  wrote:
> Actually, I would disagree with this characterization.
>
> In many cases, it's completely infeasible to maintain the information
> you'd need. For example, if you provide an API that accepts objects,
> and you maintain some internal information about them -- you have no
> opportunity to track the client's use of the API. You COULD warp the
> API to require the client track this information for you -- but they'd
> get it wrong, and  the result would be a less-efficient and more
> unreliable package.
>
> It's also inefficient to track that. Especially in cases with circular
> references, where simple reference counting cannot work.
>
> In many cases, what you end up having to do is to implement your own
> GC of these objects. Using WeakReference means you don't have to do
> that; the GC itself informs you.
>
> So it's not just an easier way to avoid poor programming. It's far
> more valuable and essential than that implies.
>
> Let's say I have a persistence package, that maintains a huge mass of
> information for immediate real-time access about a player. It streams
> in from a database, and stays around in memory.
>
> Now, let's say I have a client of that, that's one node in a grid.
> Players come and go from grid to grid, join the game, leave the game,
> even permanently.
>
> And not just players -- objects come, go, are changed. you have a rich
> mix of lightweight objects, and heavy-weight back-end data in support
> of them.
>
> A WeakReference is really the only sane way to manage this. The back-
> end can associate its data with the Player and Object's using a
> WeakReference. When a Player disappears from memory, perhaps moving on
> to another realm, the back end can then persist any changes and free
> the storage. (It can even arrange to be notified of this, or it can do
> it as a background sweep when not busy).
>
> I cast that as an MMO game to grab your interest, but it could also be
> something much more mundane, like a shopper's web session, and loaded
> product description objects. If no shoppers are browsing a product, it
> can be GC'd. In this case, you might use a map with a WeakReference
> for the key, and a SoftReference for the data. The WeakReference
> allows you to drop the mapping when the shopper goes away; the
> SoftReference allows you to reclaim the storage if you're running low
> on memory. Without the WeakReference, you'd continue to hold onto the
> shopper or player AND the mapping, just by remembering the association
> in a table.
>
> On Jul 22, 3:36 pm, DanH  wrote:
>
> > " So you'd only want to use WeakReference when you think your activity
> > might run out of memory?"
>
> > Not exactly.  If you use poor programming techniques just about any
> > long-running operation can run out of memory.  WeakReference is an aid
> > to keep you from having to use much more complex techniques (like
> > reference chains) while still having "good" programming practices.
>
> > On Jul 22, 1:36 pm, GodsMoon  wrote:
>
> > > So you'd only want to use WeakReference when you think your activity
> > > might run out of memory?
> > > But a list view already does efficient memory management for you
> > > right?
>
> > > You'd saying if I were create a large array or something like that
> > > then it would be good to use WeakReference. right?
>
> > > Thanks for the help guys,
> > > David Shellabargerwww.nightshadelabs.com
>
> > > On Jul 22, 2:26 pm, Romain Guy  wrote:
>
> > > > You definitely do NOT want to use a WeakReference to cache object. If
> > > > you do so, as soon as your data is put in the cache and not used
> > > > outside of the cache, it gets garbage collected.
>
> > > > On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  
> > > > wrote:
> > > > > Suppose you had a long list of images. As the user scrolled down you
> > > > > load the images from the net, and then display them.
> > > > > To avoid having to reload the images again if the user scrolls back
> > > > > up, you put the images in a cache (probably something like a
> > > > > Map)
>
> > > > > However because it is a long list you don't want to run into an out of
> > > > > memory situation if the user scrolls very far down and lots of images
> > > > > are put in the cache.
> > > > > So instead of storing the Drawables directly in the map, you create a
> > > > > Map> (although I would use SoftReference
> > > > > for the purpose described here).
> > > > > This means that if Android is going to encounter an out of memory
> > > > > situation it will clear all of the Soft/Weak references (and thus
> > > > > hopefully avoid running out of memory). You will have to load the
> > > > > images again since your cache has been cleared, but this is far better
> > > > > than your application running out of memory and crashing.

[android-developers] Re: What is a WeakReference?

2010-07-26 Thread Bob Kerns
Um, no. For Qt to do what you claim, it would have to traverse all the
application data -- including data owned by non-Qt code -- to discover
what application objects are still in use. In other words, it would
have to implement a GC.

Unless your definition of "almost exactly the same stuff" is a lot
looser than what I would think.

Would you care to give an example of which Qt API you mean? And
perhaps what binding, if that's relevant?

On Jul 26, 4:13 am, DanH  wrote:
> That's odd, because Qt can do almost exactly the same stuff, without
> weak references or implicit garbage collection, using reference chains
> that the average user never has to think about.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-26 Thread DanH
Qt implements object assignment.  One such object is a pointer
(similar pointers are implemented in other C++ dialects) that
increments a reference count in the addressed object when constructed,
decrements on destruction.  You can assign the pointer and it's
copied, with appropriate incrementing.  If you use the right flavor
pointer (there are several) the object will be be deleted when the
reference count goes to zero.  Other flavors (linked in a reference
chain) act like weak references and go null when the object is
deleted.

All rather automatic (and atomic), with lots of (ahem, shall we say)
"less than stellar" programmers using the stuff and only occasionally
screwing it up.

On Jul 26, 3:49 pm, Bob Kerns  wrote:
> Um, no. For Qt to do what you claim, it would have to traverse all the
> application data -- including data owned by non-Qt code -- to discover
> what application objects are still in use. In other words, it would
> have to implement a GC.
>
> Unless your definition of "almost exactly the same stuff" is a lot
> looser than what I would think.
>
> Would you care to give an example of which Qt API you mean? And
> perhaps what binding, if that's relevant?
>
> On Jul 26, 4:13 am, DanH  wrote:
>
> > That's odd, because Qt can do almost exactly the same stuff, without
> > weak references or implicit garbage collection, using reference chains
> > that the average user never has to think about.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-27 Thread AlanLawrence
However, presumably (only occasionally) "screwing it up" includes
creating circular data structures...???

--Alan

On Jul 26, 10:10 pm, DanH  wrote:
> Qt implements object assignment.  One such object is a pointer
> (similar pointers are implemented in other C++ dialects) that
> increments a reference count in the addressed object when constructed,
> decrements on destruction.  You can assign the pointer and it's
> copied, with appropriate incrementing.  If you use the right flavor
> pointer (there are several) the object will be be deleted when the
> reference count goes to zero.  Other flavors (linked in a reference
> chain) act like weak references and go null when the object is
> deleted.
>
> All rather automatic (and atomic), with lots of (ahem, shall we say)
> "less than stellar" programmers using the stuff and only occasionally
> screwing it up.
>
> On Jul 26, 3:49 pm, Bob Kerns  wrote:
>
>
>
> > Um, no. For Qt to do what you claim, it would have to traverse all the
> > application data -- including data owned by non-Qt code -- to discover
> > what application objects are still in use. In other words, it would
> > have to implement a GC.
>
> > Unless your definition of "almost exactly the same stuff" is a lot
> > looser than what I would think.
>
> > Would you care to give an example of which Qt API you mean? And
> > perhaps what binding, if that's relevant?
>
> > On Jul 26, 4:13 am, DanH  wrote:
>
> > > That's odd, because Qt can do almost exactly the same stuff, without
> > > weak references or implicit garbage collection, using reference chains
> > > that the average user never has to think about.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-27 Thread Bob Kerns
Not even remotely similar. Note carefully your phrase "increments a
reference count in the addressed object". Right there, you've gone off
the rails, placing a requirement on the referenced object -- that it
be managed by reference counts, and in a way that's compatible with
how Qt's pointers interface with them. And further, it requires that
the application that owns the object manage them in a way that is
consonant with the possibility that Qt will be deleting the object.
That means, it can't implement various cleanup strategies that depend
on knowing when the reference count is zeroed -- because it may happen
outside of its control.

And don't even get me started on circular references, and
interoperability, or performance, or storage requirements, or the
thread-safety/performance trade-off you have to make, or the effect of
all those updates on memory caches and memory bandwidth.

And I don't think that even I can begin to enumerate all the ways
there are to screw up with "smart pointers".

But at least reference counting is better than std::auto_ptr. Ever try
to explain to someone what happened when they made a std::vector of
std::auto_ptr's? And then passed it by value, or resized, or  And
even std::auto_ptr is better than malloc/free.

Anyway - care to explain, in a reference counted system, how you would
hold onto an object -- up until the object is deleted? All you get is
reference-counting smart pointers -- you don't get to impose an I'm-
about-to-be-deleted callback protocol. You don't get to have a test
for an object being dead.

Nope, your choices are -- increment the reference, and keep the object
live, or don't increment the reference count -- and don't look at it.
Don't even compare the pointer value.

That's why even reference-counted languages like Python have weak
references. It's really not something you can implement as a user-
level feature (i.e. above the reference-counting or tracing GC).

On Jul 26, 2:10 pm, DanH  wrote:
> Qt implements object assignment.  One such object is a pointer
> (similar pointers are implemented in other C++ dialects) that
> increments a reference count in the addressed object when constructed,
> decrements on destruction.  You can assign the pointer and it's
> copied, with appropriate incrementing.  If you use the right flavor
> pointer (there are several) the object will be be deleted when the
> reference count goes to zero.  Other flavors (linked in a reference
> chain) act like weak references and go null when the object is
> deleted.
>
> All rather automatic (and atomic), with lots of (ahem, shall we say)
> "less than stellar" programmers using the stuff and only occasionally
> screwing it up.
>
> On Jul 26, 3:49 pm, Bob Kerns  wrote:
>
>
>
> > Um, no. For Qt to do what you claim, it would have to traverse all the
> > application data -- including data owned by non-Qt code -- to discover
> > what application objects are still in use. In other words, it would
> > have to implement a GC.
>
> > Unless your definition of "almost exactly the same stuff" is a lot
> > looser than what I would think.
>
> > Would you care to give an example of which Qt API you mean? And
> > perhaps what binding, if that's relevant?
>
> > On Jul 26, 4:13 am, DanH  wrote:
>
> > > That's odd, because Qt can do almost exactly the same stuff, without
> > > weak references or implicit garbage collection, using reference chains
> > > that the average user never has to think about.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


[android-developers] Re: What is a WeakReference?

2010-07-27 Thread Bob Kerns
Actually, as I closed my browser, it suddenly struck me why we differ
in opinion here.

I look at Qt as being merely a library, embedded in a larger language
environment.

You're looking at it as a language itself. So long as you stay within
the confines of Qt and it's primitives and objects, then we can say
that yes, it does equivalent stuff.

But then I have to differ with your statement that Qt doesn't have
weak references. I claim that the things that "do what weak references
do" ARE in fact, weak references.

Weak references are not unique to Java -- they did not even originate
there. We had them in Lisp Machines decades ago. (Well, technically,
weak pointers, but they filled the same role-- they just turned the
reference that held them into a weak reference). Nor are they unique
to tracing garbage collectors. Python has them. A weak reference is
simply a way of referring to an object that meets two simple
requirements:

1) The object is not protected from reclamation
2) The object becomes inaccessible via the reference one it IS
reclaimed.

C++ foo* pointers meet the first, but the second is trickier, and is
what requires language support. Which, Qt can do for itself, so long
as you view it as the language in question. (It's perfectly reasonable
to view it as a sub-language embedded within a host language).

On Jul 27, 2:29 am, Bob Kerns  wrote:
> Not even remotely similar. Note carefully your phrase "increments a
> reference count in the addressed object". Right there, you've gone off
> the rails, placing a requirement on the referenced object -- that it
> be managed by reference counts, and in a way that's compatible with
> how Qt's pointers interface with them. And further, it requires that
> the application that owns the object manage them in a way that is
> consonant with the possibility that Qt will be deleting the object.
> That means, it can't implement various cleanup strategies that depend
> on knowing when the reference count is zeroed -- because it may happen
> outside of its control.
>
> And don't even get me started on circular references, and
> interoperability, or performance, or storage requirements, or the
> thread-safety/performance trade-off you have to make, or the effect of
> all those updates on memory caches and memory bandwidth.
>
> And I don't think that even I can begin to enumerate all the ways
> there are to screw up with "smart pointers".
>
> But at least reference counting is better than std::auto_ptr. Ever try
> to explain to someone what happened when they made a std::vector of
> std::auto_ptr's? And then passed it by value, or resized, or  And
> even std::auto_ptr is better than malloc/free.
>
> Anyway - care to explain, in a reference counted system, how you would
> hold onto an object -- up until the object is deleted? All you get is
> reference-counting smart pointers -- you don't get to impose an I'm-
> about-to-be-deleted callback protocol. You don't get to have a test
> for an object being dead.
>
> Nope, your choices are -- increment the reference, and keep the object
> live, or don't increment the reference count -- and don't look at it.
> Don't even compare the pointer value.
>
> That's why even reference-counted languages like Python have weak
> references. It's really not something you can implement as a user-
> level feature (i.e. above the reference-counting or tracing GC).
>
> On Jul 26, 2:10 pm, DanH  wrote:
>
>
>
> > Qt implements object assignment.  One such object is a pointer
> > (similar pointers are implemented in other C++ dialects) that
> > increments a reference count in the addressed object when constructed,
> > decrements on destruction.  You can assign the pointer and it's
> > copied, with appropriate incrementing.  If you use the right flavor
> > pointer (there are several) the object will be be deleted when the
> > reference count goes to zero.  Other flavors (linked in a reference
> > chain) act like weak references and go null when the object is
> > deleted.
>
> > All rather automatic (and atomic), with lots of (ahem, shall we say)
> > "less than stellar" programmers using the stuff and only occasionally
> > screwing it up.
>
> > On Jul 26, 3:49 pm, Bob Kerns  wrote:
>
> > > Um, no. For Qt to do what you claim, it would have to traverse all the
> > > application data -- including data owned by non-Qt code -- to discover
> > > what application objects are still in use. In other words, it would
> > > have to implement a GC.
>
> > > Unless your definition of "almost exactly the same stuff" is a lot
> > > looser than what I would think.
>
> > > Would you care to give an example of which Qt API you mean? And
> > > perhaps what binding, if that's relevant?
>
> > > On Jul 26, 4:13 am, DanH  wrote:
>
> > > > That's odd, because Qt can do almost exactly the same stuff, without
> > > > weak references or implicit garbage collection, using reference chains
> > > > that the average user never has to think about.

-- 
You received this message b

[android-developers] Re: What is a WeakReference?

2010-07-27 Thread DanH
"Not even remotely similar. Note carefully your phrase "increments a
reference count in the addressed object". Right there, you've gone off
the rails, placing a requirement on the referenced object -- that it
be managed by reference counts, and in a way that's compatible with
how Qt's pointers interface with them."

Not so.  The only requirement is that the object class be derived from
QObject, which embeds all the logic for this.  No different from Java
deriving all classes from Object.

"And further, it requires that
the application that owns the object manage them in a way that is
consonant with the possibility that Qt will be deleting the object.
That means, it can't implement various cleanup strategies that depend
on knowing when the reference count is zeroed -- because it may happen
outside of its control."

I've never delved into it, but I understand that Qt implements a
pointer type similar to the raw ref pointer that underlies the soft/
weak ones in Java -- receives notification of when an object is at
zero references.  And even without that you're guaranteed that your
object destructor will be called -- much more robust than Java's flaky
finalizer scheme (where you're not guaranteed it will be called and
you can't rely on it for "various cleanup strategies").

Note that I'm not arguing that this stuff is better, but simply
pointing out that there are indeed other ways to deal with the general
problem.  The Java approach is good but not great, and certainly not
unique.

On Jul 27, 4:29 am, Bob Kerns  wrote:
> Not even remotely similar. Note carefully your phrase "increments a
> reference count in the addressed object". Right there, you've gone off
> the rails, placing a requirement on the referenced object -- that it
> be managed by reference counts, and in a way that's compatible with
> how Qt's pointers interface with them. And further, it requires that
> the application that owns the object manage them in a way that is
> consonant with the possibility that Qt will be deleting the object.
> That means, it can't implement various cleanup strategies that depend
> on knowing when the reference count is zeroed -- because it may happen
> outside of its control.
>
> And don't even get me started on circular references, and
> interoperability, or performance, or storage requirements, or the
> thread-safety/performance trade-off you have to make, or the effect of
> all those updates on memory caches and memory bandwidth.
>
> And I don't think that even I can begin to enumerate all the ways
> there are to screw up with "smart pointers".
>
> But at least reference counting is better than std::auto_ptr. Ever try
> to explain to someone what happened when they made a std::vector of
> std::auto_ptr's? And then passed it by value, or resized, or  And
> even std::auto_ptr is better than malloc/free.
>
> Anyway - care to explain, in a reference counted system, how you would
> hold onto an object -- up until the object is deleted? All you get is
> reference-counting smart pointers -- you don't get to impose an I'm-
> about-to-be-deleted callback protocol. You don't get to have a test
> for an object being dead.
>
> Nope, your choices are -- increment the reference, and keep the object
> live, or don't increment the reference count -- and don't look at it.
> Don't even compare the pointer value.
>
> That's why even reference-counted languages like Python have weak
> references. It's really not something you can implement as a user-
> level feature (i.e. above the reference-counting or tracing GC).
>
> On Jul 26, 2:10 pm, DanH  wrote:
>
> > Qt implements object assignment.  One such object is a pointer
> > (similar pointers are implemented in other C++ dialects) that
> > increments a reference count in the addressed object when constructed,
> > decrements on destruction.  You can assign the pointer and it's
> > copied, with appropriate incrementing.  If you use the right flavor
> > pointer (there are several) the object will be be deleted when the
> > reference count goes to zero.  Other flavors (linked in a reference
> > chain) act like weak references and go null when the object is
> > deleted.
>
> > All rather automatic (and atomic), with lots of (ahem, shall we say)
> > "less than stellar" programmers using the stuff and only occasionally
> > screwing it up.
>
> > On Jul 26, 3:49 pm, Bob Kerns  wrote:
>
> > > Um, no. For Qt to do what you claim, it would have to traverse all the
> > > application data -- including data owned by non-Qt code -- to discover
> > > what application objects are still in use. In other words, it would
> > > have to implement a GC.
>
> > > Unless your definition of "almost exactly the same stuff" is a lot
> > > looser than what I would think.
>
> > > Would you care to give an example of which Qt API you mean? And
> > > perhaps what binding, if that's relevant?
>
> > > On Jul 26, 4:13 am, DanH  wrote:
>
> > > > That's odd, because Qt can do almost exactly the same stuff, without
> >

[android-developers] Re: What is a WeakReference?

2010-07-28 Thread AlanLawrence
Well - to be fair (or perhaps generous!): finalizers were in an early
release of Java; when people realized just how broken they were,
WeakReferences (and, specifically, ReferenceQueues) were added much
later, as a replacement / "this is how to do it (more) properly". Of
course, this being Java, finalizers were never removed from the
language even when WeakRefs were in place

public class Foo {
   private static final List myList = new ArrayList();
   protected void finalize() {
  myList.add(this);
   }
}

etc. etc. :)

--Alan

On Jul 27, 1:12 pm, DanH  wrote:
> "Not even remotely similar. Note carefully your phrase "increments a
> reference count in the addressed object". Right there, you've gone off
> the rails, placing a requirement on the referenced object -- that it
> be managed by reference counts, and in a way that's compatible with
> how Qt's pointers interface with them."
>
> Not so.  The only requirement is that the object class be derived from
> QObject, which embeds all the logic for this.  No different from Java
> deriving all classes from Object.
>
> "And further, it requires that
> the application that owns the object manage them in a way that is
> consonant with the possibility that Qt will be deleting the object.
> That means, it can't implement various cleanup strategies that depend
> on knowing when the reference count is zeroed -- because it may happen
> outside of its control."
>
> I've never delved into it, but I understand that Qt implements a
> pointer type similar to the raw ref pointer that underlies the soft/
> weak ones in Java -- receives notification of when an object is at
> zero references.  And even without that you're guaranteed that your
> object destructor will be called -- much more robust than Java's flaky
> finalizer scheme (where you're not guaranteed it will be called and
> you can't rely on it for "various cleanup strategies").
>
> Note that I'm not arguing that this stuff is better, but simply
> pointing out that there are indeed other ways to deal with the general
> problem.  The Java approach is good but not great, and certainly not
> unique.
>
> On Jul 27, 4:29 am, Bob Kerns  wrote:
>
>
>
> > Not even remotely similar. Note carefully your phrase "increments a
> > reference count in the addressed object". Right there, you've gone off
> > the rails, placing a requirement on the referenced object -- that it
> > be managed by reference counts, and in a way that's compatible with
> > how Qt's pointers interface with them. And further, it requires that
> > the application that owns the object manage them in a way that is
> > consonant with the possibility that Qt will be deleting the object.
> > That means, it can't implement various cleanup strategies that depend
> > on knowing when the reference count is zeroed -- because it may happen
> > outside of its control.
>
> > And don't even get me started on circular references, and
> > interoperability, or performance, or storage requirements, or the
> > thread-safety/performance trade-off you have to make, or the effect of
> > all those updates on memory caches and memory bandwidth.
>
> > And I don't think that even I can begin to enumerate all the ways
> > there are to screw up with "smart pointers".
>
> > But at least reference counting is better than std::auto_ptr. Ever try
> > to explain to someone what happened when they made a std::vector of
> > std::auto_ptr's? And then passed it by value, or resized, or  And
> > even std::auto_ptr is better than malloc/free.
>
> > Anyway - care to explain, in a reference counted system, how you would
> > hold onto an object -- up until the object is deleted? All you get is
> > reference-counting smart pointers -- you don't get to impose an I'm-
> > about-to-be-deleted callback protocol. You don't get to have a test
> > for an object being dead.
>
> > Nope, your choices are -- increment the reference, and keep the object
> > live, or don't increment the reference count -- and don't look at it.
> > Don't even compare the pointer value.
>
> > That's why even reference-counted languages like Python have weak
> > references. It's really not something you can implement as a user-
> > level feature (i.e. above the reference-counting or tracing GC).
>
> > On Jul 26, 2:10 pm, DanH  wrote:
>
> > > Qt implements object assignment.  One such object is a pointer
> > > (similar pointers are implemented in other C++ dialects) that
> > > increments a reference count in the addressed object when constructed,
> > > decrements on destruction.  You can assign the pointer and it's
> > > copied, with appropriate incrementing.  If you use the right flavor
> > > pointer (there are several) the object will be be deleted when the
> > > reference count goes to zero.  Other flavors (linked in a reference
> > > chain) act like weak references and go null when the object is
> > > deleted.
>
> > > All rather automatic (and atomic), with lots of (ahem, shall we say)
> > > "less than stellar" progra

Re: [android-developers] Re: What is a WeakReference?

2010-07-22 Thread Romain Guy
You definitely do NOT want to use a WeakReference to cache object. If
you do so, as soon as your data is put in the cache and not used
outside of the cache, it gets garbage collected.

On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  wrote:
> Suppose you had a long list of images. As the user scrolled down you
> load the images from the net, and then display them.
> To avoid having to reload the images again if the user scrolls back
> up, you put the images in a cache (probably something like a
> Map)
>
> However because it is a long list you don't want to run into an out of
> memory situation if the user scrolls very far down and lots of images
> are put in the cache.
> So instead of storing the Drawables directly in the map, you create a
> Map> (although I would use SoftReference
> for the purpose described here).
> This means that if Android is going to encounter an out of memory
> situation it will clear all of the Soft/Weak references (and thus
> hopefully avoid running out of memory). You will have to load the
> images again since your cache has been cleared, but this is far better
> than your application running out of memory and crashing.
>
> So you do something like:
>
> // caching an image
> Map cache = new HashMap SoftReference>();
> cache.put("http://mysite.com/images/1.jpg";, new
> SoftReference.put(myDrawable));
>
> // retrieve an image
> if (cache.containsKey(url)) {
>   // looks like we have this image cached
>   Drawable drawable = cache.get(url).get();
>   if (drawable == null) {
>       // the softreference has been cleared by the GC, reload the
> image
>   } else {
>       // softreference is still valid, got our image
>   }
> }
>
>
> Essentially a weak reference is a weaker reference than a soft
> reference - the GC should free weak references to regain memory before
> soft references.
>
> I think that's (mostly) correct, hope it helps.
>
> On Jul 22, 6:48 pm, GodsMoon  wrote:
>> Google just posted a new blog post 
>> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
>> I understand the AsyncTask and I'm even using one in a list with
>> images already.
>>
>> But I don't understand what a WeakReference is. I gather is is a
>> garbage collector directive, but I thought I didn't need to manage
>> garbage collection on Android.
>>
>> http://developer.android.com/reference/java/lang/ref/WeakReference.html
>> isn't as helpful as I was hoping it would be.
>
> --
> You received this message because you are subscribed to the Google
> Groups "Android Developers" group.
> To post to this group, send email to android-developers@googlegroups.com
> To unsubscribe from this group, send email to
> android-developers+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/android-developers?hl=en
>



-- 
Romain Guy
Android framework engineer
romain...@android.com

Note: please don't send private questions to me, as I don't have time
to provide private support.  All such questions should be posted on
public forums, where I and others can see and answer them

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


Re: [android-developers] Re: What is a WeakReference?

2010-07-22 Thread Kostya Vasilyev
I remember seeing somewhere that Dalvik didn't initially support Soft / 
Weak references, and this was implemented at some point.


Can someone clarify: starting with what version of Dalvik / Android 
these are available?


-- Kostya

22.07.2010 23:34, GodsMoon пишет:

The blog post is confusing.
"Note that this ImageView is stored as a WeakReference, so that a
download in progress does not prevent a killed activity's ImageView
from being garbage collected."
I didn't know that would cause a memory leak. I thought the garbage
collector would clean up ImageView if its activity gets killed.
Am I wrong?

David Shellabarger
www.nightshadelabs.com

On Jul 22, 3:06 pm, Joseph Earl  wrote:
   

No. I'm unsure as to what to use a WeakReference for exactly - as
Romain Guy said above it is too weak for this purpose, but I think
(hopefully Romain will correct me if I'm wrong) that a SoftReference
could be suitable for this purpose.

A ListView already does efficient management of your Views by
recycling. This means that you must ensure the correct details are set
in the view each time getView is called, even if you do not inflate a
view or call findViewById that time. Recycling does not mean that the
ListView caches all your items or their content.

Suppose you had a list of 10 items, all of the same type but only 5
will fit on the screen at a time. The ListView only really needs 5
views to show the rows since the other 5 won't be visible.
Thus at the top of the list the ListView might use 'View 1' for the
first item, but scroll down to the bottom and 'View 1' would now
contain item 6. As far as I understand it this is recycling.

Recycling does not take care of the amount time of it takes to get
content and set it to the view - thus if it takes a long time to get a
piece of information and display it in a list item (such as
downloading an image from the web), you will want to cache the result
in a way that does not adversely affect memory usage (as much as
possible). In this case you will also want to use a Thread or Async
task to download/get the info off the UI thread.

On Jul 22, 7:36 pm, GodsMoon  wrote:



 

So you'd only want to use WeakReference when you think your activity
might run out of memory?
But a list view already does efficient memory management for you
right?
   
 

You'd saying if I were create a large array or something like that
then it would be good to use WeakReference. right?
   
 

Thanks for the help guys,
David Shellabargerwww.nightshadelabs.com
   
 

On Jul 22, 2:26 pm, Romain Guy  wrote:
   
 

You definitely do NOT want to use a WeakReference to cache object. If
you do so, as soon as your data is put in the cache and not used
outside of the cache, it gets garbage collected.
 
 

On Thu, Jul 22, 2010 at 11:07 AM, Joseph Earl  wrote:
 

Suppose you had a long list of images. As the user scrolled down you
load the images from the net, and then display them.
To avoid having to reload the images again if the user scrolls back
up, you put the images in a cache (probably something like a
Map)
   
 

However because it is a long list you don't want to run into an out of
memory situation if the user scrolls very far down and lots of images
are put in the cache.
So instead of storing the Drawables directly in the map, you create a
Map>  (although I would use SoftReference
for the purpose described here).
This means that if Android is going to encounter an out of memory
situation it will clear all of the Soft/Weak references (and thus
hopefully avoid running out of memory). You will have to load the
images again since your cache has been cleared, but this is far better
than your application running out of memory and crashing.
   
 

So you do something like:
   
 

// caching an image
Map  cache = new HashMap>();
cache.put("http://mysite.com/images/1.jpg";, new
SoftReference.put(myDrawable));
   
 

// retrieve an image
if (cache.containsKey(url)) {
   // looks like we have this image cached
   Drawable drawable = cache.get(url).get();
   if (drawable == null) {
   // the softreference has been cleared by the GC, reload the
image
   } else {
   // softreference is still valid, got our image
   }
}
   
 

Essentially a weak reference is a weaker reference than a soft
reference - the GC should free weak references to regain memory before
soft references.
   
 

I think that's (mostly) correct, hope it helps.
   
 

On Jul 22, 6:48 pm, GodsMoon  wrote:
   

Google just posted a new blog post 
onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per
I understand the AsyncTask and I'm even using one in a list with
images already.
 
 

But I don't understand what a WeakReference is. I gather is is a
garbage collector directive, but I thought I didn't need to manage
garbage collection on Android.
 
 

Re: [android-developers] Re: What is a WeakReference?

2010-07-24 Thread Agus
GC can reclaim WeakReference even memory is still plenty, but
SoftReferences will only be cleared when the system is just about to
starve out of memory..

On Sat, Jul 24, 2010 at 2:25 PM, Joseph Earl  wrote:
> I did say '(although I would use SoftReference for the purpose
> described here).' But it wasn't clear enough I agree (and because I
> admittedly wasn't sure enough about the differences)
>
> On Jul 23, 4:25 pm, Matt Quigley  wrote:
>> On Jul 23, 2:37 am, Indicator Veritatis  wrote:
>>
>> > You left out something very important: the code hidden under "//
>> > reload the image" must not assume that it is not itself interrupted by
>> > yet another call to the garbage collector. That is, instead of simply
>> > continuing to use the soft/weak reference, it should make a strong
>> > reference to the same object, allowing this latter reference to either
>> > go out of scope or be set to null when it is done.
>>
>> You are referring to the code that Joseph Earl wrote above.  That code
>> snippet is NOT a proper way to use weak references; that cache should
>> be using soft references.
>>
>> On the other hand, in the example blog post referred to by the OP,
>> which uses weak references, that IS a proper way to use weak
>> references.  The main Activity already has a strong reference to the
>> objects.  The secondary thread does not need to create a strong
>> reference; in fact, that would make the weak reference useless.
>>
>> > But if we are making this strong reference, what was the point of
>> > using the weak/soft reference in the first place? Ah, that is the
>> > tricky thing about using them. Depending on when you can make and
>> > release the strong reference, they might not buy you much; they might
>> > not buy you anything at all. That is why they are not recommended for
>> > much outside of caches and normalized mappings.
>>
>> You are referring to a soft reference, not a weak reference.  Soft
>> references are good for caches.  Weak references are definitely
>> recommended for the idea given in the article, where the main thread
>> has a strong reference, and the background thread has a weak
>> reference.  That way if the main thread is killed (i.e. the app is
>> finished), if the background thread is still running then it won't
>> prevent the weakly referenced objects from being destroyed.
>>
>> I also hate to throw this bit of information into the mix, but it
>> should be known that Android will kill your process, and hence
>> background threads anyways, when all your main threads have been
>> destroyed (i.e. all your activities are finished, and there aren't any
>> services running).  This means that, even if you did have a background
>> thread running, it would be killed, implying that weak references
>> wouldn't help because everything is going to get killed anyways.  That
>> being said, there are still circumstances where the weak references
>> matter: just because one activity is finished, doesn't mean all of
>> your app's activities are necessarily finished.  So it would be good
>> if you went from your main activity into another sub-activity which
>> began a download.  But then the user presses back, because they don't
>> want to bother waiting on the download.  In that case your main
>> activity is still alive, but the background thread is working on the
>> sub-activity that was already finished.  If that background thread had
>> weak references, then that background thread would no longer be
>> holding on to the resources of the sub-activity with strong
>> references, and the system could GC those resources already, before
>> the background thread dies.
>>
>> -Matt
>>
>> -Matt
>
> --
> You received this message because you are subscribed to the Google
> Groups "Android Developers" group.
> To post to this group, send email to android-developers@googlegroups.com
> To unsubscribe from this group, send email to
> android-developers+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/android-developers?hl=en

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


Re: [android-developers] Re: What is a WeakReference?

2010-07-27 Thread Kostya Vasilyev
Java also gives you enough rope to hang yourself. Just have to try a 
little harder to find it.


Here is an example from production code ummm u some 12 years 
ago (written by someone else).


class Item {
String myKey;
Hashtable myHashtable;
.
Item (Hashtable table, String key) {
myKey = key;
myHashtable = table;
myHashtable.put(myKey, this);
}

protected void finalize() throws Throwable {
myHashtable.remove(myKey);
}
}

Instant circular reference, no garbage collection. This brought an 
enterprise-level server system down to its knees over a few hours :)


-- Kostya

27.07.2010 12:11, AlanLawrence пишет:

However, presumably (only occasionally) "screwing it up" includes
creating circular data structures...???

--Alan

On Jul 26, 10:10 pm, DanH  wrote:
   

Qt implements object assignment.  One such object is a pointer
(similar pointers are implemented in other C++ dialects) that
increments a reference count in the addressed object when constructed,
decrements on destruction.  You can assign the pointer and it's
copied, with appropriate incrementing.  If you use the right flavor
pointer (there are several) the object will be be deleted when the
reference count goes to zero.  Other flavors (linked in a reference
chain) act like weak references and go null when the object is
deleted.

All rather automatic (and atomic), with lots of (ahem, shall we say)
"less than stellar" programmers using the stuff and only occasionally
screwing it up.

On Jul 26, 3:49 pm, Bob Kerns  wrote:



 

Um, no. For Qt to do what you claim, it would have to traverse all the
application data -- including data owned by non-Qt code -- to discover
what application objects are still in use. In other words, it would
have to implement a GC.
   
 

Unless your definition of "almost exactly the same stuff" is a lot
looser than what I would think.
   
 

Would you care to give an example of which Qt API you mean? And
perhaps what binding, if that's relevant?
   
 

On Jul 26, 4:13 am, DanH  wrote:
   
 

That's odd, because Qt can do almost exactly the same stuff, without
weak references or implicit garbage collection, using reference chains
that the average user never has to think about.
 
   



--
Kostya Vasilev -- WiFi Manager + pretty widget -- http://kmansoft.wordpress.com

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en


Re: [android-developers] Re: What is a WeakReference?

2010-07-27 Thread Kostya Vasilyev
Java also gives you enough rope to hang yourself. Just have to try a 
little harder to find it.


Here is an example from production code ummm u some 12 years 
ago (written by someone else).


class Item {
String myKey;
Hashtable myHashtable;
.
Item (Hashtable table, String key) {
myKey = key;
myHashtable = table;
myHashtable.put(myKey, this);
}

protected void finalize() throws Throwable {
myHashtable.remove(myKey);
}
}

Instant circular reference, no garbage collection. This brought an 
enterprise-level server system down to its knees over a few hours :)


-- Kostya

27.07.2010 12:11, AlanLawrence пишет:

However, presumably (only occasionally) "screwing it up" includes
creating circular data structures...???

--Alan

On Jul 26, 10:10 pm, DanH  wrote:
   

Qt implements object assignment.  One such object is a pointer
(similar pointers are implemented in other C++ dialects) that
increments a reference count in the addressed object when constructed,
decrements on destruction.  You can assign the pointer and it's
copied, with appropriate incrementing.  If you use the right flavor
pointer (there are several) the object will be be deleted when the
reference count goes to zero.  Other flavors (linked in a reference
chain) act like weak references and go null when the object is
deleted.

All rather automatic (and atomic), with lots of (ahem, shall we say)
"less than stellar" programmers using the stuff and only occasionally
screwing it up.

On Jul 26, 3:49 pm, Bob Kerns  wrote:



 

Um, no. For Qt to do what you claim, it would have to traverse all the
application data -- including data owned by non-Qt code -- to discover
what application objects are still in use. In other words, it would
have to implement a GC.
   
 

Unless your definition of "almost exactly the same stuff" is a lot
looser than what I would think.
   
 

Would you care to give an example of which Qt API you mean? And
perhaps what binding, if that's relevant?
   
 

On Jul 26, 4:13 am, DanH  wrote:
   
 

That's odd, because Qt can do almost exactly the same stuff, without
weak references or implicit garbage collection, using reference chains
that the average user never has to think about.
 
   



--
Kostya Vasilev -- WiFi Manager + pretty widget -- http://kmansoft.wordpress.com

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en