Life_Hacker Life_Hacker - 5 months ago 21
Java Question

How to make a class with static members and function thread safe?

I have a class defined as:

class Artifacts {
private static boolean isThreadStarted = false;
private SomeClass someClass;
public static void startThread() {
isThreadStarted = true;
}
public static void setSomeClass(SomeClass = someClass1) {
if(isThreadStarted) {
someClass = someClass1;
}
}
public static SomeClass getSomeClass() {
return someClass;
}
}


Now the use case is that a method will make the value of isThreadStarted to be true. After that, a thread will start and using the value of someClass.There can be multiple threads setting and getting the value of someClass. I want to make this thread safe.

There is an annotation
@ThreadSafe
and there is a function
synchronized static
which I guess will do the thing. Please help in deciding the right approach.

Answer Source

Life_Hacker,

1st way

use static synchronized keyword with function to make Class Level lock in multithreading environment.

example :

public static synchronized void setSomeClass(Artifacts.class) {
   if(isThreadStarted) {
       someClass = someClass1;
   }
}

2nd way

inside function definition, you can create Synchronize Block

example:

public static void setSomeClass(SomeClass = someClass1) {

     synchronized(this){

          if(isThreadStarted) {
            someClass = someClass1;
          }
    }
}

2nd way is best approach