Java – garbage collection and manual memory management

This is a very basic question I'll use C and Java to make it, but it's really language independent

struct Obj
{
    boost::shared_ptr<Obj> m_field;
};

{
    boost::shared_ptr<Obj> obj1(new Obj);
    boost::shared_ptr<Obj> obj2(new Obj);
    obj1->m_field = obj2;
    obj2->m_field = obj1;
}

This is a memory leak, as we all know:) the solution is also well known: weak pointers should be used to break the "reference union" I also know that this problem cannot be solved automatically in principle The programmer who solves this problem is the only responsibility

But there is one positive thing: the programmer has complete control over the refcount value I can pause my program in the debugger and check the references of obj1 and obj2 to see if there is a problem I can also set a breakpoint in the object's destructor and observe the time of destruction (or find that the object has not been destroyed)

My question is about Java, c#, ActionScript and other "garbage collection" languages I may miss something, but in my opinion they are

Don't let me check the object count > don't let me know when the object is broken (when the object is exposed to GC)

I often hear that these languages do not allow programmers to leak memory, which is why they are great As far as I know, they just hide the memory management problem, which is difficult to solve

Finally, the problem itself:

Java:

public class Obj
{
    public Obj m_field;
}

{
     Obj obj1 = new Obj();
     Obj obj2 = new Obj();
     obj1.m_field = obj2;
     obj2.m_field = obj1;
}

>Is it a memory leak? > If so, how do I detect and fix it? > If not: why?

Solution

Managed memory systems are based on the assumption that you don't want to track memory leaks first Don't make them easier to solve, you can try to make sure they never happen

Java does have a "memory leak" disadvantage, which means that any increase in memory may affect your application, but never at all, managed memory can't clean up all memory

There are many reasons why the JVM does not use reference counting

>As you can see, it cannot handle circular references It has significant memory and thread overhead to maintain accuracy. > There are better and simpler ways to manage memory to handle this situation

Although JLS does not prohibit the use of reference counting, it is not used for any JVM AFAIK

On the contrary, Java tracks some root contexts (such as each thread stack), and can strongly track which objects need to be retained and which can be discarded according to whether these objects can be retained It also provides facilities for weak references (kept as long as the object is not cleaned up) and soft references (usually not cleaned up, but can be processed in the garbage collector)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>