Greater-than compare-and-swap - java

As the title suggests, I'm looking for a compare-and-swap implementation, but with greater-than comparison:
if(newValue > oldValue) {
oldValue = newValue;
}
where oldValue is some global shared state and newValue is private to each thread, without doing this:
synchronized(locker) {
if(newValue > oldValue) {
oldValue = newValue;
}
}
because I want a non-blocking solution. From studying source codes of other non-blocking operations, I've come up with this (assuming the values are integers):
AtomicInteger oldValue; // shared global variable
...
public boolean GreaterThanCAS(int newValue) {
while(true) {
int local = oldValue;
if(local == oldValue) {
if(newValue > local) {
if(oldValue.compareAndSet(local, newValue) {
return true; // swap successful
} // else keep looping
} else {
return false; // swap failed
}
} // else keep looping
}
}
when // else keep looping happens, it means that another thread has changed the oldValue in the meantime and so I need to loop and try again.
Is this implementation correct (thread-safe)?

Since Java 8 this can be simplified with use of updateAndGet:
public boolean greaterThanCAS(int newValue) {
return oldValue.updateAndGet(x -> x < newValue ? newValue : x) == newValue;
}
Note that this would return true also in case when old and new values are equal.
Give a try to #Adam's answer if this is not desired behaviour.

I see no problems with your implementation, provided that no thread ever decreases the value of the AtomicInteger. If they do, your code is open to race conditions.
Note that the code can be simplified as follows:
public boolean GreaterThanCAS(int newValue) {
while(true) {
int local = oldValue.get();
if(newValue <= local) {
return false; // swap failed
}
if(oldValue.compareAndSet(local, newValue)) {
return true; // swap successful
}
// keep trying
}
}

I would re write it to look more like:
while(true) {
int local = oldValue.get();
if(newValue > local){
if(oldValue.compareAndSwap(local, newValue) {
return true; // swap successful
} // else keep looping
}else
return false;
}
The equivalence check before the greater than check is redundant.
Otherwise it should work fine.

#Vadzim, I would have commented on your post, but stackoverflow says I don't have enough points to post comments. Your answer is almost correct, but your function will always return false because getAndUpdate always returns the previous value, or 'x' in your case. I think all you would need to do is replace your last '==' with '<', e.g.:
// return true if the assignment was made, false otherwise
public boolean greaterThanCAS(int newValue) {
return oldValue.getAndUpdate(x -> x < newValue ? newValue : x) < newValue;
}

Related

Java 8 compute() and computeIfPresent() to check an existing value

I have this piece of code :
if (notificationSend.get(key) != null && notificationSend.get(key).equals(value)) {
return true;
} else {
notificationSend.put(key, value);
return false;
}
and I want to know if it is possible to refactor it using Jav8 Enhancements like compute() , computeIfPresent() or computeIfAbsent()
Assuming value is non-null, you don't need to use a conditional, or any of those compute* methods.
ValueType oldValue = map.put(key, value);
return value.equals(oldValue);

Reducing conditional operators efficiently

What I am trying to perform: I am trying to reduce the conditional operators, Since Sonar is giving a error for it
if (!parseBooleanFromString(response.getBuy().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getSell().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getExchange().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeInvestments())))))) {
//Success
} else {
//Failure
}
private boolean parseBooleanFromString(String mStr) {
return Boolean.parseBoolean(mStr);
}
What i have tried:
I am trying to put all the boolean values in a list and check
Is that the best way to do or is there a more efficient way
You can also move these conditions into different functions which internally calls other functions and returns single boolean result. This way there will only one function in above if condition which will internally evaluate and returns result.
Since you're checking if each statement is false, how about you keep a global integer in memory: private int product = 1;. Make a separate method where you calculate the product (replaces the string to boolean parser):
private void updateProduct(String mStr){
if (Boolean.parseBoolean(mStr)) //If true, condition should fail
product *= 0;
else
product *= 1;
}
In essence, you are not running 'if statement' but multiplying the boolean:
product = 1;
updateProduct(response.getBuy().getHasEligibleAccounts());
updateProduct(response.getSell().getHasEligibleAccounts());
//etc
if (product > 0){
//success
} else {
//failure
}
Explanation: If at any point a condition was true, the product will always be 0. The only instance where the product is > 0 is when all statements were false
Not sure what sonar complains about, but you have alot of redundant parenthesis and confusing negations. Using DeMorgans law, you can at least simplify to:
boolean b = parseBooleanFromString(response.getBuy().getHasEligibleAccounts())
|| parseBooleanFromString(response.getSell().getHasEligibleAccounts())
|| parseBooleanFromString(response.getExchange().getHasEligibleAccounts())
|| parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions())
|| parseBooleanFromString(
response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions());
if (!b) {
or if you perfer more java 8 syntax
Stream<Boolean> bools = Stream.of(parseBooleanFromString(response.getBuy().getHasEligibleAccounts()),
parseBooleanFromString(response.getSell().getHasEligibleAccounts()),
parseBooleanFromString(response.getExchange().getHasEligibleAccounts()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()));
boolean c = ! bools.anyMatch(e -> e);
if (!c) {
I would do something like this:
private boolean checkEligibility(LaunchPoints response) {
final String trueStr = "true";
if (trueStr.equals(response.getBuy().getHasEligibleAccounts())) return true;
if (trueStr.equals(response.getSell().getHasEligibleAccounts())) return true;
[...]
return false;
}
The idea is, skip the parsing boolean, just check for "true" and make your conditions more readable.

Loss of information during a for loop

I have a problem with this method:
private boolean reflectionEqualsSet(Object left, Object right) {
Set leftSet = (Set) left;
Set rightSet = (Set) right;
if (leftSet == null) {
// POF tricks: if set to serialize is null, the deserialized set is empty
return rightSet != null && rightSet.size() == 0;
}
// check size
if (leftSet.size() != leftSet.size()) {
return false;
}
// check values
for (Object currLeft : leftSet) {
boolean found = false;
for (Object currRight : rightSet) {
if (isEqual(currLeft, currRight)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
The problem is:
I have an object with three random filled values in leftSet (2 UUID's and 1 Integer).
The values I have in my leftSet change completely in the for loop. While debugging I've found out that in the first iteration currSet already has completely different values and I can't figure out why.
In the inner loop with currRight this doesn't happen.
I've been debugging for hours and I've found the problem is in that line does anyone have an idea of why the values change? (Not the order, the values).
I know this isn't much information about the problem but that's all I can tell, I don't know how to explain it any better, sorry.
Thanks
First, your size check is off
// check size
// if (leftSet.size() != leftSet.size()) {
if (leftSet.size() != rightSet.size()) {
return false;
}
Next, I don't trust your isEqual method - please Override Object.equals(Object),
// if (isEqual(currLeft, currRight)) {
if (currLeft.equals(currRight)) {
return true; // <-- and just short-circuit with return true!
}
Obviously return false; after your for loop, and you can eliminate found.

how to use return keyword in a find operation in binary search tree

This is my method to find if a particular node is there in a binary tree.Here's my method and it works fine.
public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
return find(p.left,x);
}
else {
return find(p.right,x);
}
}
}
My question is if I don't insert return keyword inside else if(x<p.element){ and else { I get an error as missing return statement.
Say I have a binary tree consisting of elements 5,4,6,60,25,10 .
So if i am searching for 10 there's a time that
if(x==p.element){
return true;
is satisfied because of recursive calls.Then there's a return statement to be found.
If i am searching for an element that's not in tree eventually I would reach the statement
if(p==null){
return false ;
},there we find a return statement.
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?So what's wrong with not having return keyword in else if and else clauses.
Why do I have to have it there?
Why can't I do it as
`public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
find(p.left,x);
}
else {
find(p.right,x);
}
}
}`
The closest to the way you want your if-else if-else clause to behave is using the ? conditional expression:
public boolean find(BinaryNode p,int x)
{
if(p==null) {
return false ;
}
else {
return (x==p.element)?true:(x<p.element?find(p.left,x):find(p.right,x));
}
}
Other option is to store the value to be returned in a local variable and only return it at the end of your method:
public boolean find(BinaryNode p,int x)
{
boolean returnValue = false;
if(p!=null)
{
if(x==p.element){
returnValue = true;
}
else if(x<p.element){
returnValue = find(p.left,x);
}
else {
returnValue = find(p.right,x);
}
}
return returnValue;
}
And my favorite way, using short-circuit evaluation of logical expressions:
public boolean find(BinaryNode p,int x)
{
if(p==null) return false;
return x==p.element || (x<p.element && find(p.left,x)) || find(p.right,x);
}
Since Java's || and && operators won't evaluate their right part expression when the left part already determines their result. If x==p.element is true, then true will be returned without evaluation the rest of the line. If not, then (x<p.element && find(p.left,x)) will be evaluated following the same rule.
Note how find(p.left,x) won't be evaluated when x<p.element is false.
You need return statement because the find-function in the else if - else statement will return to the caller after its done, but the first-call function still have to return a value to the caller
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?
No compiler doesn't know about it. Compiler doesn't know what will be value of x and p at run-time.
Compiler simply checks for all the possibilities of the return statement and there must be exit point of the method.
You need to provide the logic to move either in right direction or left direction of the binary tree.
The last two else-if are not responsible to actually return the result of the find method its used just to move in the right direction of the tree. Ultimately final result of the the find method will come out by first two if-else clause.

How to get Boolean value from Object

I tried different ways to fix this, but I am not able to fix it. I am trying to get the Boolean value of an Object passed inside this method of a checkBox:
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String key = preference.getKey();
referenceKey=key;
Boolean changedValue=!(((Boolean)newValue).booleanValue()); //ClassCastException occurs here
}
I get:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
Instead of casting it, you can do something like
Boolean.parseBoolean(string);
Here's some of the source code for the Boolean class in java.
// Boolean Constructor for String types.
public Boolean(String s) {
this(toBoolean(s));
}
// parser.
public static boolean parseBoolean(String s) {
return toBoolean(s);
}
// ...
// Here's the source for toBoolean.
// ...
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
So as you can see, you need to pass a string with the value of "true" in order for the boolean value to be true. Otherwise it's false.
assert new Boolean( "ok" ) == false;
assert new Boolean( "True" ) == true;
assert new Boolean( "false" ) == false;
assert Boolean.parseBoolean( "ok" ) == false;
assert Boolean.parseBoolean( "True" ) == true;
assert Boolean.parseBoolean( "false" ) == false;
From the code you posted, and the result you are seeing, it doesn't look like newValue is a boolean. So you try to cast to a Boolean, but it's not one, so the error occurs.
It's not clear what you're trying to do. Ideally you'd make newValue a boolean. If you can't do that, this should work:
boolean newValue;
if (newValue instanceof Boolean) {
changedValue = newValue; // autoboxing handles this for you
} else if (newValue instanceof String) {
changedValue = Boolean.parseBoolean(newValue);
} else {
// handle other object types here, in a similar fashion to above
}
Note that this solution isn't really ideal, and is somewhat fragile. In some instances that is OK, but it is probably better to re-evaluate the inputs to your method to make them a little cleaner. If you can't, then the code above will work. It's really something only you can decide in the context of your solution.
If you know that your Preference is a CheckBoxPreference, then you can call isChecked(). It returns a boolean, not a Boolean, but that's probably close enough.
Here is some code from the APIDemos Device Administration sample (DeviceAdminSample.java).
private CheckBoxPreference mDisableCameraCheckbox;
public void onResume() {
...
mDPM.setCameraDisabled(mDeviceAdminSample, mDisableCameraCheckbox.isChecked());
...
}
public boolean onPreferenceChange(Preference preference, Object newValue) {
...
boolean value = (Boolean) newValue;
...
else if (preference == mDisableCameraCheckbox) {
mDPM.setCameraDisabled(mDeviceAdminSample, value);
reloadSummaries();
}
return true;
}

Categories