如果一段时间未使用变量引用,该如何删除?

时间:2019-07-24 00:28:09

标签: java multithreading timer timertask

大约15年没有处理Java。可能真的很简单,但我需要在5分钟后将变量设置为null。基本上,我需要销毁一件东西,但前提是没有人使用它一段时间。如果距离上次使用时间不长,则应重新使用该东西。

该应用程序是视频流服务器。 “事物”是videoStream对象。其概念是消除videoStream对象,如果一段时间内没有人连接到该对象。但是,如果最后一次连接是最近的,则保留该对象并重新使用它。

这听起来像是计时器的工作吗?

如果是,请尝试以下操作。它不会编译,因为Java计时器在新线程中执行并且该新线程不知道什么是流。流是在原始线程中创建的。错误读取:

error: cannot find symbol
        stream = null;
        ^
symbol:   variable stream
location: class DeleteStreamReferenceTask
1 error

如果计时器不是正确的方法,您能建议一个合适的替代方法吗?

import java.util.Timer;
import java.util.TimerTask;

public static void main(String[ ] args) {

    MyClass myClass = new MyClass();

}

public class MyClass {

    private VideoStream stream;
    private Timer timer;

    public void onPublish()
    {
        //Make an instance of VideoStream, but only if it doesn't exist yet.
        if(stream == null){
            //stream doesn't exist.  Make one...
            stream = new VideoStream("My Stream");
        }
        else{
           //stream already exists.  Just terminate the timer so the stream won't be destroyed.
           timer.cancel();//Terminate the timer thread.  Is this the correct?  Does this actually destroy the timer object too?
        }


    }//End onPublish()

    public void onUnPublish()
    {
        //Start a 5 minute timer.  When time up, set "stream" to null
        timer = new Timer();
        timer.schedule(new DeleteStreamReferenceTask(), 3000000);
    }

}//End MyClass  

class DeleteStreamReferenceTask extends TimerTask {
    public void run() {
        System.out.println("Time's up! Removing references to stream..");
        stream = null;//This thread doesn't know what a stream is...
    }
}

public class VideoStream {
    private String name;

    public VideoStream(String name){
        name = name;
    }
}//End VideoStream

0 个答案:

没有答案