Questions tagged [weak-references]

A weak reference is a one that makes no claim of ownership. A weak reference keeps a reference to the object in question while it is in memory, but does not prevent the memory management system from reclaiming the associated memory when the referenced object is otherwise no longer needed. Many languages feature or support various levels of weak references, such as Swift, Objective-C, Java, C#, Python, Perl and Lisp.

A weak reference is one that does not cause the memory management system to hold on to the referenced object. It is used in cases where one wants a reference to the object in question as long as it is still needed/used elsewhere, but to also not prevent it from being reclaimed by the memory management system in the course of its normal lifecycle.

Weak references are especially important where one might have two or more objects referencing each other and you want to avoid a “retain cycle” or ”strong reference cycle”, where circular combinations of strong references will prevent the memory from ever being reclaimed. One common use of weak references in conjunction with closures and callbacks.

Some garbage-collected languages feature or support various levels of weak references, such as , , , and .

Reference counting languages, such as and , use weak (and unowned) references to prevent the establishment of additional strong references. An object that has no further strong references will be deallocated.

Certain environments have further variations on weak references such as "soft", "unowned", "phantom", which have very specific meanings in those environments.

1131 questions
27
votes
2 answers

Using __block and __weak

I've read over this thread: What does the "__block" keyword mean? which discusses what __block is used for but I'm confused about one of the answers. It says __block is used to avoid retain cycles, but the comments underneath it leave me unsure. I'm…
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
25
votes
1 answer

Bitmap, Bitmap.recycle(), WeakReferences, and Garbage Collection

AFAIK on Android, it is recommended to reference Bitmap objects as WeakReferences in order to avoid memory leaks. When no more hard references are kept of a bitmap object, the garbage collector will automatically collect it. Now, if I understand…
Sly
  • 2,105
  • 5
  • 22
  • 28
25
votes
3 answers

Do capture lists of inner closures need to redeclare `self` as `weak` or `unowned`?

If I have a closure passed to a function like this: someFunctionWithTrailingClosure { [weak self] in anotherFunctionWithTrailingClosure { [weak self] in self?.doSomething() } } If I declare self as [weak self] in…
25
votes
6 answers

Using objc_setAssociatedObject with weak references

I know that OBJC_ASSOCIATION_ASSIGN exists, but does it zero the reference if the target object is dealloced? Or is it like the old days where that reference needs to get nil-ed or we risk a bad access later on?
ultramiraculous
  • 1,062
  • 14
  • 21
24
votes
6 answers

Creating a weak subscription to an IObservable

What I want to do is ensure that if the only reference to my observer is the observable, it get's garbage collected and stops receiving messages. Say I have a control with a list box on it called Messages and this code behind: //Short lived display…
ForbesLindesay
  • 10,482
  • 3
  • 47
  • 74
24
votes
3 answers

How to avoid memory leaks in callback?

Effective Java says: A third common source of memory leaks is listeners and other callbacks. If you implement an API where clients register callbacks but don’t deregister them explicitly, they will accumulate unless you take some …
unj2
  • 52,135
  • 87
  • 247
  • 375
24
votes
4 answers

Is there a way to do a WeakList or WeakCollection (like WeakReference) in CLR?

Using a List will not work as I want. What I want is for WeakReferences to be automatically removed from the list whenever the object they reference is garbage collected. ConditionalWeakTable does not satisfy me either,…
Tim Lovell-Smith
  • 15,310
  • 14
  • 76
  • 93
24
votes
2 answers

Why does Django's signal handling use weak references for callbacks by default?

The Django docs say this on the subject: Note also that Django stores signal handlers as weak references by default, so if your handler is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the…
Jason C
  • 21,377
  • 10
  • 38
  • 33
23
votes
1 answer

Why setting object that is undergoing deallocation to weak property results in crash

In Clang's Objective-C Automatic Reference Counting we see the following For __weak objects, the lvalue is updated to point to the new pointee, unless the new pointee is an object currently undergoing deallocation, in which case the lvalue is…
23
votes
1 answer

Test a weak reference before using it java

In a multithreaded Android project, I'm seeing code like this: final WeakReference myClassObjectWeakRef = new WeakReference(aMyClassObject); ...then somewhere else: if (myClassObjectWeakRef.get() != null) { …
Georges
  • 232
  • 2
  • 7
23
votes
4 answers

ConcurrentHashMap with weak keys and identity hash?

How do I get a ConcurrentHashMap with weak keys and identity hashes in Java? I think Google Guava Collections can give such a thing, but can I get it from the standard library? What other options do I have?
r.v
  • 4,697
  • 6
  • 35
  • 57
22
votes
3 answers

Weak object in an NSDictionary?

I would like to store a zeroing weak reference to an object in a NSDictionary. This is for a reference to a parent NSDictionary, so I can crawl back up a large structure without searching. I can not use __weak here; even if my local reference is…
Steven Fisher
  • 44,462
  • 20
  • 138
  • 192
22
votes
2 answers

Python: which types support weak references?

Code: from weakref import WeakSet se = WeakSet() se.add(1) Output: TypeError: cannot create weak reference to 'int' object Doc: Several built-in types such as list and dict do not directly support weak references but can add support through…
Cyker
  • 9,946
  • 8
  • 65
  • 93
22
votes
2 answers

weak vs unowned in Swift. What are the internal differences?

I understand the usage and superficial differences between weak and unowned in Swift: The simplest examples I've seen is that if there is a Dog and a Bone, the Bone may have a weak reference to the Dog (and vice versa) because the each can exist…
ephemer
  • 1,239
  • 8
  • 21
22
votes
1 answer

Why is the implementation of events in C# not using a weak event pattern by default?

This question may lead to speculative answers but I presume there's a well thought design decision behind the implementation of event in c#. The event pattern in c# keeps the subscriber alive as long as the publisher of the event is alive. Thus, if…
Krumelur
  • 32,180
  • 27
  • 124
  • 263