Well, the flag had to be set before executing the action. Unfortunatelly checking and setting the flag can not be atomic over all nodes. So this might lead to a race condition that multiple instances enter the "synchronized" area. (Which in fact is not synchronized.)
if (flag)
// <--- here the race condition might occur
flag = true;
doSomeLongRunningTasksInDB();
flag = false;
}