Skip to content

Instantly share code, notes, and snippets.

@pditommaso
Created August 2, 2017 23:18
Show Gist options
  • Save pditommaso/4616192e50cd333487211d1e37e81d58 to your computer and use it in GitHub Desktop.
Save pditommaso/4616192e50cd333487211d1e37e81d58 to your computer and use it in GitHub Desktop.
Prevent multiple JVM to access concurrently the same file
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