this class can be used in multi thread because it is thread-safe.
public class Hello {
private int value = 0;
public synchronized int get() {
return value;
}
public synchronized void set(int value) {
this.value = value;
}
}
i know that the reason that we must use synchronized when get() ,besides set() is memory visibility.
and java volatile keyword can be used for memory visibility.
so then.. this class is also thread-safe??
public class Hello {
private volatile int value = 0;
public int get() {
return value;
}
public synchronized void set(int value) {
this.value = value;
}
}
In your specific example, you don't need that extra synchronized. Given that you have already mentioned memory visibility (aka happens-before), I won't go deeper to explain this.
However, it does not apply generally. There are several assumptions in your example making it enough to simply use volatile
Type of value
Although you are simply doing a simple retrieval/assignment of value, it is not always guaranteed to be atomic for all data type. Iirc, Java only guarantee that such operation is atomic for int and types smaller that int. Which means, for example, if value is of type long, even you have declared it with volatile, you may still corrupt value with your above example
Operations on value
Ok, let's assume it is an int. In your example, you are simply getting and assigning an int for which the operation is atomic, hence simply using volatile is enough. However if you have another method doing something like value++, using volatile is not sufficient. In such case, you may either consider using Atomic* or use synchronized
Update: I later found that JLS https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7 mentioned that using volatile would enforce atomic read/write on double/long. So my original point 1 was actually wrong
In your example, there's no need to use synchronized in neither the get() nor the set method, given the value attribute is declared with the volatile keyword.
This is because the volatile keyword forces a happens-before relation between writer and reader threads.
Java Language Specification, Section 8.3.1.4. volatile fields:
The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.
The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.
A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).
So, in your case, there's no need to synchronize the get() and set() methods.
In your class Hello there is only one field int value. Synchronized locks whole object and thus heavy operation, Instead you can use AtomicInteger. Since Atomic* variables are faster. Volatile just satisfies "happens before" you cannot achieve atomicity for operations like "check then act" with volatiles.
To make Hello class thread-safe, the best way
import java.util.concurrent.atomic.AtomicInteger;
public class Hello {
private AtomicInteger value;
public int get() {
return this.value.get();
}
public synchronized void set(int value) {
this.value.set(value);
}
}
As mentioned in this post
If some object has only one field or its critical updates are
limited to only one field of object so instead of using
synchronization or other thread safe collections , Atomic variables
(AtlomicInteger, AtomicReference etc.) can be utilized.
Related
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?
In properly synchronized code, the final isn't needed.
E.g. if you would use:
class MyCounter{
private AtomicInteger c = new AtomicInteger();
public int inc(){return c.incrementAndGet();}
public int get(){return c.get();}
}
And you would share the MyCounter-instance with another thread, you need to make sure that there is a happens-before edge between writing c and reading c. This can be done in various ways e.g. you pass the MyCounter-instance to the constructor of some thread (thread start rule). Or you pass it through a volatile field (volatile variable rule) or a synchronized block (monitor lock rule).
This is typically called 'safe publication' and for a correctly synchronized system, this is all you need. If you don't pass the reference safely, you have a data race and weird problems can happen like seeing a partially constructed object. Therefore there is a second mechanism called initialization safety; so no matter if the reference to an object isn't published safely, initialization safety using final will act as a backup solution. The primary use-case for this AFAIK is security.
So for correctly synchronized code, there is no need for final.
That doesn't mean that you should not add finals. It has all kinds of benefits like no accidental changes and it is pretty informative. So I prefer to make as many fields final as possible.
Final has no meaning for method arguments from a memory model perspective, since they are private to a thread. Only shared memory needs to be dealt with in a memory model. Making arguments of a method final is a flavor issue. Some people want it, others don't. I'm not crazy about long method signatures and tend not to add them unless I'm writing some difficult code. But I would be fine if local variables and formal arguments would be final by default (like Rust).
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() ;
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.
Ex. https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/util/concurrent/atomic/AtomicInteger.java
For the following simplified class:
public class MutableInteger {
private int value;
public MutableInteger(int initial) {
synchronized(this) { // is this necessary for memory visibility?
this.value = initial;
}
}
public synchronized int get() {
return this.value;
}
public synchronized void increment() {
this.value++;
}
...
}
I guess the general question is for mutable variables guarded by synchronization is it necessary to synchronize when setting the initial value in the constructor?
You're right, without the synchronized block in the constructor there is no visibility guarantee for non-final fields, as can be seen in this example.
However in practice I would rather use volatile fields or the Atomic* classes in situations like this.
Update: It is also important to mention here that in order for your program to be correctly synchronized (as defined by the JLS), you will need to publish the reference to your object in a safe manner. The cited example doesn't do that, hence why you may see the wrong value in non-final fields. But if you publish the object reference correctly (i.e. by assigning it to a final field of another object, or by creating it before calling Thread.start()), it is guaranteed that your object will be seen at least as up-to-date as the time of publishing, therefore making the synchronized block in the constructor unnecessary.
Though you've accepted an answer, let me add my two cents.
Based on what I've read, synchronization or making the field volatile would not grantee the following visibility.
A thread T1 may see a not-null value for this, but unless you've made the field value final, there's a good chance of thread T1 seeing the default value of value.
The value could be a volatile or been accessed within synchronized blocks (monitor acquire and release), either way provided that the correct execution order was followed, there's happens-before edge from the write to the read of value. There's no argument on that.
But it's not the happens before edge that we have to consider here, but the correct publication of the object itself(MutableInteger).
Creating an object is twofold where the JVM first allocates a heap space and then start initializing fields. A thread may see a not-null reference of an object but an uninitialized field of that as long as the said field is not final (Assuming reference has been correctly published).
I have a class with a global variable, Integer clock, initialized to 0. It passes 'clock' to a few thread constructors, starting the threads also. It seems increments to 'clock' can be seen within the thread, but in their calling process, 'clock' is always 0. Because Integer is an object and objects are passed by reference, I would expect changes to 'clock' to be seen everywhere. Is this not the case?
Use an AtomicInteger instead of an Integer.
An int value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
Integer is an immutable object so you cannot change its value from another thread. And since it must be declared final when you use it in the thread you cannot reassign the variable.
A way around this is to create a wrapper for Integer that is mutable
class MutableInteger {
private int integer;
synchronized void setInteger(int integer) { ... }
synchronized int getInteger() { ... }
}
Suppose I have a Utility class,
public class Utility {
private Utility() {} //Don't worry, just doing this as guarantee.
public static int stringToInt(String s) {
return Integer.parseInt(s);
}
};
Now, suppose, in a multithreaded application, a thread calls, Utility.stringToInt() method and while the operation enters the method call, another thread calls the same method passing a different s.
What happens in this case? Does Java lock a static method?
There is no issue here. Each thread will use its own stack so there is no point of collision among different s. And Integer.parseInt() is thread safe as it only uses local variables.
Java does not lock a static method, unless you add the keyword synchronized.
Note that when you lock a static method, you grab the Mutex of the Class object the method is implemented under, so synchronizing on a static method will prevent other threads from entering any of the other "synchronized" static methods.
Now, in your example, you don't need to synchronize in this particular case. That is because parameters are passed by copy; so, multiple calls to the static method will result in multiple copies of the parameters, each in their own stack frame. Likewise, simultaneous calls to Integer.parseInt(s) will each create their own stack frame, with copies of s's value passed into the separate stack frames.
Now if Integer.parseInt(...) was implemented in a very bad way (it used static non-final members during a parseInt's execution; then there would be a large cause for concern. Fortunately, the implementers of the Java libraries are better programmers than that.
In the example you gave, there is no shared data between threads AND there is no data which is modified. (You would have to have both for there to be a threading issue)
You can write
public enum Utility {
; // no instances
public synchronized static int stringToInt(String s) {
// does something which needs to be synchronised.
}
}
this is effectively the same as
public enum Utility {
; // no instances
public static int stringToInt(String s) {
synchronized(Utility.class) {
// does something which needs to be synchronised.
}
}
}
however, it won't mark the method as synchronized for you and you don't need synchronisation unless you are accessing shared data which can be modified.
It should not unless specified explicitly. Further in this case, there wont be any thread safety issue since "s" is immutable and also local to the method.
You dont need synchronization here as the variable s is local.
You need to worry only if multiple threads share resources, for e.g. if s was static field, then you have to think about multi-threading.
In what cases is it necessary to synchronize access to instance members?
I understand that access to static members of a class always needs to be synchronized- because they are shared across all object instances of the class.
My question is when would I be incorrect if I do not synchronize instance members?
for example if my class is
public class MyClass {
private int instanceVar = 0;
public setInstanceVar()
{
instanceVar++;
}
public getInstanceVar()
{
return instanceVar;
}
}
in what cases (of usage of the class MyClass) would I need to have methods:
public synchronized setInstanceVar() and
public synchronized getInstanceVar() ?
Thanks in advance for your answers.
The synchronized modifier is really a bad idea and should be avoided at all costs. I think it is commendable that Sun tried to make locking a little easier to acheive, but synchronized just causes more trouble than it is worth.
The issue is that a synchronized method is actually just syntax sugar for getting the lock on this and holding it for the duration of the method. Thus, public synchronized void setInstanceVar() would be equivalent to something like this:
public void setInstanceVar() {
synchronized(this) {
instanceVar++;
}
}
This is bad for two reasons:
All synchronized methods within the same class use the exact same lock, which reduces throughput
Anyone can get access to the lock, including members of other classes.
There is nothing to prevent me from doing something like this in another class:
MyClass c = new MyClass();
synchronized(c) {
...
}
Within that synchronized block, I am holding the lock which is required by all synchronized methods within MyClass. This further reduces throughput and dramatically increases the chances of a deadlock.
A better approach is to have a dedicated lock object and to use the synchronized(...) block directly:
public class MyClass {
private int instanceVar;
private final Object lock = new Object(); // must be final!
public void setInstanceVar() {
synchronized(lock) {
instanceVar++;
}
}
}
Alternatively, you can use the java.util.concurrent.Lock interface and the java.util.concurrent.locks.ReentrantLock implementation to achieve basically the same result (in fact, it is the same on Java 6).
It depends on whether you want your class to be thread-safe. Most classes shouldn't be thread-safe (for simplicity) in which case you don't need synchronization. If you need it to be thread-safe, you should synchronize access or make the variable volatile. (It avoids other threads getting "stale" data.)
If you want to make this class thread safe I would declare instanceVar as volatile to make sure you get always the most updated value from memory and also I would make the setInstanceVar() synchronized because in the JVM an increment is not an atomic operation.
private volatile int instanceVar =0;
public synchronized setInstanceVar() { instanceVar++;
}
. Roughly, the answer is "it depends". Synchronizing your setter and getter here would only have the intended purpose of guaranteeing that multiple threads couldn't read variables between each others increment operations:
synchronized increment()
{
i++
}
synchronized get()
{
return i;
}
but that wouldn't really even work here, because to insure that your caller thread got the same value it incremented, you'd have to guarantee that you're atomically incrementing and then retrieving, which you're not doing here - i.e you'd have to do something like
synchronized int {
increment
return get()
}
Basically, synchronization is usefull for defining which operations need to be guaranteed to run threadsafe (inotherwords, you can't create a situation where a separate thread undermines your operation and makes your class behave illogically, or undermines what you expect the state of the data to be). It's actually a bigger topic than can be addressed here.
This book Java Concurrency in Practice is excellent, and certainly much more reliable than me.
To simply put it, you use synchronized when you have mutliple threads accessing the same method of the same instance which will change the state of the object/or application.
It is meant as a simple way to prevent race conditions between threads, and really you should only use it when you are planning on having concurrent threads accessing the same instance, such as a global object.
Now when you are reading the state of an instance of a object with concurrent threads, you may want to look into the the java.util.concurrent.locks.ReentrantReadWriteLock -- which in theory allows many threads to read at a time, but only one thread is allowed to write. So in the getter and setting method example that everyone seems to be giving, you could do the following:
public class MyClass{
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private int myValue = 0;
public void setValue(){
rwl.writeLock().lock();
myValue++;
rwl.writeLock().unlock();
}
public int getValue(){
rwl.readLock.lock();
int result = myValue;
rwl.readLock.unlock();
return result;
}
}
In Java, operations on ints are atomic so no, in this case you don't need to synchronize if all you're doing is 1 write and 1 read at a time.
If these were longs or doubles, you do need to synchronize because it's possible for part of the long/double to be updated, then have another thread read, then finally the other part of the long/double updated.