java.lang.ref
Since Java 1.2
... references?
ā— A reference is, as its name suggests, what
you use to point to (reference) an object
somewhere else in the memory.
ā— You use it all the time!
String s = ā€œstringā€; // s is a reference
There are more?
ā— Probably, all our life, we’ve been using only
one type of references; strong references.
ā— Object o = new Object();
As long as you keep o to your side, the
object it references stays in memory.
There are more?
ā— There are more levels of ā€œstrength or
reachabilityā€ for references.
ā—‹ Soft
ā—‹ Weak
ā—‹ Phantom
ā— You can get these by using package java.
lang.ref.
How to?
ā— You use them as you use the usual strong
reference, but use them for special
purposes.
ā— The GC handles them as it handles the
strong references. So it’s done for you and
you can’t add to it or extend it.
Reference<T>
ā— Constructor: Reference(T referent)
ā— T get()
ā— void clear ()
ā— That’s it. Once you initialize it, you can’t
change the ā€œreferentā€. Clearing is your only
option.
Softly reachable..
ā— The next level after strong references is soft
references.
ā— A softly reachable object is an object that has
no strong references, but has soft ones.
ā— Object o = new Object();
SoftReference<Object> softRef = new
SoftReference<Object>(o);
o = null; // o is now softly reachable
Softly reachable… so?
ā— Important point about references is when the
GC decides to reclaim referents.
ā— It’s guaranteed to live till an OutOfMemoryError
is thrown, then there’s no guarantee.
ā— Sounds good for simple caches.
ā— Some JRE implementations start collection
with the oldest objects.
Weak references
ā— It’s weakly reachable when there are no
strong or soft references to it, and it has
weak references to it.
ā— Once the object is weakly reachable, it’s
eligible for finalization at once.
Weak references
ā— java.util.WeakHashMap
ā— References the keys weakly and the values
strongly. Once the key goes weak, its record
is removed from the map.
Phantom references
ā— No strong. No soft. No weak. And some
phantom references to the object.
ā— If the object is phantomly reachable, it’s
dead! So get() returns null.
ā— In fact, it always returns null.
Phantom references
ā— Sounds unuseful!
ā— The only value is to get notified of the object
getting in that level. i.e. get notified that it’s
really dead, to do post-mortem stuff.
ā— P.S. finalize() isn’t immune to fooling around.
You can resurrect the object from death
there.
ReferenceQueue<? super T>
ā— Nothing really! It just tells you when the
objects reach registered reachability levels.
ā— If the object moves from strongly reachable
to softly reachable, you’ll get the call
ReferenceQueue
ā— Reference(T referent, ReferenceQueue<? super T>
queue)
ā— Reference<? extends T> poll() // doesn’t block
ā— remove(), remove(long timeOut) // blocks
ā— As mentioned before, phantom references are only
good with queues. However, weak and soft references
are good with it too.
Ruby - WeakRef
ā— Inherits from Delegator -> You can deal with
it the same way you deal with the object.
ā— Uses object ID to keep track
ā— Raises an exception when referenced after
being collected
Python - weakref
ā— weakref.ref(obj [,callback])
ā— Also WeakKeyDictionary and
WeakValueDictionary
ā— Not all objects can be weakly referenced.
ā— Some built-in types don’t support weak
references unless subclassed.
ā—‹ str can never be
ā— Good to avoid cyclic references (before 2.0)
Python - weakref
ā— weakref.getweakrefcount(obj)
ā— weakref.proxy(object [,callback]) //
Alternative to subclassing
ā— Extension types can be made to support
weak references
Objective-C
ā— Reference counting and ARC -> NOT GC
ā— strong vs weak @property becomes nil
automatically
ā— Avoid cyclic strong references
Objective-C
ā— NSMapTable: Dictionary (weak keys, weak
values, both)
ā— NSHashTable: Set
ā— NSPointerArray:Array
ā— NSPointerFunctions
C++11
ā— Use std::shared_ptr instead of a regular
pointer.
ā— Use std::weak_ptr with the shared pointer
ā— There are other libraries for pre C++11
Uses
ā— Simple Caching: Storing the big object in
memory until everybody stops using it.
ā—‹ Java’s SoftReference. Weak references won’t be
much useful for that
ā— Listeners: Keeps notifying objects until they’
re out of reach.
ā—‹ Problem with anonymous objects in Java.
Uses
ā— Associating data with various objects ā€œmeta-
data storingā€: Doesn’t make sense to
override
ā—‹ Store data specific to a thread
ā—‹ Store data specific to a view object; like a tag or a
serial
ā—‹ Store data specific to a resource object; like a file
Uses
ā— Canonicalized mapping
ā—‹ Store one reference for the same objects and
remove them when nobody needs them anymore.
Map employeesByID = new HashMap<String, WeakReference<Employee>();
// Maps employee IDs to weak references of Employee objects retrieved from
DB
Be Careful
ā— Weak maps usually check references for
equality.
String s1 = ā€œHello!ā€;
String s2 = new String([ā€˜H’, ā€˜e’, ā€˜l’, ā€˜l’, ā€˜o’, ā€˜!’]);
strongMap.put(s1, value); weakMap.put(s1, value);
strongMap.contains(s2) //true;
weakMap.contains(s2) // false;
Be Careful
ā— ā€œPremature optimization is the root of all
evilā€
ā—‹ Weak references and their dependencies are great
for special uses, not everything.
References
ā— Javadoc
ā— Understanding Weak References
ā— Getting to know the Ruby Standard Library - WeakRef
ā— docs.python.org
ā— Canonicalized Mapping
ā— Weak Object Pools with WeakHashMap
ā— Some others I can’t remember.

