Question: I have 10 threads that are started when my java class is started and they look into a directory and start looking for files . In one of my methods I change the .txt files extension to .working which indicates that a file is currently in process . When my java class is invoked or started I see sometimes only 5 files are being processed since their extension is .working . Kindly let me know how should I make sure that no 2 threads are calling the same .txt file !!

Answer: 
The simplest approach is to read the list of files in *one* thread, then use a thread-safe producer/consumer queue (e.g. [`ArrayBlockingQueue`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html)) to publish these "files to process". The ten threads will then all take items off the same queue, which ensures that no item is processed twice.
You are probably running into a race condition similar to the following pseudo code. Multiple threads will make the exists test and then try the rename and process the *same* file.

```
File file = new File("file.txt");
File working = new File("file.working");
if (file.exists()) {
   // race condition may happen at this point
   file.renameTo(working);
   processWorking(working);
}

```

You should synchronize around the test and rename. Something like:

```
private final Object lockObject = new Object();
...

boolean process = false;
// lock around the test and the rename
synchronized (lockObject) {
    if (file.exists()) {
       file.renameTo(working);
       process = true;
    }
}
// process the file outside of the lock
if (process) {
    processWorking(working);
}

```