Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a class without fields thread safe

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 ?

like image 626
Tausif mohammad Avatar asked Aug 25 '26 20:08

Tausif mohammad


1 Answers

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

like image 121
Davide Lorenzo MARINO Avatar answered Aug 27 '26 10:08

Davide Lorenzo MARINO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!