In fact, I do not use such synchronization. As soon as I did it. It seems to work very well. Here is an example
String syncKey = "Sync:" + req.getRequestURI(); boolean lockAcquired = false; try { lockAcquired = acquireLock(syncKey, 5000L); if (!lockAcquired) { return; } // do something here } finally { if (lockAcquired) { memcacheService.delete(syncKey); } } public boolean acquireLock(String syncKey, long maxwait) { long start = System.currentTimeMillis(); while (true) { if (memcacheService.increment(syncKey, 1L, 0L) == 1L) { return true; } if (System.currentTimeMillis() - start > maxwait) { return false; } try { Thread.sleep(100L); } catch (InterruptedException e) { } } }
I usually use more simplified synchronization. This gives me the ability to run part of the code only once.
final long now = System.currentTimeMillis() / (60L * 1000L);
source share