Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Weak reference
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Examples== Weak references can be useful when keeping a list of the current variables being referenced in the application. This list must have weak links to the objects. Otherwise, once objects are added to the list, they will be referenced by it and will persist for the duration of the program. ===Java=== Java 1.2 in 1998 introduced<ref>{{cite web|url=http://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html|title=WeakReference (Java Platform SE 7 )|website=docs.oracle.com}}</ref> two kinds of weak references, one known as a "soft reference" (intended to be used for maintaining GC-managed in-memory caches, but which doesn't work very well in practice on some platforms with dynamic heap like Android<ref>{{cite web|url=https://developer.android.com/reference/java/lang/ref/SoftReference.html|title=SoftReference - Android Developers|website=developer.android.com}}</ref>) and the other simply as a "weak reference". It also added a related experimental mechanism dubbed "phantom references" as an alternative to the dangerous and inefficient finalize() mechanism.<ref>{{cite web|url=http://docs.oracle.com/javase/7/docs/api/java/lang/ref/PhantomReference.html|title=PhantomReference (Java Platform SE 7 )|website=docs.oracle.com}}</ref> If a weak reference is created, and then elsewhere in the code <code>get()</code> is used to get the actual object, the weak reference is not strong enough to prevent garbage collection, so it may be (if there are no strong references to the object) that <code>get()</code> suddenly starts returning null.<ref>https://web.archive.org/web/20110303225354/http://weblogs.java.net/blog/2006/05/04/understanding-weak-references Java Examples</ref> <syntaxhighlight lang=java> import java.lang.ref.WeakReference; public class ReferenceTest { public static void main(String[] args) throws InterruptedException { WeakReference r = new WeakReference("I'm here"); StrongReference sr = new StrongReference("I'm here"); System.out.println("Before gc: r=" + r.get() + ", static=" + sr.get()); System.gc(); Thread.sleep(100); // Only r.get() becomes null. System.out.println("After gc: r=" + r.get() + ", static=" + sr.get()); } } </syntaxhighlight> Another use of weak references is in writing a [[cache (computing)|cache]]. Using, for example, a weak [[hash map]], one can store in the cache the various referred objects via a weak reference. When the garbage collector runs — when for example the application's memory usage gets sufficiently high — those cached objects which are no longer directly referenced by other objects are removed from the cache. ===Smalltalk=== <syntaxhighlight lang=Smalltalk> |a s1 s2| s1 := 'hello' copy. "that's a strong reference" s2 := 'world' copy. "that's a strong reference" a := WeakArray with:s1 with:s2. a printOn: Transcript. ObjectMemory collectGarbage. a printOn: Transcript. "both elements still there" s1 := nil. "strong reference goes away" ObjectMemory collectGarbage. a printOn: Transcript. "first element gone" s2 := nil. "strong reference goes away" ObjectMemory collectGarbage. a printOn: Transcript. "second element gone" </syntaxhighlight> ===Lua=== <syntaxhighlight lang="lua"> weak_table = setmetatable({}, {__mode="v"}) weak_table.item = {} print(weak_table.item) collectgarbage() print(weak_table.item) </syntaxhighlight> ===Objective-C 2.0=== In [[Objective-C]] 2.0, not only garbage collection, but also [[Reference counting|automatic reference counting]] will be affected by weak references. All variables and properties in the following example are weak. <syntaxhighlight lang=objc> @interface WeakRef : NSObject { __weak NSString *str1; __unsafe_unretained NSString *str2; } @property (nonatomic, weak) NSString *str3; @property (nonatomic, unsafe_unretained) NSString *str4; @end </syntaxhighlight> The difference between <code>weak</code> (<code>__weak</code>) and <code>unsafe_unretained</code> (<code>__unsafe_unretained</code>) is that when the object the variable pointed to is being deallocated, whether the value of the variable is going to be changed or not. <code>weak</code> ones will be updated to [[Null pointer|<code>nil</code>]] and the <code>unsafe_unretained</code> one will be left unchanged, as a [[dangling pointer]]. The <code>weak</code> references is added to Objective-C since [[Mac OS X Lion|Mac OS X 10.7 "Lion"]] and [[iOS 5]], together with [[Xcode]] 4.1 (4.2 for iOS), and only when using ARC. Older versions of Mac OS X, iOS, and GNUstep support only <code>unsafe_unretained</code> references as weak ones. ===[[Vala (programming language)|Vala]]=== <syntaxhighlight lang="vala"> class Node { public weak Node prev; // a weak reference is used to avoid circular references between nodes of a doubly-linked list public Node next; } </syntaxhighlight> ===Python=== <syntaxhighlight lang="pycon"> >>> import weakref >>> import gc >>> class Egg: ... def spam(self): ... print("I'm alive!") ... >>> obj = Egg() >>> weak_obj = weakref.ref(obj) >>> weak_obj().spam() I'm alive! >>> obj = "Something else" >>> gc.collect() 35 >>> weak_obj().spam() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'spam' </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)