IUnknown
IUnknown

Reputation: 9819

synchronizing on enum monitor

I read that from 1.5 we can use enum for singleton

public enum Singleton {

  INSTANCE;

  //Singleton method
  public void someMethod( ) {...}
}

Singleton.INSTANCE.someMethod( );

Does this mean every entry in an enum type is a instance by itself? If I define a enum type with a class,can I use block synchronization on every entry in teh enum type?

class smokers extends Thread{

    public enum restype{
        TOBACCO,MATCH,PAPER 
    }

    public void run(){
        if(xxxx){

        synchronized(restype.PAPER){
                    ....
            }
        }
        else
        {
            synchronized(restype.MATCH){
                    ....
            }

        }
    }

Is this valid code?

Upvotes: 0

Views: 4879

Answers (3)

Amit Deshpande
Amit Deshpande

Reputation: 19185

You can read about Enums here. Since its a constant and has only one instance you don't need synchronization.

But if you are changing values of members using setters then you will need to add synchronization.

public enum Restype {
    TOBACCO(1), MATCH(2), PAPER(3);

    private int value = 0;//I have purposefully not declare it as final

    private Restype(int value) {
        this.setValue(value);
    }

    public void setValue(int value) {// now I can change value in multiple
                                        // threads.
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

Now I will have various ways to achieve synchronization for setValue and getValue easiest will be to declare them synchronized.

But clearly above is Misuse of Enums.

In java you can have syncrhonized block on any object so you can have synchronized block on enum instances also.

synchronized (Restype.TOBACCO) {
        // Allowed not recommenced 
        //every class should define its own mutex
    }

Upvotes: 1

Augusto
Augusto

Reputation: 29977

The code looks valid, but if you need to do that, put the logic in the enum

public enum RestType{
    PAPER{
        public synchronized void foo(){ return true };
    },
    MATCH{
        public void foo(){ return false };
    };

    public abstract boolean foo(); //I've never see an abstract method define a 
                                   //synchronized method... so I have not 
                                   //idea if it's valid
}

Upvotes: 0

kosa
kosa

Reputation: 66657

TOBACCO,MATCH,PAPER each is instance of type restype.

You can't modify enum constants, so don't need to synchronize.

If you want to use them as object locks, yes it is valid.

NOTE: Java naming convention suggests that use first letter as Capital letter for class name.

Upvotes: 1

Related Questions