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.

weak-references
Filter by
Sorted by
Tagged with
915 votes
12 answers
256k views

What's the difference between SoftReference and WeakReference in Java?

What's the difference between java.lang.ref.WeakReference and java.lang.ref.SoftReference ?
driekken's user avatar
  • 11.5k
271 votes
6 answers
127k views

Always pass weak reference of self into block in ARC?

I am a little confused about block usage in Objective-C. I currently use ARC and I have quite a lot of blocks in my app, currently always referring to self instead of its weak reference. May that be ...
the_critic's user avatar
  • 12.8k
264 votes
8 answers
84k views

What is the difference between a weak reference and an unowned reference?

Swift has: Strong References Weak References Unowned References How is an unowned reference different from a weak reference? When is it safe to use an unowned reference? Are unowned references a ...
Ian Ringrose's user avatar
  • 51.5k
235 votes
18 answers
65k views

How do I declare an array of weak references in Swift?

I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa NSPointerArray offers a non-typesafe version of this.
Bill's user avatar
  • 45.4k
214 votes
7 answers
107k views

Java: difference between strong/soft/weak/phantom reference

I have read this article about different types of references in Java (strong, soft, weak, phantom), but I don't really understand it. What is the difference between these reference types, and when ...
user avatar
190 votes
4 answers
108k views

How to use WeakReference in Java and Android development?

I have been a Java developer for 2 years. But I have never written a WeakReference in my code. How to use WeakReference to make my application more efficient, especially the Android application?
Chris's user avatar
  • 6,501
170 votes
10 answers
62k views

When would you use a WeakHashMap or a WeakReference?

The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed ...
18Rabbit's user avatar
  • 3,211
106 votes
1 answer
46k views

Where does the weak self go?

I often do this, let when = DispatchTime.now() + 2.0 DispatchQueue.main.asyncAfter(deadline: when) { beep() } and in one app we often do this tickle.fresh(){ msg in paint() } but if you ...
Fattie's user avatar
  • 17.9k
105 votes
9 answers
35k views

Is it possible to create a "weak reference" in JavaScript?

Is there any way in JavaScript to create a "weak reference" to another object? Here is the wiki page describing what a weak reference is. Here is another article that describes them in Java. ...
Stephen Cagle's user avatar
102 votes
8 answers
30k views

Is there a practical use for weak references? [duplicate]

Possible Duplicate: Weak references - how useful are they? Since weak references can be claimed by the garbage collector at any time, is there any practical reason for using them?
user496949's user avatar
  • 84.7k
89 votes
11 answers
51k views

Why can the keyword "weak" only be applied to class and class-bound protocol types

When I'm declaring variables as weak in Swift, I sometimes get the error message from Xcode: 'weak' may only be applied to class and class-bound protocol types or 'weak' must not be applied to non-...
Thor's user avatar
  • 9,868
83 votes
2 answers
26k views

Why does exist WeakHashMap, but absent WeakSet?

From J. Bloch A ... source of memory leaks is listeners ... The best way to ensure that callbacks are garbage collected promptly is to store only weak references to them, for instance, by ...
Stan Kurilin's user avatar
  • 15.7k
82 votes
4 answers
33k views

What is the difference between a __weak and a __block reference?

I'm reading Xcode's documentation, and here is something that puzzles me: __block typeof(self) tmpSelf = self; [self methodThatTakesABlock:^ { [tmpSelf doSomething]; }]; The following is copied ...
HanXu's user avatar
  • 5,567
82 votes
4 answers
22k views

Understanding Java's Reference classes: SoftReference, WeakReference, and PhantomReference

Can someone explain the difference between the three Reference classes (or post a link to a nice explanation)? SoftReference > WeakReference > PhantomReference, but when would I use each one? Why is ...
Haywood Jablomey's user avatar
78 votes
2 answers
31k views

How does weak_ptr work?

I understand how to use weak_ptr and shared_ptr. I understand how shared_ptr works, by counting the number of references in its object. How does weak_ptr work? I tried reading through the boost source ...
Oliver Zheng's user avatar
  • 7,991
77 votes
14 answers
19k views

Pros and Cons of Listeners as WeakReferences

What are the pros and cons of keeping listeners as WeakReferences? The big 'Pro' of course is that: Adding a listener as a WeakReference means the listener doesn't need to bother 'removing' itself. ...
pdeva's user avatar
  • 44.4k
