Is unused object available for garbage collection when it's still visible in stack?

前端 未结 5 1433
心在旅途
心在旅途 2020-12-30 01:44

In the following example there are two functionally equivalent methods:

public class Question {

    public static String method1() {
        String s = new          


        
5条回答
  •  一生所求
    2020-12-30 02:27

    Basically stack frames and static area are considered as roots by GC. So if object is referenced from any stack frame its considered alive. The problem with reclaiming some objects from active stack frame is that GC works in parallel with application(mutator). How do you think GC should find out that object is unused while method is in progress? That would require a synchronization which would be VERY heavy and complex, in fact this will break the idea of GC to work in parallel with mutator. Every thread might keep variables in processor registers. To implement your logic, they should also be added to GC roots. I cant even imagine how to implement it.

    To answer you question. If you have any logic which produces a lot of objects which are unused in the future, separate it to a distinct method. This is actually a good practice.

    You should also take int account optimizations by JVM(like EJP pointed out). There is also an escape analysis, which might prevent object from heap allocation at all. But rely your codes performance on them is a bad practice

提交回复
热议问题