1

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

dorothy
  • 1,213
  • 5
  • 20
  • 35

3 Answers3

3
  • 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.

neevek
  • 11,760
  • 8
  • 55
  • 73
3

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.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35
1

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.

Community
  • 1
  • 1
Rohit Sachan
  • 1,178
  • 1
  • 8
  • 16