If compareAndSet fails, is the code below still executed? - java

I have a very dumb question.
If I use AtomicReferences compareAndSet
this way
original.set(atomic.get());
long next = some new value
atomic.compareAndSet(original.get(), next);
....more code....
is more code still updated if the comparison fails (i.e. atomic has been updated by another thread).
I'm trying to find an error in an assignment and this is the only thing I can think about and I've been trying for few hours.
P.S.
Weirdly enough, if I use synchronize on this code
it gives me the correct answer on my laptop, but not on my desktop

MangatRaiModi and SotiriosDelimanolis put me on the right path.
A simple fix:
original.set(atomic.get());
long next = some new value
while(!atomic.compareAndSet(original.get(), next))
{
do above again
}
....more code....
did it.
Still not sure how synchronized fixed this on my laptop but not on my desktop.
I'm guessing that it's slowing the threads down on the mobile Chip enough so that they can operate sequentially (Like a Print statement).
I'm probably wrong though.

Related

java.awt.Robot.waitForIdle() is unrealiable

We are seeing frequent timing issues in our nightly UI tests. The tests often fail because events performed by the java.awt.Robot have not completed before the test code tries to verifying the results.
We are code like using:
Point p = cb.getLocationOnScreen();
int m = 5;
if (cb.getWidth()<5||cb.getHeight()<5)
m=3;
System.out.println("Click at " + (p.x+m) + "," + (p.y+m));
robot.mouseMove(p.x + m, p.y + m);
robot.mousePress(MouseEvent.BUTTON1_MASK);
robot.mouseRelease(MouseEvent.BUTTON1_MASK);
robot.waitForIdle();
Thread.sleep(100);
// Verify results...
We keep having the bump up the Thread.sleep to ensure things complete on the event thread (things like clicking on a button or typing text) despite the java.awt.Robot.waitForIdle() call.
I found this question (Does java.awt.Robot.waitForIdle() wait for events to be dispatched?) which says to use java.awt.Toolkit.realSync(), but this is not an accessible method and with Java 9 coming, I'd rather not add any unnecessary reflection to our tests.
Are there better solutions? Or do people use realSync() or just increase the wait time until tests pass reliably?
UPDATE
I tried using sun.awt.SunToolkit.realSync(), but it is hanging in some tests and never returning. It looks like the EventThread is painting borders and such.
Looks like my only solution is to bump the sleep time up until the test can actually pass reliably. Yuck.
UPDATE 2
I figured out the first hang I had with realSync(). It was a problem in our code, where some paint code called a get method that called a set method which queued up another paint. Repeat forever.
Fixed our code and realSync() worked for a while, sort of. It still seems to return before it should. No idea why and I have no work around.
Also, I've seen realSync() hang and time out on my Linux box running under Java 1.7, but it works under Java 1.8. Very reliable tool here. /s
So, back the to original question. What is a decent way to tell when UI updates are done?
I came to the conclusion that I did need to use SunToolkit.realSync() and it seems to work correctly for Java 9 as well.
It seems, although I couldn't find any hard evidence, that realSync() waits for all graphics related threads while Robot.waitForIdle() and SwingUntilities.invokeLater() only wait for the Java EventThread to finish it's work.
If someone comes up with a better answer, I'd being will to accept that instead of my answer.

NullPointerException whilst learning concurrency in Scala

I'm having a little problem at the moment. My latest assignment is to create a rock paper scissors program which will run concurrently and output various values. Sounds simple and trivial, I know, but a little fun and I have been allowed to use scala which I had no knowledge of so thought it would be interesting.
Now the error is confusing me. I am receiving a NullPointerException on Thread 10, and have spent an awful long time trying to find it to no success. I have 6 classes so it would be impractical of me to put all of the code in, but I will put a few snippets.
result = Shapes.Winner(player1.getChoice(), player2.getChoice())
This is the line giving the error. Player1 and Player2 are simply objects from a class I have made, and they have been dequeued in.
Now for the confusing part. If I add a simple line in another class:
println(wait.getChoice())
it all works. This line has no relation to the first line above, and was simply for testing. But now when I take it out, I get the error. I would just leave it, but as you can see, it prints a load of rubbish onto the terminal.
I really have no idea what I'm doing wrong, and would love some help.
Feel free to ask for more snippets of the code, and thank you in advance for any help.
The problem is that you use synchronized incorrectly. You should wrap all calls to Referee.queue into Referee.synchronized {} blocks in order to synchronization to work. Otherwise the calls are not synchronized, and it's possible for one thread to modify Referee.queue without other thread notice.
Otherwise you should use thread safe collection. For example when I substitute scala.collection.mutable.Queue with scala.collection.mutable.SynchronizedQueue in the Referee class everything works ok, and you don't need to synchronize access to queue.
Even better use java.util.concurrent.ConcurrentLinkedQueue instead, because
SynchronizedQueue is deprecated in scala_2.11

Java make wrong optimization

