java multithreading. sharing data in a thread-safe manner -
i'm programming tcp socket application in java , have doubt regards how in thread-save manner.
in eample, static method startserver(int port) creates passive tcp socket. in main, wait incoming connection, managed dedicated thread.
firs of all, understand interaction between threads.
let a, b 2 instance of same class:
- instance attributes of not visibile b;
- static attributes visible both , b.
let t1 , t2 2 threads of same class:
- does attributes visibility works in same manner instance? in other words, static attributes can shared thread?
- non static attributes thread-safe?
in code thread-safe?
import java.io.*; import java.net.*; import java.util.*; public class multithreadserver extends thread { private socket client; private string nonstaticattribute; private static volatile vector<string> clientsvector; public multithreadserver(socket c, string enc) {client = c; nonstaticattribute = new string("val=" + math.random());} /** create passive socket*/ public static serversocket startserver() throws bindexception, ioexception {clientsvector= new vector<string>();} public void run() { try { multithreadserver.clientsvector.addelement(clientname); // variable shared in thread-safe way between threads? vector in internally synchronized while(true) { /** line print different values each thread? (the value assigned in costructor?) or thread display same value (the value of costructor of last thread ? ) */ system.out(nonstaticattribute); thread.sleep(1000);} } catch(ioexception e) {} } } /** main */ public static void main(string[] argv) throws ioexception { // start del server myclass.startserver(); myclass t1 = new myclass(); t1.start(); myclass t2 = new myclass(); t2.start(); .... myclass tn = new myclass(); tn.start(); } }
if have correctly understood, locals instances attributes thread-safe, because have own state (in case multiple threads works independently multiple istances).
in opinion, use of static vector thread-save, because vector internally synchronized.
what's if use non synchronized resource file?
public class myclass extends thread { // same code other example private final static file file = new file("rubrica.txt"); void run() { ..... synchronized (file) {filewriter fout= new filewriter(file,true); fout.write("add content @ end"); fout.flush(); fout.close(); } }
i appreciate help.
wish nice day :)
Comments
Post a Comment