More Related Content

PDF
Review of c_sharp2_features_part_i
PPTX
Paca oops slid
PDF
A tour on Spur for non-VM experts
Ā 
PPTX
Small Lambda Talk @Booster2015
PPTX
Javascript Prototypal Inheritance - Big Picture
PPTX
Interesting Facts About Javascript
PPTX
Javascript Objects Deep Dive
PPT
Developing Android applications with Ceylon
Review of c_sharp2_features_part_i
Paca oops slid
A tour on Spur for non-VM experts
Ā 
Small Lambda Talk @Booster2015
Javascript Prototypal Inheritance - Big Picture
Interesting Facts About Javascript
Javascript Objects Deep Dive
Developing Android applications with Ceylon

Viewers also liked (7)

PDF
Knowing your Python Garbage Collector
PDF
ŠŠµŠ“Š¾ŃŃ‚Š°Ń‚ŠŗŠø Python
PPTX
Science Exams Study Questions
PPTX
Python GC
PPT
Python Objects
PDF
Memory Management In Python The Basics
PDF
How to successfully grow a code review culture
Knowing your Python Garbage Collector
ŠŠµŠ“Š¾ŃŃ‚Š°Ń‚ŠŗŠø Python
Science Exams Study Questions
Python GC
Python Objects
Memory Management In Python The Basics
How to successfully grow a code review culture
Ad

Similar to WeakReferences (java.lang.ref and more) (20)

PDF
Garbage collection 介瓹
PDF
Introduction to Javascript and Typescript.pdf
PDF
Java reference objects basic
PDF
Optionals by Matt Faluotico
PPTX
Java GC
PDF
Persistent Data Structures by @aradzie
PDF
RxJava@DAUG
PDF
Design Patterns Illustrated
PPTX
Kaggle Tweet Sentiment Extraction: 1st place solution
PDF
I know Java, why should I consider Clojure?
Ā 
PPTX
Chapter 3. Lesson 2_ in, out and ref.pptx
PPT
JavaScript Data Types
PPTX
Memory management ARC
PDF
Be a Zen monk, the Python way
PPTX
sl-unit2 ppt for cse in b.tech jntuh iii year
PDF
The magic of (data parallel) distributed systems and where it all breaks - Re...
ODP
Working with jpa
PDF
Review of c_sharp2_features_part_iii
PDF
15 Minutes Null
PDF
Functional programming
Ā 
Garbage collection 介瓹
Introduction to Javascript and Typescript.pdf
Java reference objects basic
Optionals by Matt Faluotico
Java GC
Persistent Data Structures by @aradzie
RxJava@DAUG
Design Patterns Illustrated
Kaggle Tweet Sentiment Extraction: 1st place solution
I know Java, why should I consider Clojure?
Ā 
Chapter 3. Lesson 2_ in, out and ref.pptx
JavaScript Data Types
Memory management ARC
Be a Zen monk, the Python way
sl-unit2 ppt for cse in b.tech jntuh iii year
The magic of (data parallel) distributed systems and where it all breaks - Re...
Working with jpa
Review of c_sharp2_features_part_iii
15 Minutes Null
Functional programming
Ā 
Ad

