Search code examples
javajakarta-eewebspherecluster-computing

multi node environment (cluster), how to make sure an action executed only once on startup?


My application is running on a cluster of 4 nodes. On startup (ServletContextListener) it must execute an SQL script. How to make sure that the SQL is executed only once and not 4 times as each of the nodes will try to execute the same code?


Solution

  • If you want to execute it exactly once (like scripts that update the database structure) you should use some kind of version field in the database (in the simplest case just a single column/single row table). http://flywaydb.org/ might be a solution for you if you don't want to do it yourself. If you instead just want to ensure that no to instances are running the same script concurrently, you use basically the same idea but instead of using a version field which is alway increased use same kind of boolean lock which you reset after after your script finishes. If you want to implement ist yourself, be sure to handle concurrent access properly. For example instead of select entry from lock /if entry = 0 update lock set entry = 1 which is non atomic do something like update lock set entry = 1 where entry = 0/check if number affected rows = 1