Java direct memory: using sun.misc.Cleaner in custom classes

后端 未结 3 799
挽巷
挽巷 2021-02-13 09:07

In Java the memory allocated by NIO direct buffers is freed with sun.misc.Cleaner instances, some special phantom references that are more efficient than object fin

3条回答
  •  天涯浪人
    2021-02-13 09:31

    Hope it help you if using java9.

    The code below was already tested in Intellij IDEA 2017 and oracle jdk 9.

    import java.lang.ref.Cleaner;
    
    public class Main {
    
        public Main() {
    
        }
    
        public static void main(String[] args) {
            System.out.println("Hello World!");
    
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Cleaner cleaner = Cleaner.create();
                Main obj = new Main();
                cleaner.register(obj, new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("Hello World!222");
                    }
                });
                System.gc();
            }
        }
    }
    

提交回复
热议问题