I have next code:
boolean signal;
#Test
public void test() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (!signal){
// empty loop body
}
}
});
thread.start();
Thread.sleep(1000);
signal = true;
thread.join();
}
It runs infinity loop due to creation of local copy of signal variable in thread. I know that I can fix it by making my signal variable volatile. But also loop can successfully exit if add synchronized block inside my loop (even empty):
boolean signal;
#Test
public void test() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (!signal){
synchronized (this) {
}
}
}
});
thread.start();
Thread.sleep(1000);
signal = true;
thread.join();
}
How synchronized updates my signal value inside thread?
Synchronized does not updates the signal value itself, it basically just places a couple of flags to avoid two threads use the same object at the same time; something like: MonitorEnter and MonitorExit.
The first one locks the object, and the second one releases.
Take a look at the following article: how-the-java-virtual-machine-performs-thread-synchronization.
Please notice the article is very old; but as far as I understand the logic behind remains.
Related
I state that I read about thread, but I've never used.
So I ask to you :)
I have two thread: A and B,
where A manages the GUI, and B manages the logic.
I would start with A.
Then when A draw the GUI, I would pause it, to wait B that reach a point X into run method.
And when B reach the X point into run method, I pause B, and resume A.
A and B share some variable to manage the GUI, and the logic...
Can I do it? if yes, how? :)
Using wait() and notify() methods:
wait() - Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
notify() - Wakes up a single thread that is waiting on this object's monitor.
You can block threads using the wait and notify methods of the Object class, but it can be tricky to get right. Here's an example inside an infinite loop in a Runnable:
public class Example implements Runnable {
private volatile boolean running = true;
private volatile boolean paused = false;
private final Object pauseLock = new Object();
#Override
public void run() {
while (running) {
synchronized (pauseLock) {
if (!running) { // may have changed while waiting to
// synchronize on pauseLock
break;
}
if (paused) {
try {
pauseLock.wait(); // will cause this Thread to block until
// another thread calls pauseLock.notifyAll()
// Note that calling wait() will
// relinquish the synchronized lock that this
// thread holds on pauseLock so another thread
// can acquire the lock to call notifyAll()
// (link with explanation below this code)
} catch (InterruptedException ex) {
break;
}
if (!running) { // running might have changed since we paused
break;
}
}
}
// Your code here
}
}
public void stop() {
running = false;
// you might also want to interrupt() the Thread that is
// running this Runnable, too, or perhaps call:
resume();
// to unblock
}
public void pause() {
// you may want to throw an IllegalStateException if !running
paused = true;
}
public void resume() {
synchronized (pauseLock) {
paused = false;
pauseLock.notifyAll(); // Unblocks thread
}
}
};
(For more information on why we need to synchronize as illustrated above whilst calling wait and notifyAll, see the Java tutorial on the subject.)
If another Thread calls this Runnable's pause() method, then the Thread running the runnable will block when it gets to the top of the while loop.
Note that it is not possible to pause a thread at any arbitrary point. You need the Thread to periodically check whether it should pause and block itself if so.
I would expect that you don't need to pause the GUI thread. The operating system will take care of that, and it needs to be ready to respond in case the user does something.
One other thought is to make sure the shared variables are properly synchronized between the two threads. I tried answering a question relating to that recently, see here.
you can use a CountDownLatch. When Thread A has to wait for Thread B will call countDownLatchInstance.await(); When B reach the X point will invoke countDownLatchInstance.countDown(); allowing A to continue its execution flow.
When you say
A manages the GUI
I hope you do not refer to the UI/Main Thread
,
public class Mutex {
private final AtomicBoolean lock;
private final Object mutex;
public Mutex(boolean lock) {
this.lock = new AtomicBoolean(lock);
this.mutex = new Object();
}
public void step() {
if (lock.get()) synchronized(mutex) {
try {
mutex.wait();
} catch (InterruptedException ex) {}
}
}
public void lock() {
lock.set(true);
}
public void unlock() {
lock.set(false);
synchronized(mutex) {
mutex.notify();
}
}
}
Just add Mutex object to your thread and make getter.
public class MyThread extends Thread {
private final Mutex mutex;
public MyThread() {
this.mutex = new Mutex(false);
}
public Mutex getMutex() {
return this.mutex;
}
#Override
public void run() {
while (!isInterrupted()) {
mutex.step();
// do your code
}
}
}
If you want to pause the thread just call
myThread.getMutex().lock();
If you want to resume the thread just call
myThread.getMutex().unlock();
That's the way I got thread's wait and notify working for me:
public class Main {
public static void main(String[] args) {
final Object lock = new Object();
MyThread t = new MyThread();
t.lock = lock;
t.run();
while (true) {
try {
synchronized (lock) {
lock.wait();
}
System.out.println("hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MyThread extends Thread {
Object lock;
#Override
public void run() {
JFrame fr = new JFrame("Anothing");
JButton btn = new JButton("Next");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
synchronized (lock) {
lock.notify();
}
}
});
fr.setLayout(new FlowLayout());
fr.add(btn);
fr.setSize(400, 400);
fr.setVisible(true);
}
}
Then, whenever I press the button, the other thread wakes up, executes one round and waits for a new clicking.
The java primitive to suspend and resume a thread is deprecated. See this to figure how you can achieve best what you need - http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Check how you can do the equivalent of suspend & resume
What should I use instead of Thread.suspend and Thread.resume?
As with Thread.stop, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify.
Example code is given in the same answer to help you achieve this.
I have a worker thread that is running in the background. On this worker thread, I have a method called syncWithUiThreadAndWait. Here is the simplified code:
private void syncWithUiThreadAndWait(final Runnable codeToSync) {
if (looper == null)
throw new RuntimeException("Thread is not ready (Looper=null)");
if (looper != Looper.myLooper())
throw new RuntimeException("Called from wrong thread");
final boolean[] wasRun = {false};
new Handler(looper).post(new Runnable() {
// I use 'new Handler(looper).post' instead of direct call to make sure that this code will
// run 100% after Looper.loop() is called, because in some cases it can be called before Looper.loop
#Override
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
synchronized (MyWorkerThread.this) {
// Synchronization to establishes a happens-before relationship
wasRun[0] = true;
looper.quit();
}
}
});
}
});
Looper.loop();
synchronized (MyWorkerThread.this) {
// Synchronization to establishes a happens-before relationship
if (!wasRun[0])
throw new RuntimeException("WHY!!!");
}
}
So my question is: why sometimes this code runs correctly and sometimes thread loop does not start and I receive my 'WHY' exception?
Edit:
I decided to add some explanation to make it easier to understand.
What I am trying to do is a synchronized thread with UI thread.
First, prepare task new Handler (looper) .post (...); that will be run once I 'block' my background thread from continuing.
After that, I 'block' my background thread by Looper.loop ();
The task that I prepared will run once the loop is looped and will fire code for UI thread.
Lastly, at the end of the code that will be run on UI thread looper.quit (); is called to unblock background thread.
So even though I still don't know why it was happening. So if someone can explain I will mark it as a correct answer.
But I found a workaround using Thread.sleep() instead of using Looper.loop(). Wich works for me and probably is more efficient:
private void syncWithUiThreadAndWait(final Runnable codeToSync) {
synchronized (this) {
if (thread == null)
throw new RuntimeException("Thread not ready");
if (Thread.currentThread() != thread)
throw new RuntimeException("Called from wrong thread");
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
codeToSync.run();
setPaused(false);
}
});
setPaused(true);
final long sleepStart = System.currentTimeMillis();
while (isPaused()) {
try {
Thread.sleep(200);
} catch (InterruptedException ignored) { }
if (sleepStart + TIMEOUT_IN_MILLISEC <= System.currentTimeMillis())
throw new RuntimeException("Timeout waiting for network response");
}
}
private synchronized boolean isPaused() {
return paused;
}
private synchronized void setPaused(boolean newValue) {
paused = newValue;
}
class Test {
boolean isFirstThread = true;
private synchronized void printer(int threadNo) {
if(isFirstThread) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isFirstThread = false;
System.out.println(threadNo);
}
public void starter() {
new Thread(){
#Override()
public void run() {
printer(0);
}
}.start();
new Thread(){
#Override()
public void run() {
printer(1);
}
}.start();
new Thread(){
#Override()
public void run() {
printer(2);
}
}.start();
new Thread(){
#Override()
public void run() {
printer(3);
}
}.start();
}
}
In the above code, when i call starter from main. I have created four new Threads to call a synchronized function. I know the order of execution of the threads can't be predicted. Unless they all wait for some time, so that first thread can finish and come out of the synchronized block. In which case I expect all threads to be held in a queue so i expected the answer as
0
1
2
3
But consistently(I ran the program more than 20 times) I was getting the output as
0
3
2
1
Which means that the threads are being held in a stack instead of a queue. Why is it so? Every answer in the google result says it is a queue but I am getting it as a stack. I would like to know the reason behind for holding the threads in stack(which is counter intuitive) instead of queue?
The order in which threads start is up to the OS, it is not specified in the Java Language Spec. You call start in the main thread, but when the new thread gets allocated and when it begins processing its Runnable or run method is left to the OS' scheduler to decide.
Be careful not to rely on the order in which threads happen to start.
I state that I read about thread, but I've never used.
So I ask to you :)
I have two thread: A and B,
where A manages the GUI, and B manages the logic.
I would start with A.
Then when A draw the GUI, I would pause it, to wait B that reach a point X into run method.
And when B reach the X point into run method, I pause B, and resume A.
A and B share some variable to manage the GUI, and the logic...
Can I do it? if yes, how? :)
Using wait() and notify() methods:
wait() - Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
notify() - Wakes up a single thread that is waiting on this object's monitor.
You can block threads using the wait and notify methods of the Object class, but it can be tricky to get right. Here's an example inside an infinite loop in a Runnable:
public class Example implements Runnable {
private volatile boolean running = true;
private volatile boolean paused = false;
private final Object pauseLock = new Object();
#Override
public void run() {
while (running) {
synchronized (pauseLock) {
if (!running) { // may have changed while waiting to
// synchronize on pauseLock
break;
}
if (paused) {
try {
pauseLock.wait(); // will cause this Thread to block until
// another thread calls pauseLock.notifyAll()
// Note that calling wait() will
// relinquish the synchronized lock that this
// thread holds on pauseLock so another thread
// can acquire the lock to call notifyAll()
// (link with explanation below this code)
} catch (InterruptedException ex) {
break;
}
if (!running) { // running might have changed since we paused
break;
}
}
}
// Your code here
}
}
public void stop() {
running = false;
// you might also want to interrupt() the Thread that is
// running this Runnable, too, or perhaps call:
resume();
// to unblock
}
public void pause() {
// you may want to throw an IllegalStateException if !running
paused = true;
}
public void resume() {
synchronized (pauseLock) {
paused = false;
pauseLock.notifyAll(); // Unblocks thread
}
}
};
(For more information on why we need to synchronize as illustrated above whilst calling wait and notifyAll, see the Java tutorial on the subject.)
If another Thread calls this Runnable's pause() method, then the Thread running the runnable will block when it gets to the top of the while loop.
Note that it is not possible to pause a thread at any arbitrary point. You need the Thread to periodically check whether it should pause and block itself if so.
I would expect that you don't need to pause the GUI thread. The operating system will take care of that, and it needs to be ready to respond in case the user does something.
One other thought is to make sure the shared variables are properly synchronized between the two threads. I tried answering a question relating to that recently, see here.
you can use a CountDownLatch. When Thread A has to wait for Thread B will call countDownLatchInstance.await(); When B reach the X point will invoke countDownLatchInstance.countDown(); allowing A to continue its execution flow.
When you say
A manages the GUI
I hope you do not refer to the UI/Main Thread
,
public class Mutex {
private final AtomicBoolean lock;
private final Object mutex;
public Mutex(boolean lock) {
this.lock = new AtomicBoolean(lock);
this.mutex = new Object();
}
public void step() {
if (lock.get()) synchronized(mutex) {
try {
mutex.wait();
} catch (InterruptedException ex) {}
}
}
public void lock() {
lock.set(true);
}
public void unlock() {
lock.set(false);
synchronized(mutex) {
mutex.notify();
}
}
}
Just add Mutex object to your thread and make getter.
public class MyThread extends Thread {
private final Mutex mutex;
public MyThread() {
this.mutex = new Mutex(false);
}
public Mutex getMutex() {
return this.mutex;
}
#Override
public void run() {
while (!isInterrupted()) {
mutex.step();
// do your code
}
}
}
If you want to pause the thread just call
myThread.getMutex().lock();
If you want to resume the thread just call
myThread.getMutex().unlock();
That's the way I got thread's wait and notify working for me:
public class Main {
public static void main(String[] args) {
final Object lock = new Object();
MyThread t = new MyThread();
t.lock = lock;
t.run();
while (true) {
try {
synchronized (lock) {
lock.wait();
}
System.out.println("hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MyThread extends Thread {
Object lock;
#Override
public void run() {
JFrame fr = new JFrame("Anothing");
JButton btn = new JButton("Next");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
synchronized (lock) {
lock.notify();
}
}
});
fr.setLayout(new FlowLayout());
fr.add(btn);
fr.setSize(400, 400);
fr.setVisible(true);
}
}
Then, whenever I press the button, the other thread wakes up, executes one round and waits for a new clicking.
The java primitive to suspend and resume a thread is deprecated. See this to figure how you can achieve best what you need - http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Check how you can do the equivalent of suspend & resume
What should I use instead of Thread.suspend and Thread.resume?
As with Thread.stop, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify.
Example code is given in the same answer to help you achieve this.
Today I was creating one timeout job using TimerTask but fell in to a new problem where i have a static volatile boolean variable flag. My understanding is as soon as value of this variable get changed it is notified by all running thread. But when I ran this program I got below output which is not acceptable.
O/P:
--------------
--------------
DD
BB
Exiting process..
CC
My expectation is my last print should be Exiting process.. Why is this strange behavior?
My code is:
public class TimeOutSort {
static volatile boolean flag = false;
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
flag = true;
System.out.println("Exiting process..");
// System.exit(0);
}
}, 10 * 200);
new Thread(new Runnable() {
#Override
public void run() {
while (!flag)
System.out.println("BB");
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while (!flag)
System.out.println("CC");
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while (!flag)
System.out.println("DD");
}
}).start();
}
}
Edit: How can i achieve this ?
volatile pretty much means that each time a thread accesses a variable it must ensure to use the version visible to each thread (i.e. no per-thread caching).
This doesn't force the CC-printing thread to actually get to run immediately after the flag has been set to true. It's entirely possible (especially on a single-core machine) that one thread sets the flag and prints the message before the CC-printing thread even had a chance to run.
Also: note that printing to System.out involves acquiring a lock (somewhere inside the println() call), which can modify the multi-threaded behaviour of test code.
Threads can execute code in any order
thread BB: while (!flag) // as flag is false
thread Main: flag = true;
thread Main: System.out.println("Exiting process..");
thread BB: System.out.println("BB");
My expectation is my last print should be Exiting process..
Threads are designed to run concurrently and independently. It would be surprising if this was always the last statement because you can't be sure where each thread is when you set the flag.
The thread that prints "CC" happened not to receive any CPU time until after your thread that prints "Exiting process..." printed that. This is expected behavior.
It's not volatile not working (if it were not, some of your threads would not have stopped). It's about the order of execution of instructions in the different threads, and this is random (depends on OS scheduling) unless you explicitly synchronize the loops at intermediate steps.
To add an alternative phrasing to the explanations you got: in your sample output, the thread that prints "CC" got suspended (somewhere) "between" the lines while (!flag) and System.out.println(). Which means that after it wakes up, the println() executes before the next check of the flag. (It also won't get woken up just because you change the flag value, but because some other thread blocks or uses up its time slice.)
i didn't test it , but you may achieve it like this
public class TimeOutSort {
static volatile boolean flag = false;
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
synchronized(flag){
flag = true;
notifyAll();
}
}
}, 10 * 200);
new Thread(new Runnable() {
#Override
public void run() {
synchronized(flag){
if(!flag)
{
wait();
}
System.out.println("BB");
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
synchronized(flag){
if(!flag)
{
wait();
}
System.out.println("CC");
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
synchronized(flag){
if(!flag)
{
wait();
}
System.out.println("DD");
}
}
}).start();
}
}