Recently uploaded (20)

PDF
distributed database system" (DDBS) is often used to refer to both the distri...
PPTX
Petroleum Refining & Petrochemicals.pptx
PPTX
PRASUNET_20240614003_231416_0000[1].pptx
PDF
Computer System Architecture 3rd Edition-M Morris Mano.pdf
PDF
First part_B-Image Processing - 1 of 2).pdf
PDF
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
PPTX
Software Engineering and software moduleing
PDF
20250617 - IR - Global Guide for HR - 51 pages.pdf
PPTX
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
PDF
August 2025 - Top 10 Read Articles in Network Security & Its Applications
PDF
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf
PDF
August -2025_Top10 Read_Articles_ijait.pdf
Ā 
PPTX
Information Storage and Retrieval Techniques Unit III
PDF
Design of Material Handling Equipment Lecture Note
PDF
Prof. Dr. KAYIHURA A. SILAS MUNYANEZA, PhD..pdf
PDF
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
PPTX
Feature types and data preprocessing steps
PPTX
Chemical Technological Processes, Feasibility Study and Chemical Process Indu...
PDF
Computer organization and architecuture Digital Notes....pdf
PPTX
wireless networks, mobile computing.pptx
distributed database system" (DDBS) is often used to refer to both the distri...
Petroleum Refining & Petrochemicals.pptx
PRASUNET_20240614003_231416_0000[1].pptx
Computer System Architecture 3rd Edition-M Morris Mano.pdf
First part_B-Image Processing - 1 of 2).pdf
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
Software Engineering and software moduleing
20250617 - IR - Global Guide for HR - 51 pages.pdf
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
August 2025 - Top 10 Read Articles in Network Security & Its Applications
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf
August -2025_Top10 Read_Articles_ijait.pdf
Ā 
Information Storage and Retrieval Techniques Unit III
Design of Material Handling Equipment Lecture Note
Prof. Dr. KAYIHURA A. SILAS MUNYANEZA, PhD..pdf
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
Feature types and data preprocessing steps
Chemical Technological Processes, Feasibility Study and Chemical Process Indu...
Computer organization and architecuture Digital Notes....pdf
wireless networks, mobile computing.pptx

