well...sorry if this seems dumb, but i am confused
so i thought i would clarify with a code sample
public class FileTester {
private static final int thread_count = 50;
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("out.txt");
Thread t[] = new Thread[thread_count];
for (int i = 0; i < t.length; i++) {
new Thread(new ConcurrentFileWriter(fos)).start();
}
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
class ConcurrentFileWriter implements Runnable{
int times = 3;
FileOutputStream fos;
public void run() {
for (int i = 0; i < times; i++) {
try {
fos.write(new String("thread id :" + Thread.currentThread().getId() + " - " + i + "\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public ConcurrentFileWriter(FileOutputStream fos) {
this.fos = fos;
}
}
so from this example the writing content is different(to clarify my position in response to anans reply).
but all threads are writing to the same fileoutputstream.
now in my app its ok if i get the following output - (scenario 1)
thread id: 1 - 1
thread id: 2 - 1
thread id: 1 - 2
and so on.....
is it possible for me to get the following output (strings interleaved) - (scenario 2)
thread id: 1 thread id: 2 - 1
- 1
thread id: 1 -2
I can live with scenario 1, but not with 2.
so is it possible for me to get scenario 2 without synchronization ?
i hope i have clarified what i meant
Message was edited by:
chhasid
Message was edited by:
chhasid
I am no language lawyer but I have the feeling this is not exactly defined. I would synchronize the writing on the output stream object to be sure.
I made a test out of curiosity: several threads were writing 2 MB data concurrently on the same output stream object. On Windows the data were written sequentially whereas on Linux the last one overwrrote the previous ones.