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: 
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);
}

```
You can use the following code in you thread program.

```
 try {
        // Get a file channel for the file
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        // Use the file channel to create a lock on the file.
        // This method blocks until it can retrieve the lock.
        FileLock lock = channel.lock();

        // Try acquiring the lock without blocking. This method returns
        // null or throws an exception if the file is already locked.
        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
        }

        // Release the lock
        lock.release();

        // Close the file
        channel.close();
    } catch (Exception e) {
    }

```