Share to: share facebook share twitter share wa share telegram print page

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, Perl, Python[1] and PHP since the version 7.4.[2]

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.[3] 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.[4] 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.[5]

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

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

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. ^ 8.8. weakref — Weak references, The Python Standard Library
  2. ^ "PHP: WeakReference - Manual".
  3. ^ "Practical Memory Management". developer.apple.com.
  4. ^ Nicholas, Ethan (May 4, 2006). "Understanding Weak References". java.net. Archived from the original on 2011-03-03. Retrieved October 1, 2010.
  5. ^ Goldshtein, Zurbalev & Flatow 2012, p. 131.
  6. ^ "WeakReference (Java Platform SE 7 )". docs.oracle.com.
  7. ^ "SoftReference - Android Developers". developer.android.com.
  8. ^ "PhantomReference (Java Platform SE 7 )". docs.oracle.com.
  9. ^ 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:

This article needs to be updated. Please help update this article to reflect recent events or newly available information. (November 2022)Politics of Latvia Constitution President Edgars Rinkēvičs Government Prime Minister Evika Siliņa Cabinet Siliņa Saeima Speaker Edvards Smiltēns Dissolution Elections Recent elections Saeima: 201420182022 Presidential: 201520192023 European: 201420192024 Political parties JV ZZS AS NA ST! LPV PRO Administrative divisions Planning regions Foreign relations…

الصفحه دى يتيمه, حاول تضيفلها مقالات متعلقه لينكات فى صفحات تانيه متعلقه بيها. كفر ابو حطب البلد التقسيم الادارى مركز ههيا  الارض و السكان الحكم التأسيس والسيادة بيانات تانيه [[تصنيف: غلط فى قوالب ويكى بيانات|]] تعديل مصدري - تعديل   كفر ابو حطب قريه فى محافظة الشرقيه فى مص

Señorío de la Casa de Rubianes Armas de los señores de la Casa de RubianesPrimer titular García de Caamaño de MendozaConcesión Carlos I de España4 de febrero de 1535Linajes de Caamaño, de Mendoza, de Oca, Gayoso, OzoresActual titular Beatriz Ozores y Rey[editar datos en Wikidata] El señorío de la Casa de Rubianes es un señorío jurisdiccional otorgado al fundador de Villagarcía, posteriormente convertido en título nobiliario español.[1]​ El mayorazgo fue fundado el …

Spanish politician and journalist Uxue Barkos9th President of the Government of NavarreIn office20 July 2015 – 6 August 2019Preceded byYolanda BarcinaSucceeded byMaría ChiviteMember of the Parliament of NavarreIncumbentAssumed office 17 June 2015Member of the Congress of DeputiesIn office14 April 2004 – 1 June 2015ConstituencyNavarreMember of the SenateIncumbentAssumed office 17 August 2023ConstituencyParliament of Navarre Personal detailsBornMiren Uxue Barkos …

Radio Trigal FMLocalización San FernandoÁrea de radiodifusión ChileEslogan La pionera de la VI RegiónFrecuencia 103.9 MHz/760 kHz (San Fernando)Primera emisión 17 de enero de 1979 (44 años)Formato Noticias, MisceláneaIdioma EspañolAfiliación ARCHI, AIRPropietario Lucy Bava LaplaceSitio web radiotrigal.cl[editar datos en Wikidata] La Radio Trigal FM es una radio de frecuencia modulada, se encuentra situada en la ciudad de San Fernando. Historia Fue fundada el 17 de enero d…

Foi proposta a fusão deste artigo ou se(c)ção com Mall dos Emirados (pode-se discutir o procedimento aqui). (desde julho de 2021) A tradução deste artigo está abaixo da qualidade média aceitável. Talvez tenha sido feita por um computador ou alguém que não conhece bem o português ou a língua original. Caso queira colaborar com a Wikipédia, Mall of the Emirates e melhore este verbete conforme o guia de tradução. (Setembro de 2021) O Mall of the Emirates é um centro comercial locali…

