?
Solved

Thread question

Posted on 2003-02-25
11
Medium Priority
?
217 Views
Last Modified: 2010-03-31
I have multiple threads that are reading and writing to text files.  How can I be sure that a Thread wont try to access the text file while while another is reading or writing to the same one?

I can't use the Synchronize command on the method, because I want the method to be able to handle multiple threads writing to different files at the same time.
0
Comment
Question by:lwinkenb
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +3
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 8019475
What's wrong with:

public synchronized void writeToFile(String fileName){}

?
0
 
LVL 3

Expert Comment

by:allahabad
ID: 8019724
When one thread is writing it locks the resource, so you would need to wory that any other thread will go and write to the same file, when one thread is locking.

public synchronized void writeToFile(String fileName) , this is synchronized which  means for other thread  to get access to File object, lock need to be released.

No need to write Synchronize on the method, call  writeToFile, this will lock the file resource when one thread is writing, and release when File object is closed or exception is thrown.
0
 
LVL 1

Expert Comment

by:shji1
ID: 8019728
If you insist on not using the synchronized (not even in a part of the method) you can (maybe) use a HashMap in order to keep track on all the files you are currently writing to or reading from. You will have to update this HashMap all the time.
--
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 86

Expert Comment

by:CEHJ
ID: 8019770
Or even

public synchronized void accessFile(String fileName, boolean reading) {
  // if not reading then writing
}

?
0
 
LVL 5

Author Comment

by:lwinkenb
ID: 8019844
CEHJ >>
If I did it that way, my understanding is if one thread passed through "fileA.txt", and a second thread passed through "fileB.txt", the method would wait for the first thread to exit the method before the second thread started.

I want both files to be written at the same time if they are different.  Is my understanding of how the Synchronized method works wrong?  I'm still learning here.

Thanks,
0
 
LVL 3

Expert Comment

by:allahabad
ID: 8019969
Yes, you can do. because "fileA.txt" and "fileB.txt" are  two different File object.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8020386
You'll have to use a technique like shji1 has recommended as using the method i suggested will allow only one operation at once so it will limit your potential writes
0
 
LVL 2

Accepted Solution

by:
warsql earned 400 total points
ID: 8023014
How about
File file = new File(fileName);
if (file.isDirectory() || (file.exists() && !file.canWrite())) {
  // we have a serious problem here
}
FileOutputStream fos = null;
while (fos == null) {
  try {
    fos = new FileOutputStream(file);
  } catch (FileNotFoundException e) {
    try {
      Thread.currentThread().sleep(100);
    } catch (InterruptedException ignored) {
    }
  }
  catch (SecurityException e) {
    // We have a serious problem here
  }
}
0
 
LVL 2

Expert Comment

by:warsql
ID: 8023048
FileNotFoundException should be thrown if file is in use.  Then we'll wait at least .1 seconds to try again.  If we hit a serious problem, we'll never be able to write to the file.  Something similar could be done for reading.
0
 

Expert Comment

by:barrettbarrett
ID: 8031112
The solution is to synchronize on an object that is unique to the particular file that you are writing to.  That way you will block other writers to the same file, but not block other writers to different files.

You just need to be sure that the objects you are synchronizing on have a one-to-one correspondence with the files.

For example:

File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
FileWriter fw1 = new FileWriter( file1 );
FileWriter fw2 = new FileWriter( file2 );

now you can launch lots of threads that write to these files as long as they write using calls to a method that synchronizes on the appropriate FileWriter:

void write( FileWriter fw, String text ) throws IOException {
  synchronized(fw) {
    fw.write( text );
  }
}

So writes to fw1 will synchronize on fw1 (blocking other writers to fw1, but not writers to fw2).  Likewise for fw2.
0
 
LVL 5

Author Comment

by:lwinkenb
ID: 8037985
Thanks to everyone for the help.  I accepted warsql's answer because his was the closest to what I implemented.
0

Featured Post

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month12 days, 4 hours left to enroll

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question