Can I synchronize reads of control variables? - java

The following code will work, but I slightly resent having to write the isRunning() method:
class Test {
private boolean running;
public void startX() {
synchronized(this) {
running = true
}
while (isRunning()) {
//do something
}
}
public synchronized void stopX() {
running = false;
}
private synchronized boolean isRunning() {
return running;
}
}
Can I synchronize reads of the running variable in the while (running){} in some other way, or do I have to write the isRunning() method? The same question applies to other control variables as well, eg
for (;running;) {}
or
if (running) {}
In all of these cases it seems as though you're forced into writing a pointless method to get the synchronization correct. Am I missing something?

if you are only resetting the value of running once to designate to stop, you might be able to use the volatile keyword.
However, if you need to start and stop many times, this won't work. This is because volatile fields "may miss an update"
Here's a link to explanation of when volatile works in cases like this link
here's the code sample from that link incase it goes dead:
public class StoppableTask extends Thread {
private volatile boolean pleaseStop;
public void run() {
while (!pleaseStop) {
// do some stuff...
}
}
public void tellMeToStop() {
pleaseStop = true;
}
}
If you need to start and stop many times, then you need to either use one of the Java 5 concurrent lock objects or explicit synchronization

You could make the running field volatile. Making the field volatile puts the JVM on notice that it should make changes to that field visible to other threads.
The "miss an update" caveat is for cases where you want to read a value and update based on that value, which doesn't seem applicable here.
Multiple threads can write to this field, if all they're doing is setting a boolean flag then this won't be a problem.
Alternatively, if you are trying to cancel a thread, there's already an equivalent flag provided on Thread for this (and the visibility issue is taken care of). You can call interrupt on a thread, the code in the Runnable can query Thread.currentThread().isInterrupted() in order to tell whether it's been interrupted. This is preferable over using your own flag because the interruption will cause the thread to wake up if it is waiting or sleeping. With your own flag you have to wait until control reaches a place where the flag can be tested.

just to add up to other people's answer that suggested volatile .
Alternatively you could create a class for the checks.
I have made the variable to be static, so all threads will be pointing to same object.
class Runner{
boolean static running=true;
public static synchronized boolean getRunning(){
return running;
}
public static synchronized boolean setRunning(boolean r){
running=r;
}
}
NOTE:
if you don't require the global variable, then remove the static

Related

How to use volatile boolean to check whether the thread should run?

I have a class that extends threads as seen below, and I want it to have a volatile boolean field that it checks to decide whether to continue running or not. The shouldRun() method is called from the EDT of my GUI.
How do I get this thread to check the boolean to know whether it should run or wait() from my GUI's Event Dispatcher Thread?
public class RobotThread extends Thread{
public volatile boolean run;
//if running == true, let thread run
//if running == false, invoke wait() somehow;
public RobotThread(AutoClicker autoClicker) {
super(autoClicker);
run = true;
}
public void setRun(boolean shouldRun) {
this.run = shouldRun;
}
public boolean getRun() {
return run;
}
}
In general, I just want to be able to get this thread to wait() and restart from the Event Dispatcher Thread of my GUI with button. If there are any better ways to do this I'll be happy to hear it too.
For the waiting and restarting I believe an infinit loop, wait and notify methods are what you're looking for. For instance, look at this guide.

Java and thread safety

