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

前端 未结 5 1361
死守一世寂寞
死守一世寂寞 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:53

    Since you are talking about 2 machines, you don't even have shared memory so there is nothing to synchronize.

    We do something similar with our database. This is achieved by adding record versioning in the table. This is what you should do,

    1. Add a column for record/row version.
    2. Go through the logic to check if record needs to be updated.
    3. When you update record, make sure the record version in DB is the same as what you have.
    4. Bump up version every time you write to the database.

    You should only have one server updating the database if you follow these rules.

提交回复
热议问题