English 中文(简体)
是否提到 Java的价值观是全球性的?
原标题:Are references to Java enum values global?

请允许我说,我有一个具有多重价值观的论坛,例如:

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

并且希望建立一个锁定机制,以便我们只在一个时间处理一个类别的项目。 我的第一个想法就是这样做:

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

在我需要获得一锁的时候,我做了以下工作:

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?

感谢!

问题回答

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.

附带说明:如果你有效,汇编 Java,你的问题就会更清楚。

只有一个<代码>。 “ instance, so all synchronized (Category.A) will block each other, which is what You are do with You set.

您可使用与您有关的私人定本EnumMap,将其填入new Object(>,确保你不修改地图,并将与这一类有关的物体用作该类的锁。 这样,你就可以确信,这一锁只用于该法典。

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.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签