POV-Ray : Newsgroups : povray.off-topic : Programming design question, related to GC : Re: Programming design question, related to GC Server Time
4 Nov 2024 17:36:13 EST (-0500)
  Re: Programming design question, related to GC  
From: Darren New
Date: 12 Apr 2008 18:25:31
Message: <480136db@news.povray.org>
Warp wrote:
>   If the GC happens to make a sweep after the conditional but before
> the call, and it sets the weak reference at listeners[i] to null, we'll
> get a null pointer exception (which may seem crazy because we just
> checked that it's not null).

Yes, except that's always possible in a multi-threaded system, if 
another thread sets the listeners[i] to null. :-)

Generally speaking, you can't invoke a weak reference like that. Most 
systems get around the problem by having a function (which has to be 
built-in, you can't implement it yourself) that takes a weak reference 
and returns either null or a strong reference; *that* really is the 
point where the weak reference gets cleaned up after the object is gone. 
  I.e., weak references are simply pointers into some system-maintained 
table, not actual pointers to the objects themselves.

So the code would be

thisListener = weak_to_strong(listeners[i]);
if (thisListener != null) listeners[i].doSomething();
else listeners[i] = null;

You'd still have the weak reference. If the call to doSomething() 
cleared out the last intentional reference to that listener (the "this" 
in the call), then when you returned from the doSomething and 
"thisListener" went out of scope, then you'd wind up getting it 
collected. But you'd have to return from doSomething before that 
newly-created strong reference disappeared.

>   Or are GC engines run only at places where there can't be mutual
> exclusion problems? (How does the VM/compiler/interpreter know that?)

When the GC actually doesn't stop all threads, it uses funky tricks like 
making memory pages non-writable or non-readable and catching hardware 
exceptions to avoid having problems with interactions like that. Like, 
if the GC scans an object X for outgoing pointers, it marks it as 
read-only until it's done. Then you store a new pointer in that object 
from another thread, the GC catches the write, sees what new object Y 
you might be pointing to, and makes sure that if that 
newly-pointed-to-object had already been marked free (because you had 
not been pointing to it before but now X points to it), Y is now marked 
"in use" again.

But weak references generally have to be turned into strong references 
to use them. At least everywhere I've seen such implemented.

-- 
   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

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.