問題描述
我有一些代碼只允許一個線程訪問.我知道如何使用 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.
這篇關于跨集群共享 Java 同步塊,還是使用全局鎖?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!