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