Here is a snippet from Java library:
public final boolean compareAndExchangeAcquire(boolean expectedValue, boolean newValue) {
return (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0)) != 0;
}
It is from AtomicBoolean class. How can a cast to int return a boolean?
My main question: What is the difference between compareAndExchange vs compareAndExchangeAcquire?
In layman terms: statements written prior to xxxAcquire and after xxxRelease is free to reorder while applying xxx.
The last part of the code you posted is != 0. With clarifying variable:
int a = (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0));
return a != 0;
Of course the != operator returns a boolean.
As for the second part of the question:
Also, what is the difference between compareAndExchange vs compareAndExchangeAcquire?
Firstly some required reading: https://stackoverflow.com/a/16181675/3424746
From the above answer you should understand that compilers/processors can reorder loads/stores, and the restrictions that acquires and releases place on those. Compare and exchange is most likely implemented with a CAS instruction, which can be viewed as a load+store. compareAndExchangeAcquire and compareAndExchangeRelease add the release/acquire semantics to the CAS/load+stores in question. In other words you can use these to prevent certain reorderings, or allow certain reorderings.
Related
This question already has answers here:
"Comparison method violates its general contract!"
(13 answers)
Closed 1 year ago.
I have defined a Comparator using the ordering wrapper. Could you explain why does this code throw an exception, "Comparison method violates its general contract!"? I would really appreciate it if you could tell me how to fix it.
Ordering<Foo> order = new Ordering<Foo>() {
#Override
public int compare(Foo left, Foo right) {
return getCompare(orderMap, left.getItemId(), right.getItemId());
}
};
Collections.sort(Foos, order);
getCompare :
private int getCompare(Map<Long, Integer> orderMap, Long leftId, Long rightId) {
int indexLeft = orderMap.get(leftId) == null ? -1 : orderMap.get(leftId);
int indexRight = orderMap.get(leftId) == null ? -1 : orderMap.get(rightId);
if (indexLeft < 0 || indexRight < 0) {
return 1;
}
return Integer.compare(indexLeft, indexRight);
}
This is the contract:
If `a.compare(b) is X, and b.compare(c) is X, then a.compare(c) must also be X, whether X is negative, or positive, or zero.
If a.compare(b) is X, then b.compare(a) must be -X: 0 remains 0, -1 turns to +1, etc.
a.compare(a) must be 0.
That's it. Your compare method breaks this in many, many ways. For example, your second line has a bug in it(surely that'd be orderMap.get(rightId) == null, you can clean that up using getOrDefault instead), if either index is not found or less than 0, your code always returns 1, which breaks the rule (a.compare(b), where a is not in the map, returns 1, and b.compare(a) would also return 1. It needs to return a negative number instead).
You're going to have to come up with a rule for what happens if one of these is not in the map. If your code is written with the assumption it can't happen, well, it is - throw an exception when your assumption doesn't hold so you can investigate why your assumption (that all provided left/rightIds are always in the map and always non-negative). As written, your code straight up asplodes in a nasty way if that happens - that's what exceptions are for. Explode in an easily debuggable way.
If that was the intent, you're going to have to make up some rules. For example: If a is in the map but b is not, then a is always higher than b. That means if (indexLeft < 0 && indexRight >= 0) return -1 and also if (indexLeft >= 0 && indexRight < 0) return +1;, in order to stick to the rules. That leaves the question: What if neither is in. You can either choose that there is then no way to order them (Return 0), but do know that means you can't put more than once such item in a TreeMap or TreeSet - but sorting a list, that's fine. Individually not-comparables are allowed, and they'll end up clumped together in an arbitrary order. That doesn't break the rules.
In logic expressions remaining part would be skipped if it is unnecessary
boolean b = false && checkSomething( something)
//checkSomething() doesn't get called
What is a good way to achieve the same with arithmetic expressions ?
int i = 0 * calculateSomethig ( something )
It is possible to add ifs before * . But is there a more elegant way to solve this problem? Without of adding much stuff into expression, so that expression itself would look as close to original as possible
Why i do not want to use ifs?
from
return calculateA() * calculateB()
it'll become bulky and unclear
int result
int a = calculateA();
if (a!=0) {
result = a*calculateB()
}else{
result = 0
}
return result
8 lines of code instead of 1,
those expressions might be more complex than a*b
those expressions represent business logic so i want to keep them
clear and easily readable
there might be whole bunch of them
Why do i bother with this at all?
Because calculation methods might be expensive
uses values form other places, where searches and sorts are happening
lots of those expressions can be executed at once ( after user event and user should see result "instantly"
P( *0 in expression ) >0.5
&& and || are called short-circuit operators because they don't evaluate if the JVM will find the value of the whole expression without evaluating the whole expression. For example, the JVM does not have to evaluate the second part of the following expression to tell it evaluates to true:
6 == (2 + 4) || 8 == 9
The JVM does not have to evaluate all of the following expression either to tell it evaluates to false:
9 == 8 && 7 == 7
The multiplication operator (*) is not a short-circuit operator. And so, it does not behave that way. You can do this as you mentioned using if statements. There is no predefined way to do this.
You can create a structure that uses lambdas to evaluate its arguments lazily:
class LazyMul implements IntSupplier {
private final IntSupplier [] args;
private LazyMul(IntSupplier[] args) {
//argument checking omitted for brevity :)
this.args = args;
}
public static LazyMul of(IntSupplier ... args) {
return new LazyMul(args);
}
#Override
public int getAsInt() {
int res = 1;
for (IntSupplier arg: args) {
res *= arg.getAsInt();
if (res == 0)
break;
}
return res;
}
}
Of course this is even longer but using it is as simple as LazyMul.of(this::calculateA, this::calculateB), so if you use it several times, it's better than having an if every time around.
Unfortunately with complicated (particularly nested) expressions readability suffers, but these are the limitations of Java as a language.
Which is better in terms of best practice / efficiency?
if (x == 1
&& y == 1
&& z == 1)
{ do things }
or
if (x != 1 ||
y != 1 ||
z != 1)
{ don't do things and go to a different bit of logic.}
Is there any difference in efficiency when short circuiting ANDs and ORs? Is it (generally) better to check positively or negatively when multiple logical assertions need to be made?
For pure optimization of the code it depends case-by-case. The scenario that will on average do the least amount of comparisons.
For code design it is also case-by-case. The if-cases should match what you are actually looking for. A function that tests if a string is inputted correctly for example. (the tests are made up)
public boolean isValidString (string s) {
if (s.isEmpty())
return false;
if (s.length() < 12)
return false;
if (s...)
return false
return true;
}
In this case the most logical approach is the ||. It could be written.
public boolean isValidString (string s) {
if (s.isEmpty() || s.length() < 12 || s...)
return false;
return true;
}
With http://en.wikipedia.org/wiki/De_Morgan%27s_laws this could be rewritten to not and. However it is not what we want to test, even though they yield the same result.
So stick to the logical approach in general cases.
If you think about efficiency then think about how often each case will occur. The most likely one should be put in front so the whole expression is shortcircuited immediately.
Better you use "==" instead of going for "!=".
This is also recommended with PMD.
The following is good and improves redability.
If(true){
//
}else{
//
}
than
If(!true){
//
}else{
//
}
Well, in some JVM implementations boolean values are stored as integers in the JVM. int value 1 meaning true and int value 0 meaning false. Also, comparison logic at processor level is architecture dependent. Some machines might subtract 2 operands, then add and then compare, others might compare byte by byte etc.. So, unless you are looking at a specific hardware architecture (which you shouldn't.. atleast for java programming language), I don't think this matters much..
I'm wondering if there's a way to convert a boolean to an int without using if statements (as not to break the pipeline). For example, I could write
int boolToInt( boolean b ){
if ( b )
return 1
return 0
But I'm wondering if there's a way to do it without the if statement, like Python's
bool = True
num = 1 * ( bool )
I also figure you could do
boolean bool = True;
int myint = Boolean.valueOf( bool ).compareTo( false );
This creates an extra object, though, so it's really wasteful and I found it to be even slower than the if-statement way (which isn't necessarily inefficient, just has the one weakness).
You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.
If you check the compiled code of that method (by the way, using return b ? 1 : 0; compiles to the exact same instructions), you will see that it does not use a jump:
0x0000000002672580: sub $0x18,%rsp
0x0000000002672587: mov %rbp,0x10(%rsp) ;*synchronization entry
0x000000000267258c: mov %edx,%eax
0x000000000267258e: add $0x10,%rsp
0x0000000002672592: pop %rbp
0x0000000002672593: test %eax,-0x2542599(%rip) # 0x0000000000130000
; {poll_return}
0x00000000025b2599: retq
Note: this is on hotspot server 7 - you might get different results on a different VM.
Use the ?: operator: ( b ? 1 : 0 )
You can use the ternary operator:
return b ? 1 : 0;
If this is considered an "if", and given this is a "puzzle", you could use a map like this:
return new HashMap<Boolean, Integer>() {{
put(true, 1);
put(false, 0);
}}.get(b);
Although theoretically the implementation of HashMap doesn't need to use an if, it actually does. Nevertheless, the "if" is not in your code.
Of course to improve performance, you would:
private static Map<Boolean, Integer> map = new HashMap<Boolean, Integer>() {{
put(true, 1);
put(false, 0);
}};
Then in the method:
return map.get(b);
Otherwise, you could use the Apache Commons BooleanUtils.toInteger method which works like a charm...
// Converts a boolean to an int specifying the conversion values.
static int toInteger(boolean bool, int trueValue, int falseValue)
// Converts a Boolean to an int specifying the conversion values.
static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue)
I found a solution by framework. Use compare for Boolean.
// b = Your boolean result
// v will be 1 if b equals true, otherwise 0
int v = Boolean.compare(b, false);
This is not directly possible, not in Java anyway. You could consider directly using an int or byte instead of a boolean if you really need to avoid the branch.
It's also possible that the VM is smart enough to eliminate the branch (the if or ?:) itself in this case, as the boolean's internal representation is quite likely to be the literal 1 or 0 anyway. Here is an article on how to examine the generated native machine code for the Oracle JDK, and if you need speed, make sure you're using the "server" JVM as it performs more aggressive optimization than the "client" one.
I can't say I recommend this. It's both slower than the ternary operator by itself, and it's too clever to be called good programming, but there's this:
-Boolean.FALSE.compareTo(value)
It uses the ternary under the covers (a couple of method calls later), but it's not in your code. To be fair, I would be willing to bet that there's a branch somewhere in the Python execution as well (though I probably only bet a nickel ;) ).
Since you want no if / else solution your expression is perfect, though I would slightly change it
int myint = Boolean.valueOf( bool ).compareTo( Boolean.FALSE );
There is no object creation involved, Boolean.valueOf(boolean b) returns either Boolean.TRUE or Boolean.FALSE, see API
A reasonable alternative to ising to the ternary to avoid an "if":
private static Boolean[] array = {false, true};
int boolToInt( boolean b ){
return Arrays.binarySearch(array, b);
}
Note that I consider this s "puzzle" question, so if coding it myself i would use the ternary..
You can try using ternary operator like this
int value = flag ? 1 : 0;
Nowadays, jdk has delivered a useful Utils method: BooleanUtils.toInteger()
In the source code, the method that jdk realize it must be efficient:
public static int toInteger(boolean bool) {
return bool ? 1 : 0;
}
So, I think the most votes answer is very great, return bool ? 1 : 0 is the best practice.
Example Code to use BooleanUtils as followed:
BooleanUtils.toInteger(false);
int ansInt = givenBoolean ? 1 : 0;
I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.
It's basically a one liner for this:
if (myVar) {
myVar = false;
} else {
myVar = true;
}
It's something like this, but don't know what it's called or the correct syntax of it:
myVar = myVar : false ? true;
How about
myVar = !myVar
?
myVar = myVar ? false : true; is using the conditional operator.
You can just do this though
myVar = !myVar;
Another option is XOR:
myVar ^= true;
It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.
What you are thinking of is the conditional operator:
myVar = myVvar ? false : true;
(As you see, a lot of people call this "the ternary operator", but that only means that it is an operator with three operands. As it happens, there is only one operator with three operands in this language, but it still says nothing about what the operator does.)
It's of course easier to use the negation operator:
myVar = !myVar;
The smallest code I can think of at the moment. I don't know what its called (if it has a name, as you seem to suggest)
myVar = !myVar
What you're talking about is the "ternary" or "conditional" operator, which does an inline substitution as per a condition.
The syntax is:
condition ? trueValue : falseValue
I usually throw parentheses around my condition, sometimes around the whole conditional operator. Depends on how much I'm trying to delineate it from everything else.
So for example, suppose you want to return the larger of two numbers:
public int max(int a, int b)
{
return (a > b) ? a : b;
}
Notice that it can be substituted into the middle of something else.
Okay, now let's tackle your actual question about toggling a boolean type.
myVar = (myVar) ? false : true;
is how you would do it with the conditional operator. (Again, parentheses aren't required, I just favor them.)
But there's a simpler way to toggle the boolean... using the logical NOT ("!") operator:
myVar = !myVar;
Keep it simple. :-)
if(myVar == true)
{
myVar = false;
}
else if (myVar == false)
{
myVar = true;
}
else
{
myVar = FILE_NOT_FOUND
}
This also works :P
v=v?!v:!v;
There is a ternary operator (wikipedia). Which allows you to write a condensed if-else statement like in the second example.
In java:
myVar = (myVar) ? true : false;
There is also the NOT operator, which toggles a boolean variable. In java that is !. I believe that is what you want.
myVar = !myVar;
public boolean toggle(boolean bool)
{
return !bool;
}
I recently (on my own) found a similar answer to one already stated here. However, the simplest and shortest (non-repeating variable name with least code) answer is:
formControl.disabled ^= 1;
This works best in JavaScript when wanting to toggle boolean, DOM-based attributes (for example, a form control/input's disabled property -- going from a non-editable to edit state). After much searching (with no result that I liked) and some trial and error, I found my solution to be the simplest (however, true instead of a 1 would be clearer -- as was previously posted).
Since this syntax isn't very clear, immediately, I would not advise using it very often (I believe it is appropriate when the variable or property makes the context obvious). I have posted this response (instead of making it a comment) because the context in which the XOR bitwise self-assignment should be used is very important. This "trick" should mostly be avoided when considering best practices.
As others have noted, there are two ways to negate something: "lvalue = !lvalue;" and "lvalue ^= 1;". It's important to recognize the differences.
Saying "lvalue = !lvalue" will cause lvalue to be set to 1 if it was zero, and 0 if it was set to anything else. The lvalue will be evaluated twice; this is not a factor for simple variables, but saying "someArray[index1][index2][index3][index4] = !someArray[index1][index2][index3][index4]" could slow things down.
Saying "lvalue ^= 1;" will cause lvalue to be set to 1 if it was 0, 0 if it was 1, and something else if it was neither zero nor 1. The lvalue need only be specified or evaluated once, and if the value is known to be either zero or 1, this form is likely to be faster.
Too bad there's no auto-negate operator; there are times such a thing would be handy.
You can also use the binary form of negation as shown here.
if ((v == true) && !(v = false)) {
v != true; /* negate with true if true. */
} else {
v =! false; /* negate with false if false. */
}