Ikky
Ikky

Reputation: 2856

How to lock(sync) a static class?

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 :)

Upvotes: 0

Views: 1365

Answers (2)

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

AFAIK, there's no such thing as "static class" in Java. Do you mean a class that contains only static methods? If so, then

public static synchronized void insertIntoVector(int id) {

}

synchronizes with respect to the class object, which is sufficient, if there are only static methods and all of them are synchronized.

If you mean static inner class (where the word "static" has a different meaning than in static methods), then

public synchronized void insertIntoVector(int id)
{

}

synchronizes with respect to an instance of that static inner class.

Upvotes: 1

Andrzej Doyle
Andrzej Doyle

Reputation: 103847

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, or synchronized(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 a setFoo() (perhaps after incrementing the foo variable) may not have the desired effect if another thread called setFoo() inbetween. The best approach would be to have a method such as incrementFoo(); 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.

Upvotes: 5

Related Questions