0

I have a java class as below:

public class Example implements Runnable {

    private int num;

    ...

    // Getter
    public int getNum(){
        return this.num;
    }

    // Setter    
    public void addToNum(int amount) {

        if (this.amount> 0) {
            this.num += amount;
        }
    }

    ...
}

This class can be instantiated by multiple threads. Each of this instances have its own 'num', that is, I do not want 'num' variable to be shared between all them.

To each instance, multiple threads can be accessed in concurreny in order to read/write 'num' variable. So what is the best option to protect read/write operations on 'num' variable in order to they are atomic operations?

I know that in case on C# it can be done using lock(object) like below link but in java I have no idea (I am new on it):

Atomic operations on C#

8
  • 1
    make setter method addToNum synchronized Commented Feb 10, 2016 at 12:10
  • Are you saying that Example instances will not be shared between threads? Because if that is the case then you're fine and you don't need to add any synchronization or locks. Only if two (or more) threads will access the same Example instance will you need to think about it. Commented Feb 10, 2016 at 12:11
  • 1
    hope you want addToNum() to be accessed by only one thread at a time. y don't you synchronize that method? better approch is to use synchronize block Commented Feb 10, 2016 at 12:12
  • since num is private , you dont need to worry about synchronization Commented Feb 10, 2016 at 12:13
  • Is if (this.num > 0) { correct? For the given code, this.num would never be incremented, so there is no thread safety issue :) Commented Feb 10, 2016 at 12:35

4 Answers 4

4

You can synchronized the methods, but you might find using AtomicInteger a faster option.

private final AtomicInteger num = new AtomicInteger();

...

// Getter
public int getNum(){
    return this.num.get();
}

// Setter    
public void addToNum(int amount) {
    if (amount > 0) {
        this.num.getAndAdd(amount);
    }
}

Both of these methods are lock-less and avoid exposing a lock which could be used in an unintended way.

In Java 8, the getAndAdd uses a single machine code instruction for the addition via the Unsafe class. From AtomicInteger

private volatile int value;

public final int get() {
    return value;
}
public final int getAndAdd(int delta) {
    return unsafe.getAndAddInt(this, valueOffset, delta);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Would AtomicInteger be faster than using plain synchronization?
@TheLostMind it's faster than biased locking. i.e. even when synchronized is only actually used by one thread. This is because it uses a single machine code instruction (In Java 8)
Ah I see. Will remember that.. Thanks.. Can't upvote twice :P
@TheLostMind you can vote for any comments you like ;) I have updated my answer.
1
public synchronized void addToNum(int amount) {

    if (this.num > 0) {
        this.num += amount;
    }
}

here you'll find documentation for it http://www.programcreek.com/2014/02/how-to-make-a-method-thread-safe-in-java/

Comments

0

You can use synchronized , read about it. You can synchronized methods.

Comments

0

In Java ,I doubt about using volatile variables because volatile variables can used only when one thread is writing and other reads are reading. Volatile works only when one thread is writing .

"where one thread (T1) modifies the counter, and another thread (T2) reads the counter (but never modifies it), declaring the counter variable volatile is enough to guarantee visibility for T2 of writes to the counter variable.

If, however, both T1 and T2 were incrementing the counter variable, then declaring the counter variable volatile would not have been enough. More on that later."

Link : http://tutorials.jenkov.com/java-concurrency/volatile.html#:~:text=The%20Java%20volatile%20keyword%20is%20intended%20to%20address%20variable%20visibility,read%20directly%20from%20main%20memory.

1 Comment

There is markup available for denoting a portion of your answer as quoted material. You can edit the answer and either use the quote button on the editor toolbar or precede the paragraph with a > symbol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.