java - How can I lock a file if it exists, don't create it? -


i want test see if can lock file x. if file doesn't exist or can't locked, fail. sounds simple, keep running dead-ends. short-cut answer provide way filechannel can make exclusive lock on, without risk of creating file. let me explain...

i can't use nio lock() without writable filechannel , can't writable filechannel without opening file x in such way if doesn't exist, created. every java method i've found trying open file x writable creates if doesn't exist , there doesn't seem way exclusively lock file on read-only filechannel.

even checking confirm file exists first problematic. here's latest code:

private lockstatus openandlockfile(file file) {              if (files.notexists(file.topath())) {                 synchronized (filelist) {                     removefile(file);                 }                 return lockstatus.file_not_found;             }             try {                    rwfile = new randomaccessfile(file, "rw");                 filelock = rwfile.getchannel().lock();                               }              catch ... 

the problem code file might exist when notexists code runs, gone time new randomaccessfile(file, "rw") runs. because i'm running code in multiple threads , multiple processes means code has air-tight , rock solid.

here's example of problem existing code running in 2 processes:

1: process detects new file

2: process b detects same file

3: process processes file , moves folder

problem ---> process b accidentally creates empty file. oops!!!

4: process b detects new file created process b , processes creating duplicate file 0 bytes.

5: process detects new file accidentally created process b , tries process it...

bigger screenshot

http://i.imgur.com/klmnxlz.png

here's example using c# of i'm trying do:

stream istream = file.open("c:\\software\\code.txt", filemode.open,     fileaccess.read, fileshare.none) 

any or hints appreciated! thanks!

if trying prevent 2 threads in same application (same jvm) processing same file, should implementing using regular java locks, not file locks. file locks granted jvm , reentrant ... if 1 thread "locks" file, thread can acquire lock on same file.

what create thread-safe locking class wraps hashset<file>, file objects denote absolute file paths files exist. implement "file locking" locking on file objects.


unfortunately not in different jvms, on different server.

in case, best strategy use database implement locks.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -