multithreading - client number in a java multithread server -


i use 2 classes in server

myserver.java

private executorservice executorservice = executors.newfixedthreadpool(10);          public static void main(string[] args) throws ioexception {   server = new myserver();   server.runserver(); }  private void runserver() {           int serverport = 8071;   try {     system.out.println("starting server");     serversocket = new serversocket(serverport);       while(true) {       system.out.println("waiting request");       try {         socket s = serversocket.accept();         system.out.println("processing request");         executorservice.submit(new servicerequest(s));       } catch(ioexception ioe) {         system.out.println("error accepting connection");         ioe.printstacktrace();       }     }   }catch(ioexception e) {     system.out.println("error starting server on "+serverport);     e.printstacktrace();   } } 

and

servicerequest.java

private socket socket; bufferedreader input = null;  public servicerequest(socket connection) {   this.socket = connection; }  public void run() {    try {     //input = new bufferedreader(new inputstreamreader(socket.getinputstream()));       datainputstream din = new datainputstream(socket.getinputstream());      system.out.println("client "+ clientid +"connected"); 

i want number of each client in run() ( want result in last line of code ). how this?

when create new service request, can keep global counter ids... it's important use atomiclong, not regular int or long, if want keep unique ids.

private static atomiclong idcounter = new atomiclong(); private long clientid = idcounter.incrementandget(); 

this how can create clientids in threadsafe way, instance variable clientid create new value atomically each time servicerequest generated.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -