Synchronizing a Method Across JVM's

前端 未结 1 733
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 11:35

How does one go about synchronizing a method across JVM\'s?

My example is a web application that restricts a user name from being logged in more than once (in other word

1条回答
  •  遥遥无期
    2021-02-04 12:11

    You asked about synchronizing methods across JVMs. That requires a library that handles distributed processes. There are many options, here are just a few:

    1. Terracotta - Supports configuring certain fields as 'shared' across JVMs, so you can use standard JVM locking, like the synchronized keyword, and it will work on multiple JVMs.
    2. JGroups - Jgroups is a toolkit for distributed applications. Locking is one of the features it offers. Here is an example from their documentation

    Setting up distributed locking is never easy, regardless of what library you use. If you need it, fine, but for your example this seems like overkill. Other options:

    • Add a uniqueness constraint in the Database and let is enforce uniqueness. This can have a performance impact on the database, so it really depends how much traffic you expect to get.
    • Have the load balancer use the username (or a hash of it) as the key that it uses to assign requests to a web server. This will guarantee that requests from the same username will arrive at the same web server every time - no need for a distributed lock, just use a regular one.

    0 讨论(0)
提交回复
热议问题