Skip to content
Advertisement

Java: is it possible to create a garbage-collectable object that includes an internal heartbeat thread?

Quick question: Is is possible to create a class such as it contain an internal infinite thread (heartbeat) and its objects are automatically garbage collected?

Long question: I intend to create a class that includes an internal infinite background thread (such as a heartbeat). Although, the objects of this class shall not need an explicit destroy and shall be garbage-collected when no longer referenced (when, at this point, the heartbeat should also be destroyed), similar C#.
The problem is: Java RE will not garbage-collect these objects because they internally contain a running thread. This leads to an imortal object.

Examples:

Example C# code (works as expected):

JavaScript

C# output:

JavaScript


Example Java code (does not work):

JavaScript

Java output:

JavaScript


Is there an architectural pattern to overcome this JRE “thread keeps running because object exists – object not destroyed because thread is running” deadlock?

Advertisement

Answer

That’s not how we’d do this in Java. The usual Java appoach would be:

  • create and object
  • create a thread and pass that object to the thread
  • the thread holds a weakReference to the object
  • the main loop runs as long as the weak reference is not null

here’s some pseudocode

JavaScript
JavaScript

p.s.: please note that System.gc() is NOT granted to garbage collect anything

p.p.s.: we don’t usually write finalizers in the Java world unless we’re writing infrastructure-level libraries 🙂

Advertisement