multithreading - Allow only one Thread to access a particular file in Java -
i have folder large number of files in it. there 1 cron job takes 10 file names @ time e.g. file1, file2....., file10 , creates 10 new threads read files. content of files extracted , dumped in process(irrelevant) , file deleted
now problem if 1 of threads takes more minute process file, cron job triggers again , picks same file again not deleted yet , processes content again.
is there way restrict thread reading file/creating file object if there thread reading content it.
i can have synchronized hash map store details of 10 files 10 threads processing , check map before assign file thread finding difficult believe there no better way in java.
obviously need "sync point" between different threads; that, there plenty of options.
when threads running in same jvm, use class like
class currentlyprocessedfilestracker { synchronized void markfileforprocessing(file f) { } synchronized void markfileasdone(file f) {
or alike (where first 1 throw exception in case provided file known).
then have make sure threads have access same instance of class ... , use "lock" , "unlock" while being busy working file.
if there more 1 jvm, things become more complicated. need either inter-process communication; or go idea scary wombat , have "scheduler part" rename files (depending on context might idea; or not; depends other "responsibilities" scheduler part has - shouldn't put things 1 component).
Comments
Post a Comment