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

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

    You are correct that synchronization across processes will not work using the Java synchronization constructs. Fortunately, your problem really isn't one of code synchronization, but rather of synchronizing interactions with the database.

    The right way to deal with this problem is with database level locks. Presumably you have some table that contains a db schema version, so you should make sure to lock that table for the duration of the startup/upgrade process.

    The precise sql/db calls involved would probably be more clear if you specified your database type (DB2?) and access method (raw sql, jpa, etc).

    Update (8/4/2009 2:39PM): I suggest the LOCK TABLE statement on some table holding the version # of the schema. This will serialize access to that table preventing two instances from running through the upgrade code at once.

提交回复
热议问题