Weak reference

In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced only by weak references – meaning "every chain of references that reaches the object includes at least one weak reference as a link" – is considered weakly reachable, and can be treated as unreachable and so may be collected at any time. Some garbage-collected languages feature or support various levels of weak references, such as C#, Lua, Java, Lisp, OCaml, MATLAB[1], Perl, Python[2] and PHP since the version 7.4.[3]

Uses

Weak references have a number of common uses. When using reference counting garbage collection, weak references can break reference cycles, by using a weak reference for a link in the cycle. When one has an associative array (mapping, hash map) whose keys are (references to) objects, for example to hold auxiliary data about objects, using weak references for the keys avoids keeping the objects alive just because of their use as keys. When one has an object where other objects are registered, such as in the observer pattern (particularly in event handling), if a strong reference is kept, objects must be explicitly unregistered, otherwise a memory leak occurs (the lapsed listener problem), while a weak reference removes the need to unregister. When holding cached data that can be recreated if necessary, weak references allow the cache to be reclaimed, effectively producing discardable memory. This last case (a cache) is distinct from others, as it is preferable that the objects only be garbage collected if necessary, and there is thus a need for finer distinctions within weak references, here a stronger form of a weak reference. In many cases weak references do not need to be directly used, instead simply using a weak array or other container whose keys or values are weak references.

Garbage collection

Garbage collection is used to clean up unused objects and so reduce the potential for memory leaks and data corruption. There are two main types of garbage collection: tracing and reference counting. Reference counting schemes record the number of references to a given object and collect the object when the reference count becomes zero. Reference-counting cannot collect cyclic (or circular) references because only one object may be collected at a time. Groups of mutually referencing objects which are not directly referenced by other objects and are unreachable can thus become permanently resident; if an application continually generates such unreachable groups of unreachable objects this will have the effect of a memory leak. Weak references (references which are not counted in reference counting) may be used to solve the problem of circular references if the reference cycles are avoided by using weak references for some of the references within the group.

A very common case of such strong vs. weak reference distinctions is in tree structures, such as the Document Object Model (DOM), where parent-to-child references are strong, but child-to-parent references are weak. For example, Apple's Cocoa framework recommends this approach.[4] Indeed, even when the object graph is not a tree, a tree structure can often be imposed by the notion of object ownership, where ownership relationships are strong and form a tree, and non-ownership relationships are weak and not needed to form the tree – this approach is common in C++ (pre-C++11), using raw pointers as weak references. This approach, however, has the downside of not allowing the ability to detect when a parent branch has been removed and deleted. Since the C++11 standard, a solution was added by using shared_ptr and weak_ptr, inherited from the Boost library.

Weak references are also used to minimize the number of unnecessary objects in memory by allowing the program to indicate which objects are of minor importance by only weakly referencing them.[citation needed]

Variations

Some languages have multiple levels of weak reference strength. For example, Java has, in order of decreasing strength, soft, weak, and phantom references, defined in the package java.lang.ref.[5] Each reference type has an associated notion of reachability. The garbage collector (GC) uses an object's type of reachability to determine when to free the object. It is safe for the GC to free an object that is softly reachable, but the GC may decide not to do so if it believes the JVM can spare the memory (e.g. the JVM has much unused heap space). The GC will free a weakly reachable object as soon as the GC notices the object. Unlike the other reference types, a phantom reference cannot be followed. On the other hand, phantom references provide a mechanism to notify the program when an object has been freed (notification is implemented using ReferenceQueues).

In C#, weak references are distinguished by whether they track object resurrection or not. This distinction does not occur for strong references, as objects are not finalized if they have any strong references to them. By default, in C# weak reference do not track resurrection, meaning a weak reference is not updated if an object is resurrected; these are called short weak references, and weak references that track resurrection are called long weak references.[6]

Some non-garbage-collected languages, such as C++, provide weak/strong reference functionality as part of supporting garbage collection libraries. The Boost C++ library provides strong and weak references. It is a mistake to use regular C++ pointers as the weak counterparts of smart pointers because such usage removes the ability to detect when the strong reference count has gone to 0 and the object has been deleted. Worse yet, it does not allow for detection of whether another strong reference is already tracking a given plain pointer. This introduces the possibility of having two (or more) smart pointers tracking the same plain pointer (which causes corruption as soon as one of these smart pointers' reference count reaches 0 and the object gets deleted).

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[7] 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[8]) 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.[9]

