Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to use synchronized and volatile

I have two threads. The first thread calls the setX method, the second one calls the getX method. Do I have to set the methods synchronized although i have only one writing thread? And can i also solve my thread problem with the second class and the volatile variable?

public class Test {
    private int x;  

    public synchronized  void setX(int x) {
        this.x = x;
    }

    public synchronized  int getX() {
        return this.x;
    }
}

public class Test2 {
    private volatile int x; 

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return this.x;
    }
}
like image 245
Maxii Avatar asked Jan 28 '13 19:01

Maxii


People also ask

Do I need volatile if I use synchronized?

Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables.

Can we use synchronized with variable in Java?

You can have both static synchronized method and nonstatic synchronized method and synchronized blocks in Java but we can not have synchronized variable in java. Using synchronized keyword with a variable is illegal and will result in compilation error.

When should I use volatile in Java?

Yes, volatile must be used whenever you want a mutable variable to be accessed by multiple threads. It is not very common usecase because typically you need to perform more than a single atomic operation (e.g. check the variable state before modifying it), in which case you would use a synchronized block instead.


1 Answers

Rather than use synchronized or volatile here, I'd personally use AtomicInteger:

public class Test {
    private final AtomicInteger x = new AtomicInteger();  

    public void setX(int value) {
        x.set(value);
    }

    public int getX() {
        return x.get();
    }
}

(Note that I've also fixed your get / set - previously your getX was setting, and your setX was getting...)

like image 162
Jon Skeet Avatar answered Sep 23 '22 08:09

Jon Skeet