Java – how to prevent concurrency in Web Service APIs?
We have three web services (/ A, / B, / C), where each service maps to a method (go ()) in a separate Java class (classA, ClassB, ClassC)
Only one service should be running at the same time (i.e. / B cannot run while / A is running) However, because this is a rest API, it cannot prevent clients from requesting concurrent services
What is the best and easiest way on the server to force the service not to run at the same time?
Update: This is an internal application. We won't have a large load. There is only one application server
Update: This is a subjective question because you can make different arguments about the general application design that affects the final answer When I found the most interesting and helpful, I accepted the translation's answer
Solution
Assuming that it is impossible to force the web server to have only one listening thread for service requests... I think I just use a static lock (for clarity, it may be reentrantlock, although you can synchronize on any shared object):
public class Global { public static final Lock webLock = new reentrantlock(); } public class ClassA { public void go() { Global.webLock.lock() try { // do A stuff } finally { Global.webLock.unlock() } } } public class ClassB { public void go() { Global.webLock.lock() try { // do B stuff } finally { Global.webLock.unlock() } } } public class ClassC { public void go() { Global.webLock.lock() try { // do C stuff } finally { Global.webLock.unlock() } } }