I am creating a mutli threaded application, and I have a question regarding the use of synchronized methods.
Lets say I have the following component which would be accessed by multiple threads.
Component.java
public class Component {
private boolean active;
//Constructor
public Component(){
active = false;
}
synchronized public void initiate(){
//do something
active = true;
}
synchronized public void closedown(){
//do something
active = false;
}
public void doSomething(){
//do something
}
public boolean isActive(){
return active;
}
}
If I have two threads accessing the the same Component object and the first thread gets halted in the Component.closedown() before it has set active = false, and the second thread picks up and calls Component.isActive(), will the second thread block until the first thread has finished the closedown, or will it get the returned value of true?
If it is the latter, how can I make this thread safe?
Yes, that is the essence of mutual-exclusion locks (mutexes). If a thread gets descheduled by the OS while holding a mutex, all other threads requiring the mutex to proceed will be stalled.
The above is actually the reason why, even if we take care to make all our critical sections very short and fast to execute, mutexes will still cause occasional latency spikes, and the spikes will be huge in proportion to regular latency. For example, your simple getter will execute in a couple of nanoseconds when uncontended, but may take 10µs or more if the thread holding the mutex is descheduled at an inconvenient time.
NOTE: The code in your question lacks the synchronized designation on isActive, but I assume your question is about what would happen if it was synchronized—because the code has a data race without it. Specifically:
will the second thread block until the first thread has finished the closedown, or will it get the returned value of true?
Without synchronized it will do neither: it won't block, but it won't be guaranteed to ever return the true value. You are only guaranteed to observe the initial value (that's what the data race is about).
If you are looking for a practical advice to improve your code, then don't synchronize isActive method, but make the active flag volatile. This is standard practice for your use case.
You need to have use a lock to protect the critical sections. As some methods read from the value and some write to the value, you can try using a ReadWriteLock.
public class Component {
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private boolean active;
//Constructor
public Component(){
active = false;
}
public void initiate(){
// non-critical section
rwl.writeLock().lock();
try {
// critical section
active = true;
} finally {
rwl.writeLock().unlock();
}
}
public void closedown(){
// non-critical section
rwl.writeLock().lock();
try {
// critical section
active = false;
} finally {
rwl.writeLock().unlock();
}
}
public void doSomething(){
// do something
}
public boolean isActive(){
rwl.readLock().lock();
boolean status = active;
rwl.readLock().unlock();
return status;
}
}

One thread updates variable and another read it, do I need something special

I have a class that has the object "Card". This class keeps checking to see if the object is not null anymore. Only one other thread can update this object. Should I just do it like the code below? Use volatile?Syncronized? lock (which I dont know how to use really)? What do you recommend as easiest solution?
Class A{
public Card myCard = null;
public void keepCheck(){
while(myCard == null){
Thread.sleep(100)
}
//value updated
callAnotherMethod();
}
Another thread has following:
public void run(){
a.myCard = new Card(5);
}
What do you suggest?
You should use a proper wait event (see the Guarded Block tutorial), otherwise you run the risk of the "watching" thread seeing the reference before it sees completely initialized member fields of the Card. Also wait() will allow the thread to sleep instead of sucking up CPU in a tight while loop.
For example:
Class A {
private final Object cardMonitor = new Object();
private volatile Card myCard;
public void keepCheck () {
synchronized (cardMonitor) {
while (myCard == null) {
try {
cardMonitor.wait();
} catch (InterruptedException x) {
// either abort or ignore, your choice
}
}
}
callAnotherMethod();
}
public void run () {
synchronized (cardMonitor) {
myCard = new Card(5);
cardMonitor.notifyAll();
}
}
}
I made myCard private in the above example. I do recommend avoiding lots of public fields in a case like this, as the code could end up getting messy fast.
Also note that you do not need cardMonitor -- you could use the A itself, but having a separate monitor object lets you have finer control over synchronization.
Beware, with the above implementation, if run() is called while callAnotherMethod() is executing, it will change myCard which may break callAnotherMethod() (which you do not show). Moving callAnotherMethod() inside the synchronized block is one possible solution, but you have to decide what the appropriate strategy is there given your requirements.
The variable needs to be volatile when modifying from a different thread if you intend to poll for it, but a better solution is to use wait()/notify() or even a Semaphore to keep your other thread sleeping until myCard variable is initialized.
Looks like you have a classic producer/consumer case.
You can handle this case using wait()/notify() methods. See here for an example: How to use wait and notify in Java?
Or here, for more examples: http://www.programcreek.com/2009/02/notify-and-wait-example/

Java thread won't join

Okay I'm sure I'm missing something simple here but can't see it. I'm using a flag to end a thread and then joining it to clean up neatly, but the join never finishes it just gets stuck waiting. There is currently nothing in the thread's run loop so it isn't getting stuck in a separate loop.
Thread:
package com.nox.willywars;
public class GameThread extends Thread {
//{{Variables
private boolean running;
//}}
//{{Getters/Setters
public void setRunning(boolean running) {
this.running = running;
}
//}}
//{{Constructor
public GameThread() {
running = false;
}
//}}Constructor
//{{Public methods
#Override
public void run() {
while(running) {
///...CODE GO HERE
}
}
public boolean isRunning() {
return running;
}
//}}
}
Code that fails to stop it:
//{{Lifecycle methods
#Override
public void create() {
//LOAD! Probably debug temp
TileFactory.load();
mapScreen = new MapScreen();
setScreen(mapScreen);
gameThread = new GameThread();
gameThread.setRunning(true);
gameThread.start();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
killGameThread();
}
private void killGameThread() {
if(gameThread != null) {
if(gameThread.isAlive() && gameThread.isRunning()) {
gameThread.setRunning(false);
boolean retry = true;
while(retry) {
try {
gameThread.interrupt();
gameThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
gameThread = null;
}
}
//}}
Currently it reaches gameThread.join() and gets stuck there, waiting for the thread to finish. Am I missing something here? As I understand the thread should finish once running is set to false and then joining should happen normally because it's already stopped.
Edit: Added some more code from the class that runs GameThread. Pause() is where KillGameThread is executed. I've made running volatile but it's had no effect.
I found another weird symptom too: Some people suggested looking at what's inside GameThread when it's stuck, so I went into the debugger. While join() is stuck I suspended the GameThread thread and saw it was on while(running), and running was definitely false. Then when I stepped over the code it exited the loop and finished correctly, seemingly caused by my debugging. It's as if the thread is somehow suspended?
first set the running flag as volatile
private volatile boolean running;
What does game thread do exactly, maybe it has blocked by some I/O operation.
and if the game thread doesn't sleep/wait/join, so interrupting it is useless.
you need to share the game thread code.
As user2511414 pointed out, try with using volatile. In short, this will make sure the value od running is always accessed directly and not cached.
It setting volatile won't solve the situation, he problem most probably lays in the code section of a GameThread#run method that you commented out.
You can try using jstack or jvisualvm to get a Thread Dump of the thread you're trying to join.
This will at least show you where is it hanging, and may lead you to a solution.
The running flag is not properly synchronised. This could (in theory) result in the thread not noticing the state change ... due to the way that the Java memory model works. You should either declare it as volatile or always access and update it in synchronized method calls (or synchronized blocks).
But (IMO) the real problem is in the way (actually the ways) that you are telling the thread to stop, and haw the thread is checking or responding.
If you are going to use a flag to tell the thread to stop, then the thread needs to check that flag frequently. If the thread could spend an indefinitely long amount of time doing something else between the checks, then it may never notice that it needs to stop.
If you are going to use Thread.interrupt() then:
Your code should be calling Thread.isInterrupted() to test the thread's "interrupted" status instead of an ad-hoc flag. Furthermore, it should be testing the status regularly.
Your code need to make sure that it handles the InterruptedException and InterruptedIOException properly. This applies all the way up the call stack.
Note that calling Thread.interrupt() doesn't actually interrupt the thread in most cases. In most cases, it just sets a flag that needs to be tested manually. The only cases you get more than that is in certain blocking calls; e.g. Object.wait(...) and some IO calls.
You've left out most of the code where these things ought to happen. The best we can say is that the problem is most likely in code you haven't shown us.

Thread stops itself

I've been searching for a solution for a long time, but I wasn't able to find one, so I'll ask my question here.
I have a thread which is started when the program starts and supposed to be idle until it is enabled by the application. Simple code example:
private class UpdaterThread extends Thread {
private static final int UPDATE_RATE = 50;
private Timer updateTimer = new Timer();
private boolean enabled;
public void run() {
while (!closeRequested) {
// If this is uncommented, the thread works as it's supposed to.
// System.out.print("");
if (enabled) {
Snapshot next = getNextSnapshot(1f / UPDATE_RATE);
System.out.println("Got next Snapshot");
updateTimer.sync(UPDATE_RATE);
System.out.println("Push");
currentSnapshot = next;
}
}
}
public void enable() {
enabled = true;
}
public void disable() {
enabled = false;
}
}
When you read a variable, which the JIT believes you didn't modify, it inlines the value. If you then modify the value later, it is too late, the value has been embedded in the code.
A simple way to avoid this is to use volatile but you would still have the problem than the thread is busy waiting for the value to change and there doesn't appear to be a good reason to do this. Another option is to add code which confuses the JIT do it doesn't do this optimisation. An empty synchronized block is enough but a friendlier way is to use Thread.sleep() which at least doesn't use up all your CPU.
I suggest using a volatile fields and sleeping with a period of 10-100 ms. However a simpler option is to not start the thread until it is needed.
since run() is called when the thread is started, you could just wait until later in the program to start it, also threads do not extend "Thread" but implements "Runnable" so the class definition would look like:
public class UpdaterThread implements Runnable
hope it helps :D

Categories