Sharing a Java synchronized block across a cluster, or using a global lock?

前端 未结 5 1276
死守一世寂寞
死守一世寂寞 2021-02-01 07:14

I have some code that I want to only allow access to by one thread. I know how to accomplish this using either synchronized blocks or methods, but will this work i

5条回答
  •  走了就别回头了
    2021-02-01 07:42

    Yes, you are correct in that synchronized blocks won't work across a cluster. The reason is, as you stated, that each node has its own JVM.

    There are ways, however, to get synchronized blocks to work in a cluster as they would work in a single-node environment. The easiest way is to use a product like Terracotta, which will handle the coordination of threads between different JVMs so that normal concurrency controls can be used across the cluster. There are many articles explaining how this works, like Introduction to OpenTerracotta.

    There are other solutions, of course. It mostly depends on what you really want to achieve here. I wouldn't use database locks for synchronizing if you need to scale, as DB doesn't. But I really urge you to find a ready-made solution, because messing around with cluster synchronization is messy business :)

提交回复
热议问题