|
 |
Warp wrote:
> Darren New <dne### [at] san rr com> wrote:
>> So the code would be
>
>> thisListener = weak_to_strong(listeners[i]);
>> if (thisListener != null) listeners[i].doSomething();
>> else listeners[i] = null;
>
> In theory it could happen that each time the GC takes a sweep,
> that second line is being executed. (Yes, extremely unlikely for
> that to happen each time, but theoretically possible.) Since that
> second line is using a strong reference, the object is not destroyed?
Correct. Once the weak_to_strong creates the strong reference, it can
no longer be GCed, since there's still a strong reference around.
> Also, I assume that the weak_to_strong() function must be locking
> (ie. have mutual exclusion). Doesn't that make it slower than just
> using a strong reference?
Sure. If nothing else, you need the overhead of calling
weak_to_strong(). You don't want to use weak references if you don't
need them.
But generally, if your GC is letting your code run while the GC is
running, you're going to have various kinds of locking overhead. Often,
instead, you'll have the program stopped briefly while a little bit of
objects is marked either "free" or "in use", then more application code,
then a little bit of scanning, etc, until you've finished a full scan.
Then you throw things away, a little at a time, also.
But generally, if you have threads, you GC one thread at a time, so the
thread you're GCing isn't mutating memory as you're collecting it.
Remember, too, that you're looking for live objects, not dead ones, so
if an object goes from live to dead while you're scanning, you're OK -
you'll get it the next time around. The complexity comes from objects
going from dead to live while you're scanning.
It's not just the weak-to-strong that needs locks. If you compact memory
to make larger free spaces, you obviously need to make sure nobody is in
the middle of referencing what you're moving and so on either. Even
reference counting stuff has to have locks, except now you need locks
for every time you assign a pointer, instead of just during garbage
collection.
It's actually pretty darn complicated to get right. And it has been an
ongoing field of research for 30 years already, and there's still no
solution that makes everybody happy, so...
--
Darren New / San Diego, CA, USA (PST)
"That's pretty. Where's that?"
"It's the Age of Channelwood."
"We should go there on vacation some time."
Post a reply to this message
|
 |