-
-
Save ntung/fa78687244c9c49c654780896216163f 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