Does it make sense to synchronize web-service meth

2019-07-26 15:04发布

问题:

I'm creating a web-service written in Java and hosted on JBoss AS. I'm not a professional in web-service design yet but do I get it correctly and each call to the service initiates a new thread and not a new process? Does it make sense to have synchronized methods in my service? I need to have a method which is invoked only for one user at a time not simultaneously for multiple.

回答1:

Yes, requests are handled by individual handler threads. There is a single process for all of JBoss.

Synchronization can be problematic if your application ends up getting hosted across multiple nodes in a cluster. The locks won't propagate across multiple JVMs without the help of some magic like Terracotta. For a simple solution you can use a pessimistic row lock in your database to control access. One would of course be inclined to challenge the entire design that requires a blocking method and look for an alternative that can run in parallel.

Also, Locks from the java.util.concurrent package are preferred to the synchronized keyword if you are going that route.