java - Sharing PrintWriter between threads? -
i need synchronize access on printwriter. in code, i'm using printwriter write text file. on other project, i'm using printwriter send data through socket. , don't know how handle excess. need make thread-safe because can happen 2 thread access printwriter , send socket. don't know how because it's every time copy of object(call value). simple synchronized not work.
import java.io.file; import java.io.printwriter; import java.util.hashmap; import java.util.map; public class test { public static final void main(string[] args) { createsomestreams(); new accessstream("foo").start(); new accessstream("bar").start(); } private static map<integer, mystream> mymap = new hashmap<integer, mystream>(); private static class mystream { private printwriter printer; public mystream(printwriter printer) { this.printer = printer; } public printwriter getprinter() { return this.printer; } } private static class accessstream extends thread { private string printme; public accessstream(string msg) { this.printme = msg; } @override public void run() { try { printwriter stream = mymap.get(0).getprinter(); stream.println(this.printme); stream.close(); } catch(exception ec) { system.out.println("accessstream: " + ec); } } } private static void createsomestreams() { try { file file = new file("c:/users/user/desktop/test.txt"); if(!file.exists()) { file.createnewfile(); } printwriter writer = new printwriter(file); mystream mystream = new mystream(writer); mymap.put(0, mystream); } catch(exception ec) { system.out.println(ec); } } }
in file can read "foo", , "bar" missing. can explain me or have solution making threadsafty?
thanks.
but don't know how because it's every time copy of object(call value)
no isn't. copy of reference. both copies refer same object, , synchronized on.
just use synchronized(printer)
.
Comments
Post a Comment