If a weak reference is created, and then elsewhere in the code get() 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 get() suddenly starts returning null.[10]

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());
    }
}

Another use of weak references is in writing a 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

|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"

Lua

weak_table = setmetatable({}, {__mode="v"})
weak_table.item = {}
print(weak_table.item)
collectgarbage()
print(weak_table.item)

Objective-C 2.0

In Objective-C 2.0, not only garbage collection, but also automatic reference counting will be affected by weak references. All variables and properties in the following example are weak.

@interface WeakRef : NSObject
{
    __weak NSString *str1;
    __unsafe_unretained NSString *str2;
}

@property (nonatomic, weak) NSString *str3;
@property (nonatomic, unsafe_unretained) NSString *str4;

@end

The difference between weak (__weak) and unsafe_unretained (__unsafe_unretained) 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. weak ones will be updated to nil and the unsafe_unretained one will be left unchanged, as a dangling pointer. The weak references is added to Objective-C since 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 unsafe_unretained references as weak ones.

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;
}

Python

>>> 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'

See also

References

  1. ^ [1]
  2. ^ 8.8. weakref — Weak references, The Python Standard Library
  3. ^ "PHP: WeakReference - Manual".
  4. ^ "Practical Memory Management". developer.apple.com.
  5. ^ Nicholas, Ethan (May 4, 2006). "Understanding Weak References". java.net. Archived from the original on 2011-03-03. Retrieved October 1, 2010.
  6. ^ Goldshtein, Zurbalev & Flatow 2012, p. 131.
  7. ^ "WeakReference (Java Platform SE 7 )". docs.oracle.com.
  8. ^ "SoftReference - Android Developers". developer.android.com.
  9. ^ "PhantomReference (Java Platform SE 7 )". docs.oracle.com.
  10. ^ https://web.archive.org/web/20110303225354/http://weblogs.java.net/blog/2006/05/04/understanding-weak-references Java Examples

C++

Java

PHP

Python

Read other articles:

Bendera Aliansi Teh Susu dibuat oleh netizen (Warna bendera berbelok dari kiri melambangkan teh susu Thailand, teh susu Hong Kong dan teh susu Taiwan) Aliansi Teh Susu (Inggris: Milk Tea Alliancecode: en is deprecated ) adalah sebuah istilah yang dipakai untuk menyebut gerakan solidaritas demokrat daring yang terdiri dari para warganet dari Thailand, Hong Kong, dan Taiwan. Istilah tersebut awalnya dimulai sebagai sebuah meme dan berubah menjadi gerakan protes lintas nasional dinamis untuk men...

 

Untuk maskapai penerbangan dengan nama yang mirip, lihat Ryan Airlines. Ryanair IATA ICAO Kode panggil FR RYR RYANAIR Didirikan28 November 1984Mulai beroperasi8 Juli 1985Pusat operasi Daftar basis AlgheroAlicanteBarcelonaBariBillundBirminghamBolognaBournemouthBremenBrindisiBristolBrussels/CharleroiBudapestCagliariChania [dibuka 1 April 2013]CorkDublin (Headquarters)East MidlandsEdinburghEindhoven [dibuka 1 April 2013]FaroFez [dibuka 1 April 2013]GironaGlasgow-PrestwickGran CanariaHahnKarlsruh...

 

Prisoner of the MountainsPoster rilis teatrikalSutradaraSergei BodrovProduserBoris GillerDitulis olehBoris Giller, Arif Aliyev, Sergei BodrovCeritaBoris GillerPenata musikLeonid DesyatnikovSinematograferPavel LebeshevPenyuntingAlan BarilOlga GrinshpunVera KruglovaDistributorOrion ClassicsTanggal rilis1996Durasi98 menitNegaraRusiaKazakhstanBahasaRusia Prisoner of the Mountains (Rusia: Кавказский пленникcode: ru is deprecated , Kavkazskiy plennik), yang juga dikenal sebag...

العلاقات اليمنية الإريترية اليمن إريتريا   اليمن   إريتريا تعديل مصدري - تعديل   العلاقات اليمنية الإريترية هي العلاقات الثنائية التي تجمع بين اليمن وإريتريا.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه المقارنة الي�...

 