75 votes
5 answers
30k views

Java's WeakHashMap and caching: Why is it referencing the keys, not the values?

Java's WeakHashMap is often cited as being useful for caching. It seems odd though that its weak references are defined in terms of the map's keys, not its values. I mean, it's the values I want to ...
mxk's user avatar
  • 43.2k
75 votes
3 answers
30k views

Weak reference benefits

Can someone explain the main benefits of different types of references in C#? Weak references Soft references Phantom references Strong references. We have an application that is consuming a lot of ...
leora's user avatar
  • 192k
71 votes
7 answers
25k views

Is there a SoftHashMap in Java?

I know there is a WeakHashMap in java.util, but since it uses WeakReferences for everything, which is only referenced by this Map, referenced objects will get lost on the next GC cycle. So it's nearly ...
tigger's user avatar
  • 1,876
61 votes
2 answers
42k views

Using weak self in dispatch_async function

I read a lot of posts about using __weak self inside dispatch_async, and now I am a litle bit confused. if I have : self.myQueue = dispatch_queue_create("com.biview.core_data", NULL); ...
Marko Zadravec's user avatar
60 votes
3 answers
19k views

WeakReference/AsyncTask pattern in android

I have a question regarding this simple frequently occurring situation in android . We have a main activity , we invoke an AsyncTask alongwith the reference of the mainactivity , so that that the ...
Muhammad Ahmed AbuTalib's user avatar
49 votes
6 answers
41k views

Strong and weak references in Swift

In Objective C you can define a property as having a strong or weak reference like so: @property(strong)... @property(weak)... How is this done in swift?
67cherries's user avatar
  • 6,941
49 votes
3 answers
5k views

Cost of using weak references in Java

Has anyone researched the runtime costs involved in creating and garbage collecting Java WeakReference objects? Are there any performance issues (e.g. contention) for multi-threaded applications? ...
Stephen C's user avatar
  • 709k
45 votes
5 answers
14k views

Is Josh Smith's implementation of the RelayCommand flawed?

Consider the reference Josh Smith' article WPF Apps With The Model-View-ViewModel Design Pattern, specifically the example implementation of a RelayCommand (In Figure 3). (No need to read through the ...
Greg D's user avatar
  • 43.7k
43 votes
1 answer
11k views

How can you capture multiple arguments weakly in a Swift closure?

Is there a way to capture multiple arguments weakly in a swift closure? I know this is the syntax to capture one argument weakly: { [weak arg] arg.doSomething() } How can I do this for two ...
phoganuci's user avatar
  • 5,034
42 votes
3 answers
9k views

When to use weak references in Python?

Can anyone explain usage of weak references? The documentation doesn't explain it precisely, it just says that the GC can destroy the object linked to via a weak reference at any time. Then what's ...
bodacydo's user avatar
  • 77.3k
42 votes
8 answers
12k views

Collections of zeroing weak references under ARC

How can I get an array of zeroing weak references under ARC? I don't want the array to retain the objects. And I'd like the array elements either to remove themselves when they're deallocated, or set ...
paulmelnikow's user avatar
  • 17.1k
41 votes
5 answers
12k views

Weak references - how useful are they?

So I've been mulling over some automatic memory management ideas lately - specifically, I've been looking at implementing a memory manager based on reference counting. Of course, everyone knows that ...
Ken Wayne VanderLinde's user avatar
36 votes
3 answers
33k views

Android Asyntask: Use weak reference for context to avoid device rotate screen

In Apress Pro Android 4 the author has said that: [...] context of currently running activity will no longer be valid when the device is rotated. [...] One approach is to use a weak reference to ...
hqt's user avatar
  • 30k
36 votes
8 answers
20k views

Good implementation of weak dictionary in .Net

Where can I find good implementation of IDictionary which uses weak references inside? Dictionary should be holding only weak references to values and eventually clean up itself of dead references. ...
Konstantin Spirin's user avatar
36 votes
5 answers
7k views

IBOutlet and viewDidUnload under ARC

There is a similar question to this on SO here, however I just want to clarify something that wasn't fully explained there. I understand that all delegates and outlets - in fact any reference to a "...
Stuart's user avatar
  • 36.9k
35 votes
1 answer
4k views

JVM G1GC's mixed gc not collecting much old regions

