Peter
Peter

Reputation: 857

Are references to Java enum values global?

Let's say I have an enum with multiple values, for example:

public enum Category {
  A, B, C, D;
}

And would like to create a locking mechanism so that we are only processing one item per category at a single time. My first idea was to do something like this:

Set categories = new HashSet();
for (Category cat : Category.values() {
  categories.put(cat);
}

and then when I need to acquire a lock, I do the following:

synchronized(categories.get(category)) {
  ....
}

will this work or are all references to an enum value global so if some other thread, elsewhere, did the same thing they would block each other?

Thanks!

Upvotes: 1

Views: 1125

Answers (3)

JB Nizet
JB Nizet

Reputation: 691943

Each enum value is a singleton. Only one instance exists for the classloader which loaded the enum class. So yes, if two threads use an enum value as a lock, they will use the same lock and thus block each other.

Side note: your question would be clearer if you used valid, compiling Java code.

Upvotes: 4

assylias
assylias

Reputation: 328735

There is only one Category.A instance, so all synchronized(Category.A) will block each other, which is what you are doing with your set.

You could use a private final EnumMap associated to your enum, fill it with new Object()s, make sure you don't modify the map, and use the object associated with the category as a lock for that category. That way you are sure that the lock is only used in that piece of code.

Upvotes: 3

Bonny Bonev
Bonny Bonev

Reputation: 131

Your enum will be visible in your project (package). If you need to use this logick elsewhere, you will need to add reference to this project.

Upvotes: 0

Related Questions