Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Object.observe/unobserve interact with garbage collection?

Does having an active Object.observe on an object prevent it from being garbage collected? Do you need to first call Object.unobserve to allow it to be garbage collected? Or does GCing an object remove all its active observers?

like image 391
alexp Avatar asked Aug 14 '14 17:08

alexp


People also ask

How does garbage collector know which objects to free?

When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots.

What is the main objective of garbage collection?

The main objective of Garbage Collection is to free heap memory by destroying the objects that don't contain a reference. When there are no references to an object, it is assumed to be dead and no longer needed. So the memory occupied by the object can be reclaimed.

How does JVM garbage collection work?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.

How is Java's garbage collection implemented?

Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.


1 Answers

Observing an object does not keep it alive. Once the object dies, its observers simply won't receive any more events. At least that's true in V8's implementation, which is the only one so far. It's probably safe to assume that it will hold for other implementations as well, should this feature become standard some day.

However, observation keeps its active observers alive, plus some internal, heap-allocated data structures associated with each observer function. In fact, this additional data will only die when the function itself has also died, even if it has long ceased to observe anything.

like image 109
Andreas Rossberg Avatar answered Sep 19 '22 08:09

Andreas Rossberg