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;
}
}
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.
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.
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.
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...)
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