简体   繁体   English

如何在呈现页面之前获取线程响应

[英]How to get the Thread response before page get rendered

I have an application which require File Operation , that need to be done as concurrently 我有一个需要File Operation的应用程序,需要同时执行

  1. If a user try to READ a file , other users cant perform WRITE operation 如果用户尝试读取文件,则其他用户无法执行WRITE操作
  2. If a user try to WRITE to file , other user cant perform READ Operation 如果用户尝试写入文件,其他用户将无法执行读取操作

business logic applied : 应用的业务逻辑:

Created Thread using Runnable Interface and added Synchronized READ Methods to read property file from remote location and put it into session /request object 使用Runnable Interface创建线程,并添加了同步READ方法以从远程位置读取属性文件并将其放入会话/ request对象中

  • issue : while starting a new thread the response get finished (since thread is independent path of execution) .so the property values are not available 问题:启动新线程时,响应完成(由于线程是独立的执行路径)。因此,属性值不可用

How to get the thread response before the page get displayed ? 如何在显示页面之前获取线程响应? I heared that we can use Callable Interface , please share the best approach suited in this situation. 听说我们可以使用Callable Interface,请分享适合这种情况的最佳方法。

Making a thread in servlet in this way(initiate a Runnable and run it by JVM directly) is completely non-sense and not recommended for sake of memory leak, and unmanaged context. 以这种方式在servlet中创建线程(初始化Runnable并直接由JVM运行)完全是Runnable ,并且不建议这样做,以免发生内存泄漏和非托管上下文。

It's completely nature you get undefined/nonstable states of request/session context by the new thread. 通过新线程获得请求/会话上下文的不确定/不稳定状态是完全自然的。

Since the thread gets started asynchronously, the servlet/server context continue its working and response to the client, and the request context is no more valid. 由于线程是异步启动的,因此servlet /服务器上下文继续其工作并响应客户端,并且请求上下文不再有效。

You may do it by a mutex, since the servlet context is multi-threaded by default, and you may not never and never run threads that way please, and if you do, you may do it by session context listeners to handle events and prevent any possible memory leak. 您可以通过互斥量来完成此操作,因为Servlet上下文默认情况下是多线程的,请不要再也永远不要那样运行线程,如果这样做,可以通过会话上下文侦听器来处理事件并防止任何可能的内存泄漏。

You may either wait(block) the response while the related context(file) is locked, which is not so logical. 您可以在相关的上下文(文件)被锁定时等待(阻止)响应,这不是那么合理。 Or inform the user the requested file is being locked becasue of another read/write operation. 或者,由于另一个读/写操作,通知用户所请求的文件已被锁定。
And of course you need a push like method(like websockets) or alternatives(check status by ajax or reloading) to check the latest related context status. 当然,您需要类似push的方法(例如websockets)或替代方法(通过ajax或重新加载来检查状态)来检查最新的相关上下文状态。

And the most logical way is, you need to do it in queue mode, and just make sure the part of the file need to be changed is valid with latest state. 最合乎逻辑的方式是,您需要在队列模式下进行操作,只需确保需要更改的文件部分在最新状态下有效。

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

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