0

I am building a multiplayer game in Java using Java sockets for a university project, and I've reached the point where it's playable, but I am not sure how to release resources after the game ends.

The server should be able to support multiple simultaneous matches, so everytime a new game starts, it's assigned its own thread, which then generates all objects used for game logic. Aside from closing sockets and input/output streams, will terminating the main thread (as in "reaching the end of the run method") mark all objects I use for game logic for garbage collection, or do I have to delete references one by one to avoid memory leaks?

From what I've read, my assumption is correct, and what I need to check is whether all objects I create are actually only referenced by the main thread

Jack
  • 35
  • 4

1 Answers1

1

All objects are allocated on the heap area managed by the JVM. 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.

You may use some gc flags to enhance your server performances. In the end, memory is managed by the garbage collector and there is little you can do.

Snix
  • 541
  • 4
  • 12
  • That much is clear to me: my question is not about performance, it's about making my program work properly. What I'm unsure of is whether my approach will cause memory leaks: if a thread reaches the end of the "run()" method, will it release all objects it has created? Will they no longer be referenced, so that they are elegible for GC? Or will this happen only if the thread itself is no longer referenced once it reaches the end of the "run()" method? – Jack Jun 06 '20 at 23:15
  • 1
    If they aren't shared with others thread, yes, they will be eligible for Garbage Collection. But you shouldn't worry too much about this and i'll tell you why. You can easily check with a [JVM profiler](https://visualvm.github.io/) if GC is not working as expected or if the heap is getting full you will be able to see which objects are being kept alive instead of dying. You can easily spot these kind of behaviour. Also, you can use code analysis to check if you are managing your resources properly. – Snix Jun 06 '20 at 23:19
  • 1
    @Jack There is no need to “release objects”. Also, which thread has created the object, is irrelevant. As this answer said, whether objects are *reachable* matters. In this regard, you don’t even need to reach the end of the `run()` method; most of the objects may get garbage collected even earlier. Usually, we say that local variables of *still running* methods may prevent garbage collection of their referents. But, in fact, [not even that is stopping gc](https://stackoverflow.com/a/24380219/2711488) in general. The basic rule is, an object may get collected, when it has no noticeable effect. – Holger Jun 08 '20 at 16:24