Región Industrial de Kaesong개성공업지구 Región Administrativa Especial Fábricas en Kaesong La Región Industrial de Kaesong (en rosa)Coordenadas 37°55′48″N 126°37′30″E / 37.93, 126.625Idioma oficial CoreanoEntidad Región Administrativa Especial • País  Corea del NorteSuperficie   • Total 66 km²Huso horario UTC+9Forma de gobierno Región industrialDialecto Gyeonggi (Seulés) Separada de la ciudad de Kaesong en 2002[editar datos e…

عبد العزيز بن عبد الله بن أبي سلمة معلومات شخصية تاريخ الميلاد 1 ألفية  تاريخ الوفاة 164هـ اللقب الماجشون المذهب الفقهي أهل السنة والجماعة الحياة العملية العصر القرن الثاني للهجرة المنطقة المدينة النبوية ، بغداد نظام المدرسة مدرسة الحديث المهنة عالم مسلم مجال العمل علم ال

プログレスM-15MISSに接近するプログレスM-15M任務種別ISS 補給船運用者ロシア連邦宇宙局COSPAR ID2012-015ASATCAT №38222 特性宇宙機種別プログレス-M (11F615A60)製造者RKKエネルギア 任務開始打ち上げ日2012年4月20日 12時50分24秒 (UTC)ロケットソユーズ-U打上げ場所バイコヌール 31/6 任務終了廃棄種別軌道離脱減衰日2012年8月20日 軌道特性参照座標地球周回軌道体制低軌道傾斜角51.6° ISSの

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: José Maceo – news · newspapers · books · scholar · JSTOR (August 2021) (Learn how and when to remove this template message) In this Spanish name, the first or paternal surname is Maceo and the second or maternal family name is Grajales. José MaceoBorn(18…

Peggys Cove, Nova Scotia. Peggys Cove (Peggy's Cove antara tahun 1951-1976) adalah sebuah kampung pedesaan kecil di Kotamadya Regional Halifax, Nova Scotia. Desa yang didirikan pada tahun 1811 ini adalah salah satu daerah tujuan wisata terkenal, meskipun penduduknya masih bekerja sebagai nelayan lobster dan menampilkan ciri pedusunan. Terdapat mercusuar klasik berwarna merah-putih di atas tempat bercadas yang kini tak digunakan lagi. Mercusuar ini memiliki kantor pos kecil di lantai bawah. Pada …

Pour les articles homonymes, voir Agena. L'étage Agena vu depuis le vaisseau Gemini 8 durant une répétition de manœuvre de rendez-vous spatial. Un étage Agena sur la chaîne de production de Lockheed. Agena (RM-81 pour l'Armée de l'Air américaine) est un étage supérieur d'un lanceur développé dans les années 1950 par le constructeur Lockheed et utilisé avec les lanceurs Atlas, Thor et Titan pour lancer un grand nombre de satellites de reconnaissance militaires mais également plusie…

У Вікіпедії є статті про інших людей із прізвищем Кальченко. Кальченко Сергій Віталійович Народився 30 грудня 1964(1964-12-30) (58 років)Київ, Українська РСР, СРСРКраїна  СРСР УкраїнаДіяльність правник, політикAlma mater НТУУ КПІ ім. Ігоря Сікорського і Національний юридичн…

  لمعانٍ أخرى، طالع كريكت (توضيح).   ميّز عن كروكيه. كريكتمعلومات عامةأعلى هيئة منظمة المجلس الدولي للكريكيت نشأة 1780بلد المنشأ إنجلترا المنتسبون لاعب كريكت الهيئات التنظيميةالاتحاد الدولي المجلس الدولي للكريكيتالخصائصالتصنيف رياضة جماعية — رياضة كروية — رياضة …

This article is about the Last Shadow Puppets album. For the album's title song, see The Age of the Understatement (song). 2008 studio album by The Last Shadow PuppetsThe Age of the UnderstatementStudio album by The Last Shadow PuppetsReleased15 April 2008 (2008-04-15)RecordedAugust 2007[1]Studio Black Box, France RAK, London[a] British Grove, London[b] GenreSymphonic poppop rockbaroque popLength35:10LabelDominoProducerJames FordThe Last Shadow Pupp…

Superliga chorwacka w piłce siatkowej mężczyzn 2022/2023 2021/2022 2023/2024 Szczegóły Państwo  Chorwacja Organizator Chorwacki Związek Piłki Siatkowej Edycja 32. Liczba zespołów 12 Termin 01.10.2022 – 06.05.2023 Zwycięzca HAOK Mladost Zagrzeb 2. miejsce MOK Mursa Osijek 3. miejsce OK Ribola Kaštela Superliga chorwacka w piłce siatkowej mężczyzn 2022/2023 – 32. sezon mistrzostw Chorwacji w piłce siatkowej zorganizowany przez Chorwacki Związek Piłki Siatkowej (Hrvatski …

2003 live album by Vince NeilLive at the Whisky: One Night OnlyLive album by Vince NeilReleasedMay 27, 2003[1]GenreHeavy metalLabelImage EntertainmentVince Neil chronology Carved in Stone(1995) Live at the Whisky: One Night Only(2003) Tattoos & Tequila(2010) Professional ratingsReview scoresSourceRatingAllmusic[2] Live at the Whisky: One Night Only is a live album by Vince Neil, lead vocalist of heavy metal band Mötley Crüe, recorded at the Whisky a Go Go. Content T…

Chinese New Version Original title新譯本 (Simplified 新 译本)CountryChina(Hong Kong)LanguageChineseGenreBible versionPublisherWorldwide Bible SocietyPublication date1992Media typePrint (Hardback & Paperback) The Chinese New Version (abbreviation:CNV; simplified Chinese: 新译本; traditional Chinese: 新譯本) is a Chinese language Bible translation that was completed in 1992 by the Worldwide Bible Society (環球聖經公會 Huanqiu Shengjing Xiehui) with the a…

静岡県道242号浜岡菊川線(しずおかけんどう242ごう はまおかきくがわせん)は、静岡県御前崎市、菊川市、牧之原市を通る道路(県道)である。 概要 路線データ 陸上距離:14.5km 起点:御前崎市池新田(静岡県道37号掛川浜岡線、静岡県道372号大東相良線交点) 終点:菊川市沢水加(国道473号交点)※実際の終点は牧之原市東萩間 重複区間 静岡県道69号相良大須賀線(…

Historic house in Ohio, United States United States historic placeDarlon Allen HouseU.S. National Register of Historic Places Front of the house, seen after restorationShow map of OhioShow map of the United StatesLocationState Route 58 in Huntington TownshipNearest cityWellington, OhioCoordinates41°6′46″N 82°13′12″W / 41.11278°N 82.22000°W / 41.11278; -82.22000Area5 acres (2.0 ha)Built1830 (1830)Architectural styleGreek RevivalMPSWellington-Hunt…

Kembali kehalaman sebelumnya

Lokasi Pengunjung: 3.142.40.44