Java 如何防止对象被垃圾回收

Java 如何防止对象被垃圾回收,java,garbage-collection,Java,Garbage Collection,我有一个实用程序类,它启动一个长时间运行的后台线程。实用程序类在主类中初始化。但实用程序类对象正在被垃圾回收。我怎样才能防止这种情况。这是我的班级结构 public class Main { public static void main(String[] args) throws Exception { Utility u = new Utility(); u.startTask(); //This is not referenced after this and hence get

我有一个实用程序类,它启动一个长时间运行的后台线程。实用程序类在主类中初始化。但实用程序类对象正在被垃圾回收。我怎样才能防止这种情况。这是我的班级结构

public class Main {

public static void main(String[] args) throws Exception {
  Utility u = new Utility();
  u.startTask(); //This is not referenced after this and hence getting gc'ed
  .....
  ....
  api.addMessageCreateListener(event -> {
  /////continuously running 
  }
 }
}

我想要的是防止实用程序对象被垃圾收集。

我假设方法
实用程序#startTask()
自己启动线程,否则这将是一个阻塞调用,并且主方法不会在startTask返回之前结束

public class Threading {

    public static void main(String[] args) {
        Utility utility = new Threading().new Utility();
        Future utilFuture = Executors.newSingleThreadExecutor().submit(utility);

        System.out.println("end main");
    }
    
    public class Utility implements Runnable {
        @Override
        public void run() {
            System.out.println("Start Utility");
            for(int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                    System.out.println("foo: " + i);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                }
            }
        }
        
    }
}
但是,这不应阻止您在实用程序本身中实现可运行接口。只要实用程序在自己的线程中运行,就不必担心封闭方法返回。由于踏板仍在运行,因此不会收集实例

public class Threading {

    public static void main(String[] args) {
        Utility utility = new Threading().new Utility();
        Future utilFuture = Executors.newSingleThreadExecutor().submit(utility);

        System.out.println("end main");
    }
    
    public class Utility implements Runnable {
        @Override
        public void run() {
            System.out.println("Start Utility");
            for(int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                    System.out.println("foo: " + i);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                }
            }
        }
        
    }
}
公共类线程{
公共静态void main(字符串[]args){
实用工具=新线程()。新实用工具();
Future utilFuture=Executors.newSingleThreadExecutor().submit(实用程序);
System.out.println(“末端总管”);
}
公共类实用程序实现可运行的{
@凌驾
公开募捐{
System.out.println(“启动实用程序”);
对于(int i=0;i<10;i++){
试一试{
睡眠(1000);
System.out.println(“foo:+i”);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
}
}
}
}
}

注意:在您的情况下,您可能不需要
未来的
,但是,如果需要,它是一个非常有用的工具,可以中断执行。

如果没有代码使用gargabe收集,为什么要阻止它?@plalx是正确的:如果不存在对实例的引用,则表明设计存在问题,但如果GC收集它,则会破坏应用程序。请为我们提供有关您试图实现的目标的更多信息。它可能在后台运行任务,在这种情况下,它应该位于新的threadu.startTask()中正在启动刷新本地缓存的长时间运行的后台线程。您仍然没有回答为什么要阻止
实用程序
实例的垃圾收集。其垃圾收集的假定相关性是什么?你为什么认为,这会带来一个问题?