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--;
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With