简体   繁体   English

并发:处理Web应用程序中的多个提交

[英]Concurrency : Handling multiple submits in a web application

This is a recent interview question to my friend: 这是我朋友最近的面试问题:

How would you handle a situation where users enter some data in the screen and let's say 5 of them clicked on the Submit button * the SAME time ? 如何处理用户在屏幕上输入一些数据的情况,让我们说其中5个点击了提交按钮* 相同的时间 * *

(By same time,the interviewer insisted that they are same to the level of nanoseconds) (与此同时,采访者坚持认为它们与纳秒级相同)

My answer was just to make the method that handles the request synchronized and only one request can acquire the lock on the method at a given time. 我的答案只是使处理请求的方法同步,并且只有一个请求可以在给定时间获取方法上的锁。

But it looks like the interviewer kept insisting there was a "better way" to handle it . 但看起来采访者坚持认为有一种“更好的方法”来处理它。

One other approach to handle locking at the database level, but I don't think it is "better". 另一种在数据库级别处理锁定的方法,但我不认为它“更好”。

Are there any other approaches. 还有其他方法吗? This seems to be a fairly common problem. 这似乎是一个相当普遍的问题。

If you have only one network card, you can only have one request coming down it at once. 如果您只有一个网卡,则一次只能有一个请求。 ;) ;)

The answer he is probably looking for is something like 他可能正在寻找的答案是这样的

  • Make the servlet stateless so they can be executed concurrently. 使servlet无状态,以便它们可以同时执行。
  • Use components which allow thread safe concurrent access like Atomic* or Concurrent* 使用允许线程安全并发访问的组件,如Atomic *或Concurrent *
  • Use locks only where you obsolutely have to. 只在你绝对需要的地方使用锁。

What I prefer to do is to make the service so fast it can respond before the next resquest can come in. ;) Though I don't have the overhead of Java EE or databases to worry about. 我更喜欢做的是使服务如此之快,以便在下一次resquest之前响应。;)虽然我没有担心Java EE或数据库的开销。

Does it matter that they click at the same time eg are they both updating the same record on a database? 他们同时点击是否重要,例如他们是否都在更新数据库中的相同记录?

A synchronized method will not cut it, especially if it's a webapp distributed amongst multiple JVMs. 同步方法不会削减它,特别是如果它是在多个JVM之间分布的webapp。 Also the synchronized method may block, but then the other threads would just fire after the first completes and you'd have lost writes. 同步方法也可以阻塞,但是其他线程只会在第一次完成后触发并且您丢失了写入。

So locking at database level seems to be the option here ie if the record has been updated, report an error back to the users whose updates were serviced after the first. 因此,锁定在数据库级别似乎是这里的选项,即如果记录已更新,则向第一个之后提供服务的用户报告错误。

You do not have to worry about this as web server launches each request in isolated thread and manages it. 您不必担心这一点,因为Web服务器在隔离线程中启动每个请求并对其进行管理。

But if you have some shared resource like some file for logging then you need to achieve concurrency and put thread lock on it in request and inter requests 但是,如果您有一些共享资源,如某些文件用于日志记录,那么您需要实现并发并在请求和内部请求中对其进行线程锁定

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

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