I stumbled upon this question and a couple of other along the same lines.
While we know creation of enum is thread safe and enums
are by birth singletons .
It kind of confuses me that why would any one want to have a synchronized
method with in an enum
. Yes I am fully aware that methods in an enum
are not thread safe but then what?
They must not try to change the state of an enum any way . If we are not concerned about change of state of an enum then why would we ever like a method in an enum to be thread safe.
Best Answer
If you design your
enum
so that the methods don't change its state, then they are by definition thread safe. It is, however, possible to introduce state into anenum
so that concurrent modification does become a problem.Should you? Probably not. However, since Java has the flexibility to allow concurrent access to members of an
enum
, synchronization tools are needed to ensure that behavior occurs correctly.Contrived example
Let's say you want to enumerate recent decades, and query them for phrases that people said when they wanted to say it was "cool." Since you don't want to favor any one of these phrases more than another, you want to make sure that they get used evenly, even across threads. You might try something like this:
If you're familiar with classic problems in concurrency (counting to 100 with multiple threads comes to mind), you'll know that without synchronization, two threads could see the value of
currentPhrase
, retrieve the phrase, and increment at the same time. This could result in repeated uses of the same phrase, since one thread didn't know that a phrase had already been used when it read the counter.Cool phrases inspired by http://www.thebestpageintheuniverse.net/c.cgi?u=epic