WeakReferences (java.lang.ref and more)

  • 2. ... references? ā— A reference is, as its name suggests, what you use to point to (reference) an object somewhere else in the memory. ā— You use it all the time! String s = ā€œstringā€; // s is a reference
  • 3. There are more? ā— Probably, all our life, we’ve been using only one type of references; strong references. ā— Object o = new Object(); As long as you keep o to your side, the object it references stays in memory.
  • 4. There are more? ā— There are more levels of ā€œstrength or reachabilityā€ for references. ā—‹ Soft ā—‹ Weak ā—‹ Phantom ā— You can get these by using package java. lang.ref.
  • 5. How to? ā— You use them as you use the usual strong reference, but use them for special purposes. ā— The GC handles them as it handles the strong references. So it’s done for you and you can’t add to it or extend it.
  • 6. Reference<T> ā— Constructor: Reference(T referent) ā— T get() ā— void clear () ā— That’s it. Once you initialize it, you can’t change the ā€œreferentā€. Clearing is your only option.
  • 7. Softly reachable.. ā— The next level after strong references is soft references. ā— A softly reachable object is an object that has no strong references, but has soft ones. ā— Object o = new Object(); SoftReference<Object> softRef = new SoftReference<Object>(o); o = null; // o is now softly reachable
  • 8. Softly reachable… so? ā— Important point about references is when the GC decides to reclaim referents. ā— It’s guaranteed to live till an OutOfMemoryError is thrown, then there’s no guarantee. ā— Sounds good for simple caches. ā— Some JRE implementations start collection with the oldest objects.
  • 9. Weak references ā— It’s weakly reachable when there are no strong or soft references to it, and it has weak references to it. ā— Once the object is weakly reachable, it’s eligible for finalization at once.
  • 10. Weak references ā— java.util.WeakHashMap ā— References the keys weakly and the values strongly. Once the key goes weak, its record is removed from the map.
  • 11. Phantom references ā— No strong. No soft. No weak. And some phantom references to the object. ā— If the object is phantomly reachable, it’s dead! So get() returns null. ā— In fact, it always returns null.
  • 12. Phantom references ā— Sounds unuseful! ā— The only value is to get notified of the object getting in that level. i.e. get notified that it’s really dead, to do post-mortem stuff. ā— P.S. finalize() isn’t immune to fooling around. You can resurrect the object from death there.
  • 13. ReferenceQueue<? super T> ā— Nothing really! It just tells you when the objects reach registered reachability levels. ā— If the object moves from strongly reachable to softly reachable, you’ll get the call
  • 14. ReferenceQueue ā— Reference(T referent, ReferenceQueue<? super T> queue) ā— Reference<? extends T> poll() // doesn’t block ā— remove(), remove(long timeOut) // blocks ā— As mentioned before, phantom references are only good with queues. However, weak and soft references are good with it too.
  • 15. Ruby - WeakRef ā— Inherits from Delegator -> You can deal with it the same way you deal with the object. ā— Uses object ID to keep track ā— Raises an exception when referenced after being collected
  • 16. Python - weakref ā— weakref.ref(obj [,callback]) ā— Also WeakKeyDictionary and WeakValueDictionary ā— Not all objects can be weakly referenced. ā— Some built-in types don’t support weak references unless subclassed. ā—‹ str can never be ā— Good to avoid cyclic references (before 2.0)
  • 17. Python - weakref ā— weakref.getweakrefcount(obj) ā— weakref.proxy(object [,callback]) // Alternative to subclassing ā— Extension types can be made to support weak references
  • 18. Objective-C ā— Reference counting and ARC -> NOT GC ā— strong vs weak @property becomes nil automatically ā— Avoid cyclic strong references
  • 19. Objective-C ā— NSMapTable: Dictionary (weak keys, weak values, both) ā— NSHashTable: Set ā— NSPointerArray:Array ā— NSPointerFunctions
  • 20. C++11 ā— Use std::shared_ptr instead of a regular pointer. ā— Use std::weak_ptr with the shared pointer ā— There are other libraries for pre C++11
  • 21. Uses ā— Simple Caching: Storing the big object in memory until everybody stops using it. ā—‹ Java’s SoftReference. Weak references won’t be much useful for that ā— Listeners: Keeps notifying objects until they’ re out of reach. ā—‹ Problem with anonymous objects in Java.
  • 22. Uses ā— Associating data with various objects ā€œmeta- data storingā€: Doesn’t make sense to override ā—‹ Store data specific to a thread ā—‹ Store data specific to a view object; like a tag or a serial ā—‹ Store data specific to a resource object; like a file
  • 23. Uses ā— Canonicalized mapping ā—‹ Store one reference for the same objects and remove them when nobody needs them anymore. Map employeesByID = new HashMap<String, WeakReference<Employee>(); // Maps employee IDs to weak references of Employee objects retrieved from DB
  • 24. Be Careful ā— Weak maps usually check references for equality. String s1 = ā€œHello!ā€; String s2 = new String([ā€˜H’, ā€˜e’, ā€˜l’, ā€˜l’, ā€˜o’, ā€˜!’]); strongMap.put(s1, value); weakMap.put(s1, value); strongMap.contains(s2) //true; weakMap.contains(s2) // false;
  • 25. Be Careful ā— ā€œPremature optimization is the root of all evilā€ ā—‹ Weak references and their dependencies are great for special uses, not everything.
  • 26. References ā— Javadoc ā— Understanding Weak References ā— Getting to know the Ruby Standard Library - WeakRef ā— docs.python.org ā— Canonicalized Mapping ā— Weak Object Pools with WeakHashMap ā— Some others I can’t remember.