Method synchronization via JVM

How to organize synchronization of a method in JVM?

My example is a web application that restricts the registration of a username more than once (in other words, the first user can log in, but if another user signs up with the same username, he gets rejected).

The web application is deployed on multiple servers, so there are several JVMs, and users may try to log on to different servers depending on load balancing.

Here is the method

public synchronized static SessionData logonSync(String userName, String password) throws Exception { int count = DB.count("sessions", "WHERE user_name=?", userName); if (count > 0) { throw new Exception("logon.error.loginAlreadyUsed"); } return logon(userName, password); } 

It works correctly on 1 application server due to the synchronized method, but after several JVMs? Two users can simultaneously try to log in to different web applications. How can I prevent this?

* EDIT * The application also uses Memcached if your solution wants to use some transactional caching techniques.

+8
java concurrency synchronized jvm
source share
1 answer

You asked about method synchronization in the JVM. This requires a library that processes distributed processes. There are many options, here are just a few:

  • Terracotta - Supports setting up certain fields as "shared" in the JVM, so you can use a standard JVM lock, such as a synchronized keyword, and it will run on multiple JVMs.
  • JGroups - Jgroups is a toolkit for distributed applications. Locking is one of the features that it offers. Below is an example from the documentation

Setting up distributed locking is never easy, regardless of the library used. If you need it, itโ€™s good, but for your example it seems redundant. Other options:

  • Add a unique constraint to the database and enable uniqueness. This can affect database performance, so it really depends on how much traffic you expect to receive.
  • The load balancer uses the username (or hash) as the key that it uses to assign requests to the web server. This ensures that requests from the same username will be sent to the same web server every time - there is no need for a distributed lock, just use the usual one.
+9
source share

All Articles