John dari BretagneEarl of RichmondLambang John dari BretagneBerkuasa1306–1334PendahuluYann II dari BretagnePenerusYann III dari BretagneAyahYann II dari BretagneIbuBeatrice dari InggrisPasanganTidak menikah John dari Bretagne atau Jean de Bretagne (skt. tahun 1266 – 17 Januari 1334) Earl Ketiga Richmond, merupakan seorang berkebangsaan Inggris bangsawan dari Prancis/asal Breton. Ia bekerja di bawah Edward I, dan berperang di dalam Perang Skotlandia. Pada tanggal 15 Oktober 1306 ia me...

 

Paul McShane McShane bermain untuk Hull CityInformasi pribadiNama lengkap Paul David McShane[1]Tanggal lahir 6 Januari 1986 (umur 38)[1]Tempat lahir Kilpedder, Republik IrlandiaTinggi 1,83 m (6 ft 0 in)Posisi bermain BekInformasi klubKlub saat ini Manchester UnitedNomor 62Karier junior St Joseph's Boys2002–2004 Manchester UnitedKarier senior*Tahun Tim Tampil (Gol)2004–2006 Manchester United 0 (0)2004–2005 → Walsall (pinjaman) 4 (1)2005–2006 → B...

André Brasil Nazionalità  Brasile Nuoto Specialità 100 m stile libero200 m farfalla Palmarès  Paralimpiadi Oro Pechino 2008 50 m Stile libero S10 Oro Pechino 2008 100 m Stile libero S10 Oro Pechino 2008 400 m Stile libero S10 Oro Pechino 2008 100 m Farfalla S10 Argento Pechino 2008 200 m Misti S10   Modifica dati su Wikidata · Manuale André Brasil Esteves (23 maggio 1984) è un nuotatore brasiliano. Ha vinto l'oro per il Brasile ai XIII Giochi paralimpici estivi, ol...

 

Earthquake in South Asia Kashmir earthquake redirects here. For the 1555 earthquake, see 1555 Kashmir earthquake. For the 1885 earthquake, see 1885 Kashmir earthquake. For the 2019 earthquake, see 2019 Kashmir earthquake. 2005 Kashmir earthquakeClockwise from top left: Destroyed building, Muzaffarabad Pakistani soldiers unload relief supplies from a U.S. Navy helicopter, Balakot U.S. Navy Hospitalman holds an injured three-year-old boy, Shinkiari Destroyed building, Nardjan U.S. Army helicopt...

 

 烏克蘭總理Прем'єр-міністр України烏克蘭國徽現任杰尼斯·什米加尔自2020年3月4日任命者烏克蘭總統任期總統任命首任維托爾德·福金设立1991年11月后继职位無网站www.kmu.gov.ua/control/en/(英文) 乌克兰 乌克兰政府与政治系列条目 宪法 政府 总统 弗拉基米尔·泽连斯基 總統辦公室 国家安全与国防事务委员会 总统代表(英语:Representatives of the President of Ukraine) 总...

