Skip to content

Instantly share code, notes, and snippets.

@ntung
Forked from pditommaso/sync.groovy
Created July 7, 2020 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntung/fa78687244c9c49c654780896216163f to your computer and use it in GitHub Desktop.
Save ntung/fa78687244c9c49c654780896216163f 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