Here is an example method for explaining thread safety:
class Counter {
private int counter = 0;
public void increment() {
counter ;
}
public int getValue() {
return counter;
}
}
In order to provide thread safety, there are several methods and I would prefer using AtomicInteger
approach. However;
1. I am also wondering if I can provide thread safe by using final
for the necessary variable(s). If so, how can I perform this?
2. Is one of the reason using final
commonly in Java for variables and method arguments to provide thread safety?
CodePudding user response:
No, the final
keyword doesn't have anything in common with thread safety.
The final
keyword on variables makes them immutable, you can't change their value anymore.
However, it's not like the const
keyword in c where the whole variable content cannot change. In Java only the reference is immutable.
final AtomicReference<String> toto = new AtomicReference<>("text");
toto.set("new text"); // totally fine
toto = new AtomicReference<>("text"); // does not compile, as toto is immutable reference.
But, there is another keyword that fulfill what you are looking for. It's volatile
. https://www.baeldung.com/java-volatile
In short, the value change on all thread simultaneously and is available immediately.
That's what is used in all the Atomic*
Java classes.
CodePudding user response:
I m just gonna add this with Erwan Daniel's answer .
Your
If you want a counter shared between all your Threads here is another version of your code.
class SharedCounter {
private AtomicInteger sharedCounter ;
public Counter(){
this.sharedCounter = new AtomicInteger(0);
}
public void increment() {
sharedCounter.getAndIncrement();
}
public int value() {
return sharedCounter.get();
}
The final will prevent your atomicInteger12
from changing the object it's using And you can freely set it's value.
final SharedCounter atomicInteger12 = new Counter() ;