What is the best way to clean up an Object in Java?

后端 未结 9 1918
悲&欢浪女
悲&欢浪女 2021-01-01 14:05

We don\'t have any destructor in Java as we have in C++.

Q1. How should we clean up any Object in java.

Q2. Is there any a

相关标签:
9条回答
  • 2021-01-01 14:41

    You could also add a shutdown hook to your program, if your program is shutting down too:

    //add shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            ThirdPartyTerminate();
        }
    });
    
    0 讨论(0)
  • 2021-01-01 14:42

    Two syntax sugar options:

    1) There is a @Cleanup annotation in Lombok that mostly resembles C++ destructors (more):

    @Cleanup
    ResourceClass resource = new ResourceClass();
    

    2) There is also try-with-resources statement. For example:

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
      System.out.println(br.readLine());
    }
    
    0 讨论(0)
  • 2021-01-01 14:43

    You can use java.lang.ref.Cleaner in Java 9,

    0 讨论(0)
  • 2021-01-01 14:48

    You can clean up objects by removing references to it, when you no longer need it. You dont have to do it explicitly. An explicit cleanup would require setting the reference to null, thereby providing a hint to the garbage collector that the object can be collected. This hint works because of internal reference counts for each object, that are maintained internally. For instance

    
    C a = new C(); //create an object of class C and assign it to 'a'
    a = new C(); //create another object of class C and assign it to 'a'. The older object is no longer referred to. It is now eligible for GC.
    

    There are better alternatives to finalize() depending on how much finalize() is helping your situation.

    Often, the best practice is to provide a method like close() or disposeResources() in the API which will allow the caller to help the API clean up itself. For instance, the java.sql.Connection class does this. This is better than the finalize() method, since the JVM will call the finalize() method. Often the finalize() method will be run by a low priority thread in the JVM, leading to certain strange errors.

    In the case of the Connection class, waiting for the JVM to perform finalization does prove costly in a lot of applications, since a database can accept only so many connections at a time. Therefore, most programmers will call close() explicitly on a Connection object.

    In your case, it should translate into something similar (and in this context, the finally block is guaranteed to run always)

    
    try
    {
     ThirdPartyInitialize();
     // use third party component in this try block
    }
    finally
    {
     ThirdPartyTerminate();
    }
    

    This is similar to the how the Connection class is also used in most situations.

    0 讨论(0)
  • 2021-01-01 14:53

    Your objects in Java really never need to be "Cleaned Up", GC Just works. Nearly every time I've seen someObject=null in code, it's been someone who didn't know what they were doing. There IS a theoretical case for this, but it's really an edge case and generally better handled in other ways like the recently added try with resource.

    If you have an external resource that needs to be cleaned up when an object is no longer used, that is another matter.

    There are "Reference" classes that will hold a special type of Reference to your class--it will not stop garbage collection, but can notify you when the class is garbage collected (Through a callback if you like). Look up WeakReference, PhantomReference, etc.

    These are reliable and work in a much more deterministic way than a actual "finalize" method would because the callback is outside your class, so you don't end up executing a method in some pre-deleted or half-deleted state and the problems that could cause.

    0 讨论(0)
  • 2021-01-01 14:54

    The best way to clean up after objects is to just drop the object.

    Finally blocks can be abstracted using the Execute Around idiom.

    Finalisers should be avoided. They probably wont get called immediately. The clean up should happen anyway. They are relatively slow. You might want to add one as a safety-net if you are writing a low-level resource wrapper (for, say, a file handle) if performance is not critical.

    0 讨论(0)
提交回复
热议问题