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 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) {
    }

```