简体   繁体   English

ScheduledExecutorService不显示变量更改

[英]ScheduledExecutorService does not show the change in variable

I have been trying to execute a code with the delay of 1 second in my java servlet. 我一直在尝试在我的Java Servlet中执行延迟为1秒的代码。 I need to check the condition if the tracking is on or off. 我需要检查跟踪打开或关闭的条件。 If it is off then it goes to else and shuts the scheduler. 如果关闭,则转到其他位置并关闭调度程序。 The code is as under. 代码如下。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    Map m=request.getParameterMap();
    Set s = m.entrySet();
    Iterator it = s.iterator();
    int index=0;

        while(it.hasNext()){

            Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>)it.next();

            String key             = entry.getKey();
            String[] value         = entry.getValue();

            System.out.println("Value is "+value[0].toString());
                     switch(key)
                     {
                     case "RegId": 
                         RegId=value[0].toString();
                         break;
                     case "isTrackingRequested": 
                         isTrackingRequested=Boolean.valueOf(value[0]);
                         break;     
         }
     }
    boolean isTrackingRequestednew=isTrackingRequested;
    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

        ses.scheduleAtFixedRate(new Runnable() {
            @Override 
            public void run() { 

                // code to run 
                if(isTrackingRequestednew){
                    try {
                        System.out.println("===========================================================================");
                        System.out.println("new track status is "+isTrackingRequestednew);
                        System.out.println("===========================================================================");

                        }catch(Exception e)
                        {   

                        } 
                     }
                else
                {
                    ses.shutdown();

                }
            } 
        }, 0, 1, TimeUnit.SECONDS);
}

Now in order to stop the tracking my application send the isTrackingRequestednew as "false", now this value is not getting changed at all. 现在,为了停止跟踪,我的应用程序将isTrackingRequestednew发送为“ false”,现在此值根本没有更改。 I dont know why is that happening. 我不知道为什么会这样。 Please help me. 请帮我。

This code would not compile, you can't access local (not final) variable inside inner class. 此代码无法编译,您无法访问内部类内部的局部(而非最终)变量。
Every time on post request you create new ExecutorService, instead of creating it once per session or tracking entity. 每次发布请求时,您都可以创建新的ExecutorService,而不是为每个会话或跟踪实体创建一次。 I don't know what is the purpose of this thread, so I would save your weird code style 我不知道该线程的作用是什么,所以我将保留您怪异的代码样式

private static class TrackingInfo {
    final private AtomicBoolean status;
    final private ScheduledExecutorService ses;

    TrackingInfo(boolean flagStatus) {
        this.status = new AtomicBoolean(flagStatus);
        this.ses = Executors.newSingleThreadScheduledExecutor();
        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                // code to run
                if (status.get()) {
                    try {
                        System.out.println("===========================================================================");
                        System.out.println("new track status is " + status.get());
                        System.out.println("===========================================================================");

                    } catch (Exception e) {

                }
                } else {
                    ses.shutdown();
                }
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    public void setStatus(boolean status) {
        this.status.set(status);
    }
}

use either request.getSession().getAttribute(...) / setAttribute() to hold this TrackingInfo and worker inside it and pass flag changes to worker by TrackingInfo.setStatus(newStatus) instance, or you can have some Map variable in your controller class (not method local variable) and store tracking id and TrackingInfo associated with it. 使用request.getSession().getAttribute(...) / setAttribute()在其中容纳此TrackingInfo和worker并通过TrackingInfo.setStatus(newStatus)实例将标志更改传递给worker,或者您可以在其中包含一些Map变量控制器类(而不是方法局部变量),并存储与之关联的跟踪ID和TrackingInfo
Imho, if your real terminating of tracking thread is as simple as it is in posted code 恕我直言,如果您真正终止跟踪线程就像在已发布的代码中一样简单

else {
    ses.shutdown();
}

you don't need TrackingInfo at all. 您根本不需要TrackingInfo Simply store (in session or cache as it is described above) reference to the scheduler and than you receive isTrackingRequestednew with false value in your doPost method, get this scheduler and shutdown it like this 只需存储(如上所述,在会话或高速缓存中)对调度程序的引用,然后在doPost方法中收到带有错误值的isTrackingRequestednew ,即可获取此调度程序并像这样关闭它

if (!isTrackingRequestednew) {
    ScheduledExecutorService scheduler = (ScheduledExecutorService) request.getSession().getAttribute("trackingScheduler");
    if (scheduler != null) {
        scheduler.shutdown();
    }
}

Instead "trackingScheduler" you can use some tracking id as identifier and send it with every request. 而是使用"trackingScheduler"您可以使用一些跟踪ID作为标识符,并随每个请求发送。
Note that you also have to cleanup old schedulers which were not shutdowned properly due some network errors or whatever. 请注意,您还必须清理由于某些网络错误或其他原因未正确关闭的旧调度程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM