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.

Filter by
Sorted by
Tagged with
0 votes
1 answer
50 views

How do I avoid memory leaks when calling async functions in a Timer.scheduledTimer's repeating code?

I am using an SDK which initiates a download, and am trying to build resiliency into my app if the app is closed before the download is complete. If the app is closed while the download still is ...
ADC2000's user avatar
  • 63
-1 votes
2 answers
436 views

How can I prevent a DOM node removed from its tree from being held by spurious strong references, like from closures?

For a toy example, suppose I have a clock widget: { const clockElem = document.getElementById('clock'); const timefmt = new Intl.DateTimeFormat( 'default', { timeStyle: 'medium', }); ...
user3840170's user avatar
1 vote
0 answers
69 views

python performs a deepcopy of a weakref.proxy's content. Why? Which entity owns the reference?

I wanted to double check my assumption, that the content of a weakref.proxy is not deepcopied when performing a deepcopy of it. To that end, I wrote the following code snippet: import copy import ...
mutableVoid's user avatar
  • 1,354
1 vote
0 answers
52 views

ConditionalWeakTable works differently in .Net 7.0 and .Net Framework 4.8? [duplicate]

Here's something that is really mind boggling. I discover that ConditionalWeakTable is working differently in .Net 7.0 and .Net Framework 4.8. I get the code straight from here: public class Program { ...
Graviton's user avatar
  • 82k
1 vote
1 answer
143 views

Weak binding to model properties from subview

I've encountered memory leak in SwiftUI view's models when using bindings. I've created ObservableObject model like final class Model: ObservableObject { @Published var selectedValue: String? } ...
Michał Ziobro's user avatar
0 votes
1 answer
23 views

Will WeakSet be garbage collected if values are used as keys in Map?

I have some HTML elemenets that are used as keys in ES6 Maps, I also have a "WeakSet" which contains those same HTML elements as values, now those HTML elements will eventually be removed ...
Djordje Vuckovic's user avatar
1 vote
1 answer
67 views

Difference between unowned var something: Something! and weak var something: Something! in Swift

Consider the following example given below: protocol Something: AnyObject { func f() } class A { unowned var something1: Something! weak var something2: Something! func f() { ...
Roman Podymov's user avatar
1 vote
0 answers
222 views

Parent/Child relationship - should parent be weak?

Normally, in a parent/child relationship, the parent property in the Child class would need to be weak. For example: class Parent { var children: [Child] } class Child { weak var parent: ...
HangarRash's user avatar
  • 10.1k
1 vote
0 answers
25 views

ConditionalWeakTable example doesn't work? [duplicate]

I'm playing around with ConditionalWeakTable for the first time, so I figured I'd run the example from the docs. This doesn't compile out of the box... I had to change this: else if (cwt.TryGetValue(...
James Crosswell's user avatar
0 votes
1 answer
52 views

Weak referenced Passthrough Subject doesn't send input

I'm trying some patterns and at some point I realised my passthrough subject doesn't send anything when self is weak. Here what i did : import Foundation import Combine class ViewModel { var ...
incelemeTRe's user avatar
2 votes
1 answer
60 views

How to intern objects with weakref/gc support?

I'm trying to implement interning of non-string objects in python. For strings we have the sys.intern function. However it doesn't support other immutable objects. To put it out of the way, I'm aware ...
Yakov Galka's user avatar
  • 71.1k
6 votes
1 answer
232 views

In Rust, how does Weak<T> know when the inner value has been dropped?

std::rc::Weak<T> has the following definition: pub struct Weak<T: ?Sized> { ptr: NonNull<RcBox<T>>, } In my understanding, when there's no more Rc<T> left, RcBox<...
Calogyne's user avatar
0 votes
0 answers
65 views

garbage collection in python threading

When implementing a thread that is intended to periodically read from a stream, I cannot manage to make the thread stop correctly. This is only the case when the callback function that I use is ...
Pascal's user avatar
  • 926
0 votes
1 answer
61 views

Danger of java code optimization for the usage of the weak references to strong references remembered in local variables? [closed]

I have faced the problem sometimes my weak reference to some object just disappeared, even if I had the strong reference remembered in the local variable. But it seems to me this can have something to ...
Artur Linhart's user avatar
1 vote
1 answer
87 views

Adding WeakReferences into HashMap via #compute - may I get null or not?

Let's say I have following implementation of cache, purposed to associate some data (connection pool in my case) with the latest state/version of another object: public class Demo<V> { ...
Andrey B. Panfilov's user avatar
3 votes
2 answers
462 views

Weak reference doesn't work as expected when passing it as a method reference

I am already aware of the strong/weak reference concept in swift. yet after running the next code, and tapping on the Button (and dismissing the screen), the TestViewModel stayed in memory! I was ...
vigdora's user avatar
  • 339
0 votes
1 answer
100 views

In Swift, if BOTH the parent and child classes have weak references, then what will happen?

When implementing code in Swift, we always are careful to avoid retaining the cycle, and we avoid using weak or unowned. What will happen if we declare weak for all references, all variables/...
Akshay Pure's user avatar
0 votes
1 answer
265 views

Fragment Memory Leak during FragmentTransaction Android Studio

I am using LeakCanary to monitor memory leaks in my mobile app in Android Studio. They were found in an activity that makes a FragmentTransaction operation with two Fragments. They are both ...
Samy Sylvester's user avatar
0 votes
0 answers
87 views

Android Coroutines and WeakReferences

To avoid activity leaks when using threads, handlers, etc, I always wrap the Activity, View, Context, etc., in a WeakReference, so: val textViewRef = WeakReference(textView) thread { ..... ...
API_1024's user avatar
  • 509
4 votes
1 answer
394 views

What's the benefit of asyncio using weakrefs to keep track of tasks?

Python docs for asyncio.create_task state: Important: Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. ...
max's user avatar
  • 49.8k
0 votes
1 answer
66 views

How to get a consistent WeakSet length during finalization?

Consider the following code which uses a WeakSet at the same time as a finalizer: >>> import weakref >>> import gc >>> class A: ... pass >>> class Parent: ... ...
F.X.'s user avatar
  • 6,919
1 vote
0 answers
145 views

How can I use PartialEq with circular Rc or Weak?

I have the following struct and when I try to call assert_eq!() on an instance of this struct I get a stack overflow due to the circular reference. I tried replacing Rc in the parent with Weak but I ...
Danilo Souza Morães's user avatar
0 votes
2 answers
93 views

Rc::downgrade does not seem to drop ownership in a Rust program

I'm trying to create a simple minesweeper in Rust. For this I want to create a Grid object, holding all Case objects. When a Case is clicked, it notifies the Grid. I want all cases to have a Weak ...
timete_os's user avatar
1 vote
1 answer
176 views

How to inject WeakReference Fragment using Koin - Android

I have a class that relies on WeakReference<Fragment>. class ExampleManager(reference: WeakReference<Fragment>) How would I inject ExampleManager constructor? val exampleModule = module {...
MaaAn13's user avatar
  • 286
0 votes
2 answers
95 views

Wrong result when comparing ref and WeakMethod in Python?

I'm using a set to hold weak references to callables. These can be functions, callable instances (i.e. using the __call__ method), and bound methods. Following the docs, I'm using weakref.WeakMethod ...
bavaza's user avatar
  • 10.6k
1 vote
2 answers
375 views

How do I clone a “WeakMap” or “WeakSet” in Javascript?

I know that WeakMap and WeakSet are not iterable for security reasons, that is, “to prevent attackers from seeing the garbage collector’s internal behavior,” but then, this means you cannot clone a ...
Константин Ван's user avatar
1 vote
0 answers
41 views

Does cross-referencing in WeakMap prevent garbage collection? [duplicate]

I'm extending this question: Would a "circular" reference be treated as "reachability" for a WeakMap? If I have 2 WeakMaps that have entries whose values cross references the keys, ...
Miloš Šimek's user avatar
0 votes
1 answer
198 views

Rust learning question tree example. Update element inside Rc

I'm studying rust and I'm stuck on a question about Rc, Weak and RefCell. The use case is to implement a fully functioning tree, where each node has one parent and a list of children. The ...
hasdrubal's user avatar
  • 1,076
0 votes
2 answers
325 views

How to garbage collect callbacks with weak references in Java?

I'm reading Effective Java by Joshua Bloch. In Item 7: Eliminate Obsolete Object References of chapter 2 he states: A third common source of memory leaks is listeners and other callbacks. If you ...
Rahul's user avatar
  • 583
1 vote
1 answer
59 views

Does ConditionalWeakTable<TKey, TValue> guarantee insertion order?

As the title already says, is insertion order guaranteed by ConditionalWeakTable<TKey, TValue>? Couldn't find any answers for this on the internet, and it doesn't inherit any other collection ...
Christoph Mett's user avatar
0 votes
1 answer
56 views

Pythonic way to filter a list of weakrefs

I really dislike this approach to loop a list of weakrefs, see if they're still not garbage collected and if they're not perform some operation on the item and then later remove all those stale refs ...
Dean's user avatar
  • 6,730
0 votes
1 answer
42 views

How can I cache where a value has a strong reference to its key?

I have class whose instances can create a self-wrapped copy of its own. class Some { static class Nullable extends Some { Nullable(Some wrapped) { this.wrapped = wrapped; } @...
Jin Kwon's user avatar
  • 20.7k
3 votes
2 answers
219 views

ConditionalWeakTable - GC.Collect() behavior, why it does not operate as expected?

Why my weakRef.Target is still alive on the second shot? Could it be a bug? If not, where is the error? Result: weakRef.Target is alive = True, expected true because inst keep a hold on SomeClass. ...
Eric Ouellet's user avatar
  • 11.2k
1 vote
0 answers
37 views

Unexpected behavior of object life with WeakReference usage [duplicate]

This is my code,the results and expected results. Why alive = true instead of false on second line? Results: weakRef.Target is alive = True, expected true because inst keep a hold on SomeClass. ...
Eric Ouellet's user avatar
  • 11.2k
0 votes
0 answers
205 views

Using weak references with structs with lifetime parameters

I want to implement the observer pattern using Weak smart pointers. Ideally this would look something like the following (playground): use std::cell::RefCell; use std::rc::{Rc, Weak}; struct ...
frankplow's user avatar
  • 502
3 votes
2 answers
5k views

KeyError: <weakref at 0x7fc9e8267ad0; to 'Flask' at 0x7fc9e9ec5750>

I've been having a hard time handling sessions in flask. Since when I manage the application in the local environment everything works perfectly, including flask sessions. But when i already host it ...
Jose Joel Vargas Martinez's user avatar
1 vote
0 answers
107 views

Should classes that have events always implement IDisposable and set them to null?

Implementing IDisposable in every class that has a c# event/delegate is wrong? The dispose code would simply set all the events of the class to null to prevent leaks¹. But I don't see anyone doing it, ...
Andre S.'s user avatar
3 votes
1 answer
128 views

WeakKeyDictionary with tuple of objects as key

I want to use a WeakKeyDictionary where the keys are tuples of other objects, e.g. of type Tuple[A,B], in such a way: # a,b,c defined somewhere d = WeakKeyDictionary() d[(a, b)] = c This does not ...
Albert's user avatar
  • 66k
0 votes
0 answers
40 views

Keeping an object in memory if two other objects hold references

I have three objects: a Query, a Document, and an Index. A Query uses an Index to speed up access to a Document. An Index is specific to a (Query, Document) pair; a Query may have multiple indexes for ...
Michael Kay's user avatar
1 vote
1 answer
411 views

Avoiding objects garbage collection

TLDR: How can I force the JVM not to garbage collect my objects, even if I don't want to use them in any meaningful way? Longer story: I have some Items which are loaded from a permanent storage and ...
fonadius's user avatar
3 votes
0 answers
151 views

__attribute__((weakref)) not work for external function

Recently I 'm studying the linking process and when it comes to weak symbol, my textbook give a code below to demonstrate how to use __attribute__((weakref)) to declare a weak reference to external ...
NO3's user avatar
  • 31
1 vote
1 answer
562 views

Testing against memory leaks in Kotlin Native

The following Kotlin Native test code uses weak references and manual triggering of garbage collection in the hope of ensuring objects have been reclaimed (rationale: if this works correctly then this ...
Tom's user avatar
  • 4,930
2 votes
1 answer
51 views

Java: WeakReference.get() returns differently after System.gc()

I tried to see when weak reference returns null by get(): String string = new String("abc"); WeakReference<String> wi = new WeakReference<>(string); WeakReference<String> ...
Immanuel Kant's user avatar
0 votes
0 answers
90 views

Strategies for debugging/finding weak references in python?

In trying to pickle an object I get the following error: ReferenceError Traceback (most recent call last) /Users/rhys/phd-work/tmp-design-test.py in <cell line: 125>() ...
Goods's user avatar
  • 225
0 votes
0 answers
41 views

Do I use WeakReference correctly

I am building a javaagent, which help people to find leaked JDBC connections. When client code creates a connection, my agent will record the stacktrace which called to create that connection, the ...
WestFarmer's user avatar
1 vote
1 answer
383 views

How do I make an exit handler that runs after all weakref finalizers run

I have a module meant to be consumed as a library by other programs. I am using weakref.finalize to register cleanup functions for these objects, and atexit.register for some top level cleanup. I ...
Craig White's user avatar
0 votes
1 answer
107 views

Returning iterator from weak references for mapping and modifying values

I'm trying quite complex stuff with Rust where I need the following attributes, and am fighting the compiler. Object which itself lives from start to finish of application, however, where internal ...
tradinggy's user avatar
  • 1,221
2 votes
1 answer
307 views

How can I access the weakref object of the class itself through the class?

As far as I know, __weakref__ is a descriptor defined in class, so that if it invoked from the instances of the class, it will give the weakref object: from weakref import ref class A: pass obj =...
S.B's user avatar
  • 13.8k
0 votes
1 answer
116 views

Strange behavior with `weakref` in IPython

While coding a cache class for one of my projects I wanted to try out the weakref package as its functionality seems to fit this purpose very well. The class is supposed to cache blocks of data from ...
Cubi73's user avatar
  • 1,901
2 votes
1 answer
131 views

weakref (WeakKeyDictionary) to frame (FrameType) objects

I want to have a dict mapping from active frame (FrameType) objects to some data. Active meaning that it is in the current execution stack trace. However, holding a reference to the frame object is ...
Albert's user avatar
  • 66k

1
2 3 4 5
23