Created
August 2, 2017 23:18
-
-
Save pditommaso/4616192e50cd333487211d1e37e81d58 to your computer and use it in GitHub Desktop.
Prevent multiple JVM to access concurrently the same file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.channels.FileLock | |
final file = new RandomAccessFile(new File("foo.lock"), "rw") | |
println "<Entering in critical section>" | |
try { | |
/* | |
* wait to acquire a lock | |
*/ | |
def secs = 0 | |
FileLock lock | |
while( !(lock=file.getChannel().tryLock()) ) { | |
print "\rwaiting to acquire lock ${(secs+=100).intdiv(1000) } " | |
sleep 100 | |
} | |
/* | |
* now it can do the job | |
*/ | |
println '\r' | |
try { | |
int count = 20 | |
while( count>0 ) { | |
print "\rtime to finish job .. ${count--} " | |
sleep 1_000 | |
} | |
println "" | |
} | |
finally { | |
lock.close() | |
} | |
} | |
finally { | |
file.close() | |
} | |
println "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment