SilentFlame
SilentFlame

Reputation: 527

Is there a way to implement an if-else condition that is threadsafe/ atomic in java?

Let's take for example:

 public class XYZ{
    private AtomicInteger var1;
    private int const_val;

    // these all attributes are initialized with a constructor, when an instance of the class is called.

    // my focus is on this method, to make this thread-safe
    public boolean isPossible(){
        if(var1 < const_val){
            var1.incrementAndGet();
            return true;
        }
        else{
            return false;
        }
    }
}

How to make this (entire "if-else" snippet) thread-safe/atomic if I cannot use the locking mechanism (in java)?

I read something on the line of AtomicIntegers, and reading something with AtomicBooleans, can I use these to make this snippet thread-safe?

Upvotes: 0

Views: 539

Answers (2)

pveentjer
pveentjer

Reputation: 11392

Something like this should do the trick.

public boolean isPossible(){
    for(;;){
        int current = var1.get();
        if(current>=max){
            return false;
        }
        
        if(var1.compareAndSet(current, current+1)){
            return true;
        }
    }
    
}

Upvotes: 2

MikeFHay
MikeFHay

Reputation: 9043

Instead of enforcing the maximum at writing time, you can increment unconditionally, and enforce the maximum at reading time, like so:

public boolean increment(){
    return var1.getAndIncrement() < const_val;
}

public int getVar1() {
    return Math.min(const_val, var1.get());
}

That's assuming that all you ever do with this variable is increment it. One issue with this solution is it could eventually lead to overflow. If that's a likely concern, you can switch to AtomicLong.

Upvotes: 0

Related Questions