Вопрос по java – В чем разница между System.gc () и finalize () в Java?

12

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded Kru
Error: User Rate Limit Exceeded Peter Lawrey

Ваш Ответ

8   ответов
0

Error: User Rate Limit Exceeded

0

System.gc()nullifiedgc()finalize()gc

11

System.gc()Error: User Rate Limit Exceeded

Runs the garbage collector.

Error: User Rate Limit ExceededSystem.gcError: User Rate Limit Exceeded

Object.finalize()Error: User Rate Limit Exceeded

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededRuntime.getRuntime().addShutdownHook(Thread).

Error: User Rate Limit ExceededSystem.gc()Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded sayali
Error: User Rate Limit Exceededa best effortError: User Rate Limit Exceeded
2

System.gc()Error: User Rate Limit ExceededFinalize()Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

class MyClass {
    public UnmanagedResource resource;

    void Finalize() {
        FreeUnmanagedResource(resource);
    }
}

MyClass[] data = new MyClass[1000];
for(int i=0; i<1000; i++) {
    data[i] = new MyClass();
}
//do some work
data = null;
System.gc(); //Note that it doesn't guarantee you that all MyClass instances will be actually collected at this point.
System.gc()Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded sayali
0

Garbage collectionError: User Rate Limit ExceededFinalize()Error: User Rate Limit ExceededFinalize()Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
1

0

Finalizers are unpredictable, often dangerous, and generally unnecessary. never do anything time-critical in a finalizer. never depend on a finalizer to update critical persistent state.

Oh, and one more thing: there is a severe performance penalty for using finalizers. On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns. In other words, it is about 430 times slower to create and destroy objects with finalizers.

Bar bar = new Bar(...);
try {
    // Your code here
} finally {
    bar.releaseResource(); // You implementation. For example close connection
}
1

system.gc()Error: User Rate Limit Exceeded

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

finalize()Error: User Rate Limit Exceeded

Похожие вопросы