I want to create a class which will be accessed by multiple threads for getting a data. So I have a method like this:
public static String getData(){
//some logic before returning the value
// return data once initialized
}
Now there will be method which will set that data:
private void setData(){
}
I want this setData
to be called only once, so thought of including it in static
block:
static {
setData()
}
Now I have these questions:
I'm planning to create a static class for this, so that other threads can call like this:
ThreadSafe.getData();
In my
getData
, I want to check first the validity of that data before returning, if the data is invalid, I need to again callsetData
and then return it. Given this fact, I need to makegetData
synchronized
right?
will my above approach work in a multi threading environment?