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 an enum
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:
enum Decades {
NINETIES( "dope", "fly", "bomb", "tight" ),
EIGHTIES( "bad", "righteous", "sick", "gnarly" ),
SEVENTIES( "boss", "choice", "funky" );
final String[] phrases;
volatile int currentPhrase = 0;
Decades( String... phrases ){
this.phrases = phrases;
}
synchronized String getCoolPhrase(){
final String result = phrases[currentPhrase];
currentPhrase = (currentPhrase + 1) % phrases.length;
return result;
}
}
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