lundi 7 novembre 2022

Should all the static methods be synchronised?

I will explain the two use-cases here:

  1. Static method which uses an Objects and perform some operations and returns the same Object:
     // Lets assume here SomeObject contains a function putInt which store a HashMap.
     public static SomeObject createIntPerfEvent(SomeObject objectName,
                                                final String eventName,
                                                final int value){
         objectName.putInt(eventName, value);
         return objectName;
     }

  1. Static method which Creates an Objects and perform some operations and returns the created Object:
     // Lets assume here SomeObject contains a function putInt which store a HashMap.
     public static SomeObject createIntPerfEvent(final String eventName,
                                                final int value){
         SomeObject object Name = new SomeObject();
         objectName.putInt(eventName, value);
         return objectName;
     }

For the above two examples, For Case 2 we should have a synchronised method because we are creating a new object and if it is not thread safe it could cause unwanted problems. But for the case 1 I wasn't sure if the same logic applies.

Can someone please explain why the first Case should or shouldn't be synchronised?

I tried creating a sample program to do the same thing, didn't face any problem. But was wondering if there is some Design pattern which advocates this.

Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire