![]() Which means that when we create a weak reference to an object, and garbage collector runs, it will clear the object from memory right away (If there are no other strong references to this object). Weak ReferenceĪ weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. ![]() The object will stay in the memory and nothing will happen as this is what we expected (Strong references prevents GC from destroying the referenced object). When we try to print myObject before garbage collector runs It will print the address of the object in memory.īut, what happens when garbage collector runs? (We simulate this by forcing GC to run by writing System.gc()) ![]() So for example, when we create an instance of a class called Dummy Like in the following image:Ī new object of type Dummy gets created in memory and myObject has a strong reference to it. This reference will prevent the garbage collector (GC) from destroying this object. It is the reference that gets created by default whenever we create any object. We will focus on Strong and Weak references in this article. There are 4 types of references in Java: Strong, Soft, Weak, and Phatom. But I didn’t quite get it when I googled it Also, all of the examples I read weren’t practical which made it harder to grasp the concept. I’ve heard about weak references for the first time when I was reading more in LeakCanary library’s documentation to see how it works.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |