0

Have a question about multiple clients connecting a single server. Here is my server side code:

//...    
ServerSocket serverSocket = null;
        try{
            serverSocket = new ServerSocket(port);
        }catch(IOException e){
            e.printStackTrace();
        }
        Socket server = null;

        while(true){
            try{
                server = serverSocket.accept();
                new createdThread(server).start(); //This is a thread class specified somewhere else to handle the socket. 
            }catch(IOException e){
                e.printStackTrace();
            }

createdThread() is a thread that will start to handle the socket, and it takes the Socket server as an argument. Suppose I have a connection and a thread starts, the accepted socket was passed to the thread as an argument. In this case, server should be passed as a reference if I'm not wrong. If before the end of the first thread, serverSocketgets a new connection and create a new socket, which will change the value of server. Will this impact the execution of the first thread since the first thread takes the reference as its argument, meaning the underlying object of that reference is changed?

I tested the program and it seemed working well. Each thread was not impacted by each other, although all of their constructor arguments are references to the same object. This does not make sense to me, and hope someone could clarify. Thanks.

Jason
  • 63
  • 4

2 Answers2

1

When server object is passed to createdThread() method a second copy of the same reference to it is created. Take a look at "Figure 1" here. So when you change the value of server object inside the loop one reference is lost but the second one still exists inside the method which is used by a thread.

Mikita Harbacheuski
  • 2,193
  • 8
  • 16
1

Suppose I have a connection and a thread starts, the accepted socket was passed to the thread as an argument.

By value. In other words, by copy.

In this case, server should be passed as a reference if I'm not wrong.

As the value of a reference to Socket.

If before the end of the first thread, serverSocketgets a new connection and create a new socket, which will change the value of server.

Correct.

No it Will this impact the execution of the first thread

No.

since the first thread takes the reference as its argument

No it doesn't. It takes the value of the reference as its argument, and (presumably) stores that into yet another variable. Not the original server variable.

meaning the underlying object of that reference is changed?

No.

user207421
  • 305,947
  • 44
  • 307
  • 483