跨集群共享 Java 同步块,还是使用全局锁?

2022-01-14 00:00:00 sql cluster-computing db2 locking java

我有一些代码只允许一个线程访问.我知道如何使用 synchronized 块或方法来完成此操作,但这是否适用于集群环境?

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 in a clustered environment?

目标环境为 WebSphere 6.0,集群中有 2 个节点.

The target environment is WebSphere 6.0, with 2 nodes in the cluster.

我感觉 synchronized 行不通,因为每个节点上的应用程序的每个实例都会有自己的 JVM,对吧?

I have a feeling that synchronized won't work, since each instance of the application on each node will have its own JVM, right?

我在这里尝试做的是在系统启动时对数据库记录进行一些更新.它将查找比代码版本更旧的任何数据库记录,并执行特定任务来更新它们.我只希望一个节点来执行这些升级,因为我想确保每个工作项只升级一次,并且这些升级的性能不是一个大问题,因为它只发生在应用程序启动时,它只是真正做任何事情自上次启动以来代码已更改的时间.

What I am trying to do here is perform some updates to database records when the system is booted. It will look for any database records that are older that the version of the code, and perform specific tasks to update them. I only want one node to perform these upgrades, since I want to be sure that each work item is only upgraded once, and performance of these upgrades is not a big concern, since it only happens at application startup, and it only really does anything when the code has been changed since the last time it started up.

数据库是DB2v9,我直接通过JNDI(无ORM层)访问.

The database is DB2v9, and I am accessing it directly via JNDI (no ORM layer).

有人建议在这里使用全局锁,但我不知道该怎么做.

It has been suggested that a global lock might be the way to go here, but I'm not sure how to do that.

有没有人指点一下这个领域?

Does anyone have any pointers in this arena?

谢谢!

推荐答案

您是正确的,跨进程同步将无法使用 Java 同步构造.幸运的是,您的问题实际上不是代码同步问题,而是与数据库的交互同步问题.

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.

处理这个问题的正确方法是使用数据库级锁.假设您有一些包含 db 架构版本的表,因此您应该确保在启动/升级过程中锁定该表.

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.

如果您指定数据库类型(DB2?)和访问方法(原始 sql、jpa 等),所涉及的精确 sql/db 调用可能会更清楚.

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).

更新(2009 年 8 月 4 日下午 2:39):我建议使用 LOCK TABLE 对一些持有模式版本号的表的声明.这将序列化对该表的访问,防止两个实例同时运行升级代码.

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.

相关文章