3

If I make a class with only methods and no variables, with each method having its own local variable then, will that class be thread-safe? for eg.

   public class Client {

                public String xyz(final String inputXML) {
                      DataInputStream dis = null;
                      DataOutputStream dout = null;
                      Socket clientSocket = null;
                        //do some processing 
                    }

                public String abc(final String inputXML) {
                      DataInputStream dis = null;
                      DataOutputStream dout = null;
                      Socket clientSocket = null;
                        //do some processing 
                    }
        }

now if I launch multiple threads of this Client then, will the class be thread safe ?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • It is thread safe, but if you try to open the same socket from multiple threads you will still get concurrency issues. – Adriaan Koster Feb 12 '16 at 11:06
  • 1
    It is not the same Socket because there is no share data between different calls to those methods. If a new Socket is created in each thread it works on a different port on the client side so no data is mixed between socket connections. A socket is identified by the ip, port of the server and ip, port of the client. The port of the client changes in this case – Davide Lorenzo MARINO Feb 12 '16 at 11:17
  • See also http://stackoverflow.com/a/9735625/545127 – Raedwald Feb 12 '16 at 13:03

2 Answers2

5

Yes your class is thread safe.

A method is thread safe if:

  • has no access to shared variables
  • Access to shared immutable variables
  • Access to variables which state can be modified only in a thread safe manner (for example via synchronized methods)
  • Access to variables with a synchronized block using the same lock of other threads that use the same variable

Your methods haven't access to shared variables so are thread safe

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

Theoretically yes, practically it depends on the values of your variables if they are independent instances or if they point to the same instances somewhere in the system