2013 American film by J.H. Wyman and Niels Arden Oplev Dead Man DownTheatrical release posterDirected byNiels Arden OplevWritten byJ.H. WymanProduced by Neal H. Moritz J.H. Wyman Starring Colin Farrell Noomi Rapace Dominic Cooper Terrence Howard Isabelle Huppert CinematographyPaul CameronEdited by Timothy A. Good Frédéric Thoraval Music byJacob GrothProductioncompanies Original Film Frequency Films IM Global WWE Studios Distributed byFilmDistrictRelease date March 8, 2013 (20...

 

International athletics championship event5th IAAF World Indoor ChampionshipsDates10 March–12 MarchHost cityBarcelona, Catalonia, SpainVenuePalau Sant JordiEvents27Participation594 athletes from 131 nations← 1993 Toronto 1997 Paris → The 5th IAAF World Indoor Championships in Athletics were held at the Palau Sant Jordi in Barcelona, Catalonia, Spain from 10 March to 12 March 1995. Almost 600 athletes from 131 nations participated in 27 events. Results Men Event Gold Silver Bronz...

 

US federal government agency Bureau of Economic AnalysisLogo of the Bureau of Economic AnalysisAgency overviewFormedJanuary 1, 1972; 52 years ago (1972-01-01)Preceding agencyOffice of Business EconomicsHeadquartersSuitland, MDEmployees500Annual budget$101 million (FY2019)Agency executivesVipin Arora, DirectorPatricia Abaroa, Deputy Director;Parent departmentDepartment of CommerceWebsitewww.bea.gov The Bureau of Economic Analysis (BEA) of the United States Department of Comme...

Vessel filled with a superheated transparent liquid Fermilab's disused 15-foot (4.57 m) bubble chamber The first tracks observed in John Wood's 1.5-inch (3.8 cm) liquid hydrogen bubble chamber, in 1954. A bubble chamber is a vessel filled with a superheated transparent liquid (most often liquid hydrogen) used to detect electrically charged particles moving through it. It was invented in 1952 by Donald A. Glaser,[1] for which he was awarded the 1960 Nobel Prize in Physics. ...

 

Period of the US Supreme Court in 1795 Supreme Court of the United StatesRutledge CourtJay Court ← → Ellsworth CourtChief Justice John RutledgeAugust 12, 1795 – December 28, 1795(138 days)SeatOld City HallPhiladelphia, PennsylvaniaNo. of positions6Rutledge Court decisions The Rutledge Court refers to the Supreme Court of the United States from June to December 1795, when John Rutledge served as the second Chief Justice of the United States. Rutledge took office as a reces...

 

Textural form of igneous rock with large grained crystals in a fine matrix This article is about the igneous rock. For other uses, see Porphyry. Not to be confused with Copper porphyry. Imperial Porphyry from the Red Sea Mountains of Egypt A waterworn cobble of porphyry Rhyolite porphyry from Colorado; scale bar in lower left is 1 cm (0.39 in) Porphyry (/ˈpɔːrfəri/ POR-fə-ree) is any of various granites or igneous rocks with coarse-grained crystals such as feldspar or quartz di...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يوليو 2019) بريت غرانت   معلومات شخصية الميلاد 1 فبراير 1978 (46 سنة)  أتلانتا  مواطنة الولايات المتحدة  الحياة العملية المدرسة الأم كلية ستانفورد للحقوق  [لغ�...

 

  لمعانٍ أخرى، طالع مردان (توضيح). مردان   تقسيم إداري البلد باكستان  [1] عاصمة لـ ناحية مردان المسؤولون العمدة حماة الله ميار[2](حزب عوامي الوطني) خصائص جغرافية إحداثيات 34°11′45″N 72°02′41″E / 34.195833333333°N 72.044722222222°E / 34.195833333333; 72.044722222222   المساحة 632 ك�...

 

Refly HarunLahir26 Januari 1970 (umur 54)Palembang, Sumatera Selatan, IndonesiaAlmamaterUniversitas Gadjah MadaUniversitas IndonesiaUniversitas Notre DameUniversitas AndalasPekerjaanDosen, pengacaraDikenal atasPakar hukum tata negaraSuami/istriYuyun Hairunisa, S.H., M.Kn. ​ ​(m. 1996)​Anak2Informasi YouTubeKanal Refly Harun Tahun aktif2020–sekarangGenreBeritaPelanggan3,25 juta[1](Hingga 5 Juli 2024[update])Total ta...

Chemical compound Not to be confused with Cofactor F430. Structure of Coenzyme F420 Coenzyme F420 is a family of coenzymes involved in redox reactions in a number of bacteria and archaea. It is derived from coenzyme FO (7,8-didemethyl-8-hydroxy-5-deazariboflavin) and differs by having a oligoglutamyl tail attached via a 2-phospho-L-lactate bridge. F420 is so named because it is a flavin derivative with an absorption maximum at 420 nm. F420 was originally discovered in methanogenic archaea[...

 

SvijanyComune Svijany – Veduta LocalizzazioneStato Rep. Ceca Regione Liberec DistrettoLiberec AmministrazioneSindacoPetr Lelek TerritorioCoordinate50°34′22″N 15°03′26″E50°34′22″N, 15°03′26″E (Svijany) Altitudine255 m s.l.m. Superficie2,70[1] km² Abitanti301[2] (1-1-2011) Densità111,48 ab./km² Altre informazioniCod. postale463 46 Fuso orarioUTC+1 Codice ČSÚCZ564443 TargaLB CartografiaSvijany Sito istituzionaleModifica da...