# Weakref: can I use it like this?

**URL:** <https://www.ruby-forum.com/t/weakref-can-i-use-it-like-this/184720>\
**Category:** Ruby\
**Created:** [March 7, 2010, 11:01am UTC](https://www.ruby-forum.com/t/weakref-can-i-use-it-like-this/184720 "2010-03-07T11:01:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jeremyheiler](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/34f0e0/32.png) [@jeremyheiler](https://www.ruby-forum.com/u/jeremyheiler)\
**Post date:** [March 7, 2010, 11:01am UTC](https://www.ruby-forum.com/t/weakref-can-i-use-it-like-this/184720/1 "2010-03-07T11:01:39Z")

</div>

I want to do some extended processing on an object referred to by a  
weakref. This might generate lots of garbage so I don’t want to turn  
off garbage collection while I’m doing this. So I’d really like to  
get a proper non-weak reference to the weakref-ed object (assuming  
it’s not _already_ garbage-collected). Is it safe to do this?

```
obj = weakref. __getobj__ # will raise error if weakref is invalid
process obj

```

I’m hoping this will ensure that if the process method is called then  
it gets a real reference to the weakref-ed object, so that it can  
safely execute even though garbage collection is still on. I’m also  
hoping that once the binding of the obj variable goes out of scope  
then the object is available for garbage collection again.

Will this work as I expect? Is it thread-safe? Portable across  
different Ruby implementations? Have I missed some race condition?

Regards,

Jeremy H.

---

<div class="post-metadata">

**Author:** ![jeremyheiler](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/34f0e0/32.png) [@jeremyheiler](https://www.ruby-forum.com/u/jeremyheiler)\
**Post date:** [March 7, 2010, 6:20pm UTC](https://www.ruby-forum.com/t/weakref-can-i-use-it-like-this/184720/2 "2010-03-07T18:20:35Z")

</div>

On 03/07/2010 10:55 AM, Jeremy H. wrote:

> it gets a real reference to the weakref-ed object, so that it can  
> safely execute even though garbage collection is still on. I’m also  
> hoping that once the binding of the obj variable goes out of scope  
> then the object is available for garbage collection again.
> 
> Will this work as I expect? Is it thread-safe? Portable across  
> different Ruby implementations? Have I missed some race condition?

I think that’s exactly the way it should be done.

Kind regards

robert
