Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix volatile and synchronized as a read-write lock

Consider a primitive type variable with lots of threads reading and a few threads writing, will the following code work correctly?

If it will, does it provide better performance than 1). declaring synchronized on all the methods; 2). using an explicit ReadWriteLock?

Is this a common pattern? If not, what pattern is usually used in this situation?

This currently works fine for me, but I feel it's a bit redundant to use both volatile and synchronized.

private volatile int value = 1;

public void func1()
{
    if (value == 1) {
        // do something
    }
}

public void func2()
{
    if (value == 2) {
        // do something
    }
}

public void func3()
{
    if (value == 3) {
        // do something
    }
}

public synchronized void increase()
{
    if (value < 10) value++;
}

public synchronized void decrease()
{
    if (value > 0) value--;
}
like image 579
Hongbo Avatar asked Nov 27 '10 02:11

Hongbo


1 Answers

Yes, it is common, at least to a certain degree :)

The pattern you are using is described in this IBM article -> http://www.ibm.com/developerworks/java/library/j-jtp06197/index.html

(pattern #5, cheap read-write lock trick)

like image 170
Yoni Avatar answered Oct 27 '22 13:10

Yoni