Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there the concept of strong reference cycle (or something similar) in Java, similar to that of Swift? [duplicate]

In Swift, great emphasis has been placed on strong reference cycle, and different ways to avoid it. If there are strong reference cycle between two variables, they will keep each other in memory forever, and cause the program to crash if large images or videos are been kept in memory by strong reference cycle.

I was just wondering if such concept exist in Java? Is it possible to unintentionally create something similar to strong reference cycle in Java? I have several months of Java experience, but I have never heard of anyone mentioning such concept in Java, even though Java do use reference variables to point to objects.

like image 499
Thor Avatar asked Jan 06 '23 06:01

Thor


1 Answers

It seems that swift uses "reference counting" to detect object liveness: each object has a counter associated with it that gets incremented if a new reference to that object is created and gets decremented if a reference to that object disappears. An object is dead if the reference count is zero, meaning that there are no more references to it.

Java on the the other hand uses "reachability" as a measure of liveness: an object is alive as long as there exists a reference chain from some "running code" to the object.

There are pros and cons to both approaches:

  • reference counting makes the garbage collectors life easier: just look at the reference count and you know whether an object is alive
  • on the other hand, reference counting makes it possible to create reference cycles between otherwise dead objects
  • reachability means that the garbage collector has to start at the objects that a thread can directly reach and follow all references to mark live objects
  • reachability on the other hand means that reference cycles are no problem: either both objects are reachable or neither one
like image 77
Thomas Kläger Avatar answered Jan 13 '23 10:01

Thomas Kläger