Multi node environment (cluster), how to make sure that the action is performed only once at startup?

My application runs in a cluster of 4 nodes. At startup (ServletContextListener), it should execute an SQL script. How to make sure that SQL is executed only once, and not 4 times, since each node will try to execute the same code?

+4
source share
1 answer

If you want to execute it exactly once (for example, scripts that update the database structure), you should use some kind of version field in the database (in the simplest case, only one table / one row). http://flywaydb.org/ may be the solution for you if you don't want to do it yourself. If instead you just want the instance instances to work with the same script at the same time, you use basically the same idea, but instead of using the version field that always grows, use the same logical lock that you reset after your script ends. If you want to implement ist yourself, be sure to handle concurrent access. 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

+1
source

All Articles