My server is using 1.8.0_92 on CentOS 6.7, GC param is '-Xms16g -Xmx16g -XX:+UseG1GC'. So the default InitiatingHeapOccupancyPercent is 45, G1HeapWastePercent is 5 and G1MixedGCLiveThresholdPercent is ...
koji lin's user avatar
  • 677
34 votes
10 answers
27k views

Generic typeof for weak self references

I am trying to figure out a way to use typeof to create a weak reference to self for use in blocks to avoid retain cycles. When I first read about this it seems that the convention was to use __block ...
keegan3d's user avatar
  • 10.9k
34 votes
4 answers
24k views

WeakReference and event handling

Is it a good practice to implement event handling through WeakReference if that event is the only thing holding the reference and that we would need the object to be garbage collected? As an ...
33 votes
1 answer
6k views

Should ConditionalWeakTable<TKey, TValue> be used for non-compiler purposes?

I've recently come across the ConditionalWeakTable<TKey,TValue> class in my search for an IDictionary which uses weak references, as suggested in answers here and here. There is a definitive ...
rikoe's user avatar
  • 1,659
32 votes
2 answers
7k views

Is self captured within a nested function

With closures I usually append [weak self] onto my capture list and then do a null check on self: func myInstanceMethod() { let myClosure = { [weak self] (result : Bool) in if ...
Jaja Harris's user avatar
  • 4,418
31 votes
2 answers
23k views

weak or strong for IBOutlet and other [duplicate]

I have switched my project to ARC, and I don't understand if I have to use strong or weak for IBOutlets. Xcode do this: in interface builder, if a create a UILabel for example and I connect it with ...
Piero's user avatar
  • 9,203
30 votes
4 answers
24k views

Using Java's ReferenceQueue

Do SoftReference and WeakReference really only help when created as instance variables? Is there any benefit to using them in method scope? The other big part is ReferenceQueue. Besides being able to ...
bgroenks's user avatar
  • 1,879
30 votes
5 answers
14k views

What's the difference between ES6 Set and WeakSet?

ECMAScript 6 has these very similar collections: Set and WeakSet. What is the difference between them?
Luboš Turek's user avatar
  • 6,443
29 votes
8 answers
11k views

HashMap with weak values

I'm implementing a cache for Objects stored persistently. The idea is: Method getObjectFromPersistence(long id); ///Takes about 3 seconds Method getObjectFromCache(long id) //Instantly And have a ...
Addev's user avatar
  • 32.3k
29 votes
1 answer
7k views

Set equivalent of WeakHashMap?

Is HashSet<WeakReference<T>> the Set equivalent of WeakHashMap<T>? That is, will entries be automatically deleted when they are no longer referenced? If not, what is the equivalent?
Barry Fruitman's user avatar
28 votes
9 answers
8k views

Weak events in .NET?

If object A listens to an event from object B, object B will keep object A alive. Is there a standard implementation of weak events that would prevent this? I know WPF has some mechanism but I am ...
tom7's user avatar
  • 4,102
28 votes
4 answers
3k views

Why isn’t my weak reference cleared right after the strong ones are gone?

I am a little bit stubborn, but I want to understand weak and strong references well, so that's why I'm asking you once again. Consider this: __weak NSString* mySecondPointer = myText; NSLog(@"...
radekEm's user avatar
  • 4,627
27 votes
2 answers
21k views

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 ...
Adam Jenkins's user avatar
  • 53.7k
27 votes
3 answers
17k views

How do events cause memory leaks in C# and how do Weak References help mitigate that?

There are two ways (that I know of) to cause an unintentional memory leak in C#: Not disposing of resources that implement IDisposable Referencing and de-referencing events incorrectly. I don't ...
jnvjgt's user avatar
  • 273
27 votes
3 answers
4k views

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() } } ...
Nirma's user avatar
  • 5,730
27 votes
1 answer
6k views

Is it possible to create a truely weak-keyed dictionary in C#?

I'm trying to nut out the details for a true WeakKeyedDictionary<,> for C#... but I'm running into difficulties. I realise this is a non-trivial task, but the seeming inability to declare a ...
Mania's user avatar
  • 1,728
26 votes
6 answers
8k views

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 ...
ultramiraculous's user avatar
25 votes
1 answer
21k views

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 ...
Sly's user avatar
  • 2,101
25 votes
2 answers
3k views

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 ...
Jason C's user avatar
  • 21.7k

1
2 3 4 5
23