I have this code
while(!decks.get(0).isEmpty()){
SingleCardWindow obj = new SingleCardWindow(decks.get(0).take());
while(obj.isVisible()){
}
System.out.println("Closed");
}
SingleCardWindow it is inherit-class from JFrame. This code displays all cards from the deck. Displays one card, wait until I close this window, and displays next card. In Windows it works well.
In linux (java-oracle-7) "Closed" never writing!
But if I make
while(!decks.get(0).isEmpty()){
SingleCardWindow obj = new SingleCardWindow(decks.get(0).take());
while(obj.isVisible()){
System.out.println("SOMETHING");
}
System.out.println("Closed");
}
program works right. So, i think that compiler optimize "while(obj.isVisible())" like "while(true)". What I should do with this? I dont needs any code into the loop.
In the second case you added this line:
System.out.println("SOMETHING");
PrintStream#println is a synchronized method, so if that helped your program to start working, it is a quite clear indication that the method obj.isVisible is not synchronized, and since you don't use any explicit synchronization, you are effectively causing a data race in your program. The reading thread never observes the change in the value of the isVisible property.
But, as many others have already noticed, this just answers the question as you have asked it; the code you have posted has many more issues with an inappropriate programming model (busy waiting) used to solve an essentially event-based problem.

Debug-Execution Adventure

I debugged my java code. It didn't give any errors.But when i executed it (it isn't giving errors either, but) the code didn't successfully terminate. This is very funny. But is that even possible?
sure, when the slowdown introduced by debugger does mask some race condition, but this normally only applies to multi-threading or networking code.
Yes it is possible that code works when debugging and doesn't work when running. Two possible reasons I can think of right now are
Concurrency in case of multithreading: if your debugger stops on a breakpoint, timing between multiple threads can change which can influence the behaviour
When debugging, you can trigger certain parts of the code multiple times (more than when it has been executed without debugging), like for example via the toString method or via doing inspects or having some watch expression configured
Yes, your code can be syntactically correct (and thus might run without any errors) but may be semantically incorrect.
Assume the following:
public int add( int operand1, int operand2)
{
return operant1 - operand2;
}
This would run without errors but still be incorrect due to logic/implementation error.
So, it IS possible to get wrong results by otherwise smoothly running code.

Weird Java problem, while loop termination

I have a piece of code that looks like this:
Algorithm a = null;
while(a == null)
{
a = grid.getAlgorithm();
}
getAlgorithm() in my Grid class returns some subtype of Algorithm depending on what the user chooses from some options.
My problem is that even after an algorithm is selected, the loop never terminates. However, that's not the tricky bit, if I simply place a System.out.println("Got here"); after my call to getAlgorithm(), the program runs perfectly fine and the loop terminates as intended.
My question is: why does adding that magic print statement suddenly make the loop terminate?
Moreover, this issue first came up when I started using my new laptop, I doubt that's related, but I figured it would be worth mentioning.
Edit: The program in question is NOT multithreaded. The code for getAlgorithm() is:
public Algorithm getAlgorithm ()
{
return algorithm;
}
Where algorithm is initially null, but will change value upon some user input.
I believe the issue has to deal with how grid.getAlgorithm is executed. If there is very little cost associated with executing the method, then your while loop will cycle very quickly as long the method continues to return null. That is often referred to as a busy wait.
Now it sounds like your new laptop is encountering a starvation issue which didn't manifest on your old computer. It is hard to say why but if you look at the link I included above, the Wikipedia article does indicate that busy waits do have unpredictable behavior. Maybe your old computer handles user IO better than your new laptop. Regardless, on your new laptop, that loop is taking resources away from whatever is handling your user IO hence it is starving the process that is responsible for breaking the loop.
You are doing active polling. This is a bad practice. You should at least let the polling thread sleep (with Thread.sleep). Since println does some io, it probably does just that. If your app is not multithreaded it is unlikely to work at all.
If this loop is to wait for user input in a GUI then ouch. Bad, bad idea and even with Thread.sleep() added I'd never recommend it. Instead, you most likely want to register an event listener on the component in question, and only have the validation code fire off when the contents change.
It's more than likely you're program is locking up because you've reached some form of deadlock more than anything else, especially if your application is multithreaded. Rather than try to solve this issue and hack your way round it, I'd seriously consider redesigning how this part of the application works.
You should check getAlgorithm(), there must be something wrong in the method.
There are two scenarios:
Your code is really not meant to be multi-threaded. In this case you need to insert some sort of user input in the loop. Otherwise you might as well leave it as Algorithm a = grid.getAlgorithm(); and prevent the infinite loop.
Your code is multi-threaded in which case you have some sort of 'visibility' problem. Go to Atomicity, Visibility and Ordering or read Java Concurrency in Practice to learn more about visibility. Essentially it means that without some sort of synchronization between threads, the thread you are looping in may never find out that the value has changed due to optimizations the JVM may perform.
You did not mention any context around how this code is run. If it is a console based application and you started from a 'main' function, you would know if there was multi-threading. I am assuming this is not the case since you say there is no multithreading. Another option would be that this is a swing application in which case you should read Multithreaded Swing Applications. It might be a web application in which case a similar case to swing might apply.
In any case you could always debug the application to see which thread is writing to the 'algorithm' variable, then see which thread is reading from it.
I hope this is helpful. In any case, you may find more help if you give a little more context in your question. Especially for a question with such an intriguing title as 'Weird Java problem, while loop termination'.

Categories