• this引用逸出


    1.定义

    public class UnsafeClass {
        
        public UnsafeClass(Button button) {
            button.addActionListener(new ActionListener() {
                //在这里发布  会导致this引用逸出,因为构造函数没有完全返回
                //如果在这里新建新的线程,那么新线程会持有没有完全构造完成的this引用
                @Override
                public void actionPerformed(ActionEvent e) {
                    
                }
            });
        }
    }

    如上述代码所示,在构造函数中定义新的线程或者发布会导致this引用逸出,此时的问题就在于构造函数还没有构造完成.

    2.解决

    public class SafeClass {
        private final ActionListener actionListener;
        private SafeClass() {
            actionListener = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                }
            };
        }
        public SafeClass newInstance(Button button) {
            //构造函数构造完毕在进行发布
            SafeClass safeClass = new SafeClass();
            button.addActionListener(safeClass.actionListener);
            return safeClass;
        }
    }

    发布this没有问题,只要在构造函数返回时进行发布就可以了.

    public class SafeClass {
        private final Runnable runnable;
        private SafeClass() {
            runnable = new Runnable() {
                
                @Override
                public void run() {
                }
            };
            
        }
        public SafeClass newInstance(Thread d) {
            //构造函数构造完毕在进行发布
            SafeClass safeClass = new SafeClass();
            d = new Thread(safeClass.runnable);
            return safeClass;
        }
    }

    线程的版本也可以这样写,只要保证构造函数构造完毕即可.

  • 相关阅读:
    django migration
    Jenkins Jobs status dashboard by Build Monitor Plugin
    PyWebIO Write interactive web app in script way.
    Infrastructure as Code
    sqlalchemy
    reactsketch
    CI/CD System and gerrittrigger keypoints.
    mysql backup
    Alembic A database migrations tool for SQLAlchemy.
    docker support for inner loop
  • 原文地址:https://www.cnblogs.com/lishuaiqi/p/11795525.html
Copyright © 2020-2023  润新知