CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   Multithreading file writing (http://www.codingforums.com/showthread.php?t=269408)

kainard 08-02-2012 08:01 PM

Multithreading file writing
 
Hi all,
I'm looking for a simple java example of a multithread server that creates a number of threads that open and write the same file in a synchronized way.

Can someone link an example or write a sample code? Google didnt help me

Thanks in advance

Fou-Lu 08-02-2012 08:38 PM

Doesn't really matter what you do with it. Simply search for thread synchronization in Java.
All you need to do is control the condition of the wait and notify so that when one thread is writing to the file it blocks all other threads from opening until its finished. When done, notify so that another thread can pick it up.

kainard 08-02-2012 10:21 PM

I found this example http://www.java-samples.com/showtuto...tutorialid=306 it's clear how to use it if I push and pop with different methods, but if I only use a method like this

PHP Code:

    synchronized public void writeStuff(String msgthrows Exception {
       
        
FileOutputStream file = new FileOutputStream("file.txt"true);
        
PrintStream ps = new PrintStream(file);
        
        
ps.println(msg);
        
    } 

in every thread, how do I use wait() and notify()? Or just synchronized is enough?


All times are GMT +1. The time now is 10:00 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.