在 Web 应用程序的多线程环境中管理资源
您能否建议以下流程是否线程安全 -
Web 应用程序收到请求 ->从请求中获取数据->处理它->写入临时文件 ->临时文件进入批处理,将数据插入数据库。
我担心的是,当多个请求同时发生时,在临时文件上写入是否是线程安全的。
对于任何建议我都会非常高兴。
PS - Web应用程序本身并不插入数据,而是批处理过程,因为批处理过程与数据库的接口已经经过充分验证和测试(有点遗留应用程序)。
Could you please suggest if the below flow is thread safe -
Web application gets a request -> fetch the data from request -> process it -> write to a temp file -> temp file goes to batch process which inserts data in db.
My concern is when multiple request would be hitting at same time, writing on the temp file would be thread safe or not.
I would be more than happy for any suggestion.
P.S. - The web application is not inserting data itself but the batch process is because the interface of batch process with db is well proven and tested (kinda legacy application).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java Web 应用程序服务器对传入请求进行排队并创建工作线程池来处理它们。应用服务器从池中分配一个线程来处理队列头部的请求,因此从其角度来看,用于处理该请求的代码似乎是单线程的。
但服务器本身是多线程的,因为它使用线程池。由不同线程共享的数据或文件不是线程安全的。因此,您必须同步处理写入文件的代码部分或在写入操作期间锁定它。
如果临时文件不共享,那么就没有问题。您是否为每个请求创建一个文件?
Java web application servers queue up incoming requests and create a pool of worker threads to process them. The app server assigns a thread from the pool to process the request at the head of queue, so the code used to process that request appears to be single-threaded from its point of view.
But the server itself is multi-threaded, because it uses a pool of threads. Data or files that are shared by different threads are not thread-safe. So you'll have to synchronize the section of the code that deals with writing to the file or lock it during the write operation.
If the temp files are not shared, then you don't a problem. Do you create a file for each request?
如果您可以保证您的临时文件具有唯一的名称,并且每个请求都创建它自己的临时文件,那么我会说它是线程安全的(当然假设 servlet 中的处理也是线程安全的。)
If you can guarantee that your temp files have unique names, and each request creates it's own temp file, then I'd say it was threadsafe ( assuming of course that the processing within the servlet is also threadsafe. )
如果您使用同步方法写入临时文件(如果每个请求中都是同一个文件)。这与将线程安全写入套接字非常相似。
If you use a synchronized method to write to the temp file if it is the same file in every request. It is pretty similar to write thread safe to a socket.