dorothy
dorothy

Reputation: 1243

Java Runnable File IO

i have written a Runnable class

private static class Processing implements Runnable {
    private static File file;
    private static byte[] message;
    public Processing ( File f, byte[] m ){
        this.file = f;
        this.message = m;
    }       
    public void run(){
        WriteToFile( file , message );
                          ... other processing....
    }

private static void WriteToFile( File f , byte[] msg ){
    FileOutputStream fs = null;
    try {
        fs =  new FileOutputStream( f )  ;
        fs.write(  msg );
        fs.flush();
        fs.close(); 
    }catch (Exception e){
        e.printStackTrace();
    }

}

In the main class

public class MainClass{
   public void somemethod(){
      ....
      ( new Thread(new Processing ( <somefile> , <somebytes> ))).start();
      ....
   }

}

My question is

  1. is this method correct? my wish is to improve file io (in the WriteToFile method) because MainClass is called by more than 1000 users.
  2. How can I simulate 1000 users in the code? is it

    for (int i = 0 ; i<1000 ...){
      ( new Thread(new Processing ( <somefile> , <somebytes> ))).start();
    }
    

thanks

Upvotes: 1

Views: 291

Answers (3)

C.Champagne
C.Champagne

Reputation: 5489

I agree with Neeveks,'s answer but I can see two additional issues.

1) file and message should be instance variables and should not be static. Setting them static means that you can only manage one file and one message at once.

2) Method's name begin with lower case letter in Java. Please rename WriteToFile to writeToFile. This not a programming issue but it helps reading your code.

Upvotes: 3

Rohit Sachan
Rohit Sachan

Reputation: 1222

Looks ok, You can try Memory mapped files if data is large. You can get some reference from already existing ans about writing to files here.

Upvotes: 1

neevek
neevek

Reputation: 12138

  • For Q1: Looks okay, but bear in mind that you always close a stream in finally block, because write operation may fail, which may leave your file handle dangling.

  • For Q2: That's how it is done, as long as you are not writing to the same file with 1000 threads, in that case, you need to take thread safety into account.

Upvotes: 3

Related Questions