Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronization on single statement?

if I have a getter method that has only one statement like this

public class NumberClass{
    int number;

    public int getNumber() {
        return number;
    }
    ...
}

and multiple threads access this method, do I have to synchronize this method or it is not necessary since it has only one statement??

like image 576
Dorgham Avatar asked Feb 20 '26 22:02

Dorgham


1 Answers

I have to synchronize this [get] method or it is not necessary since it has only one statement??

It has nothing to do with 1 or more statements. It depends on whether or not the value has been updated in another thread and if you want all of the threads to see a consistent value.

If the number field was updated in thread1, then thread2 may get either the original value or the new value depending on how the update was synchronized. To have the value published appropriately both the set and get methods need to synchronized.

If you are just trying to share an int value then marking the number field as being volatile would work or using an AtomicInteger to share the value between multiple threads reliably may be more appropriate.

private volatile int number;

or use:

private AtomicInteger number = new AtomicInteger();
like image 61
Gray Avatar answered Feb 22 '26 11:02

Gray