-1

I want to disobey controller's method process more than one request at a time. Is there any good way to implement this?

Problem appeares when I call methods by ajax post/get requests. I declared timeout for ajax. By timeout js resends ajax request. Sometimes server doesnt ready to response at a given timeout. So during processing one ajax request server starts processing another ajax request, and I get troubles.

I know that I can fix it on client side by $.when().done() or by ajax success functions, but I have no idea how to fix it on server side. Any ideas?

Altemriod
  • 13
  • 1

1 Answers1

0

If you need to ensure that a particular block of code executes only once at a time (whether it's a controller action or something else) you can use java's synchronized keyword. You can add method level synchronization by adding this to the method signature, though I don't know how well that works with a controller action (I've never tried). You can also add a synchronized block by wrapping code as such:

// inside your controller action
synchronized {
    // will only execute once concurrently within your JVM
}

Or you can synchronize on some object so that your synchronization could be based on some parameter:

// inside your controller action
synchronized ("${params.something}-whatever".intern()) {
    // will only execute one concurrently per unique 'key'
}

There are nuances worth learning about (such as what happens if you call this method from within itself: it will work, and memory implications of interning strings vs using some other key objects for synchronization) but this is a general pattern that should allow you to control concurrent execution of potentially-thread-unsafe code.

With all of that said, be careful implementing a pattern like this. It is pretty easy to end up with poor performance or even deadlocks, when often the underlying problem is in your client-side code and a need to better handle duplicate or aborted requests!

Daniel
  • 3,312
  • 1
  • 14
  • 31
  • See https://stackoverflow.com/questions/10578984/what-is-java-string-interning for a discussion (old but still useful) on string interning. See https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html and https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html for info on synchronization in java. – Daniel Dec 11 '18 at 21:50