I am writing a multi-thread program in Java, where i am creating a seperate thread to handle each new client connection. I have:
Socket s;
while(true)
{
s = server.accept();
ClientHandler ch = new ClientHandler(s);
Thread servingThread = new Thread(ch);
servingThread.start();
}
In the ClientHandler thread i have:
public class ClientHandler implements Runnable
{
private Socket s;
public ClientHandler(Socket _Socket, boolean _accepted, BaseStation _bs)
{
this.s = _Socket;
}
If in Java i can’t pass an object but only a reference to it, isn’t that going to cause a problem, to the s instance inside ClientHandler whenever server accepts a new connection?
Is it not going to change inside ClientHandler too and corrupt it? If so, what’s the correct way to do it?
Your concern is correct because the
Socketobject (like any other object in Java) is passed by reference, therefore there is a probability of it being referenced by different modules, or different threads, causing unpredictable behaviour.However in case of your program there is no problem. The reason is: whenever server accepts a new connection it will create a new
Socketobject, which you are then passing to a new instance ofClientHandler. Therefore every new connection from the client will be served by an independentClientHandlerinstance, so there are no race conditions to theSocketobject to worry about. So you are safe for now.As a counter-example if you decide to create two
ClientHandlerthreads to read from the sameSocketobject like this …… then you might be in trouble because two
ClientHandlers will get the same reference to the sameSocketobject and if both attempt to read from the same socket they will each get only half of the data. E.g. if you are receiving a string"hello", you might end up withchreading"hel"andch2reading"lo", or any other combination.