restrict access to a file from multiple threads

I need an effective way to restrict access to a File from multiple threads. The FileLocking works to restrict access between JVMs but not between threads in a JVM.Any ideas would be of great help!ThanksBrian Husted
[242 byte] By [bhuste1a] at [2007-10-3 3:24:21]
# 1

A couple of solutions come to mind:

1. Temporarily rename the file when one thread accesses it and then rename it back to its original name when the thread is done

2. Store the file in a variable if it's not too large and then delete the actual file. When done recreate the file and put the contents back

billyChilla at 2007-7-14 21:17:05 > top of Java-index,Core,Core APIs...
# 2
#2 is not atomic so it can't work.You probably need to use a java.util.concurrent.Semaphore on the file within your JVM and a FileLock as well to protect against other instances of your program, if that can arise.
ejpa at 2007-7-14 21:17:05 > top of Java-index,Core,Core APIs...
# 3
It will be good to use a singleton pattern to restrict access to the file. Just one object in a JVM will have privileges to do operations with the file. Expose one synchronized method on this object which has all file operations.
gautamwada at 2007-7-14 21:17:05 > top of Java-index,Core,Core APIs...
# 4
I feel the method in which u write the code is to be declared synchronized so that access from multiple threads is denied until current thread execution is completed.If ur writing code in blocks go for synchronized blocks.
KKC_12a at 2007-7-14 21:17:05 > top of Java-index,Core,Core APIs...
# 5

File f = new File("smallFile.txt");

SomeReader sr = new SomeReader(f);

String fileContents = sr.getContents();

sr.close();

f.delete();

//do other stuff with file

f.createNewFile();

or

File f = new File("smallFile.txt");

f.renameTo("tempName");

//do other stuff with file

f.renameTo("smallFile.txt");

This is a hack way of doing it but, if another Thread tries to access the file it won't be there.

Using "synchronized" methods works best.

Message was edited by:

billyChill

billyChilla at 2007-7-14 21:17:05 > top of Java-index,Core,Core APIs...