I’m creating a static class which is going to hold some vectors with info.
I have to make it synchronized so that the class will be locked if someone is editing or reading from the vectors.
What is the best way to do this?
Is it enough to have a function which is synchronized inside the class like this:
public synchronized insertIntoVector(int id)
{
}
Thanks in advance 🙂
Firstly, you need to define exactly what you mean by “static class”. At first, I thought you meant a class where all methods were static (that wasn’t meant to be instantiated) – but your code snippet implies this isn’t the case.
In any case, synchronized methods inside the class are equivalent to
synchronized(this)if they are instance methods, orsynchronized(TheContainingClassName.class)if they’re static methods.If you are either creating a non-instantiable class with all static methods, or if you are creating a class that will act as a singleton, then synchronizing every method of the class will ensure that only one thread can be calling methods at once.
Do try to ensure that your methods are atomic though, if possible; calls to different methods can be interleaved by other threads, so something like a
getFoo()call followed by asetFoo()(perhaps after incrementing the foo variable) may not have the desired effect if another thread calledsetFoo()inbetween. The best approach would be to have a method such asincrementFoo(); alternatively (if this is not possible) you can publish the synchronization details so that your callers can manually hold a lock over the class/instance during the entire sequence of calls.