One of my Runnable runs following code:
while(true) {}
I have tried wrapping that Runnable in Executor apis and then tried shutdown method. Tried thread.interrupt. but nothing works. I can not modify Runnable code. Any suggestions...
Check its interrupted flag:
while (!Thread.currentThread().isInterrupted()) {}
Most of the Executors interrupt worker threads on shutdownNow, so this gives you a tidy mechanism for a clean shutdown.
If you need to terminate the Runnable outside the context of an Executor, you'll need to give it a shutdown method that sets a flag.
final AtomicBoolean isShutdown = new AtomicBoolean();
public void shutdown() {
if (!isShutdown.compareAndSet(false, true)) {
throw new IllegalStateException();
}
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !isShutdown.get()) {}
}
Related
May be my header would not be correct.
I have started java multithread concept with programming. since i have read inside synchronized block only one thread will inter on a particular object lock. But i have confused after looking the output of this program.
package com.example.classandobjectlevellock;
class MyThread implements Runnable
{
Object ob = new Object();
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName()+" Is waitng");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ClassAndObjectLevelLock {
public static void main(String[] args) throws InterruptedException {
MyThread task1 = new MyThread();
MyThread task2 = new MyThread();
Thread t1 = new Thread(task1,"Thread1");
Thread t2 = new Thread(task1,"Thread2");
Thread t3 = new Thread(task2,"Thread3");
t1.start();
Thread.sleep(1000);
t2.start();
Thread.sleep(1000);
t3.start();
}
}
Output:
Thread1 Is waitng
Thread2 Is waitng
Thread3 Is waitng
If i am not wrong, Thread-1 and thread-3 is entering into synchronized method because it having two different target object. But why Thread-2 is entering into Synchronized block?
Please help me for understanding of this .
Thanks in advance.
Calling wait() causes the lock to be released.
Per the wait() Javadocs:
Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object. In
other words, this method behaves exactly as if it simply performs the
call wait(0).
The current thread must own this object's monitor. The thread
releases ownership of this monitor and waits until another thread
notifies threads waiting on this object's monitor to wake up either
through a call to the notify method or the notifyAll method. The
thread then waits until it can re-obtain ownership of the monitor and
resumes execution.
I have the following program, where I am using java.util.concurrent.CountDownLatch and without using await() method it's working fine.
I am new to concurrency and want to know the purpose of await(). In CyclicBarrier I can understand why await() is needed, but why in CountDownLatch?
Class CountDownLatchSimple:
public static void main(String args[]) {
CountDownLatch latch = new CountDownLatch(3);
Thread one = new Thread(new Runner(latch),"one");
Thread two = new Thread(new Runner(latch), "two");
Thread three = new Thread(new Runner(latch), "three");
// Starting all the threads
one.start(); two.start(); three.start();
}
Class Runner implements Runnable:
CountDownLatch latch;
public Runner(CountDownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is Waiting.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println(Thread.currentThread().getName()+" is Completed.");
}
OUTPUT
two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.
CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.
Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.
So in your example it would make sense to call await() at the end of main() method:
latch.await();
Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.
I've just switched from Oracle JDK 1.6, to Open JDK 1.7.0_03, and I've hit a rather remarkable deadlock on exit:
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.Thread.join(Thread.java:1258)
- locked <0x8608dda0> (a sun.awt.X11.XToolkit$1$1)
at java.lang.Thread.join(Thread.java:1332)
at java.lang.ApplicationShutdownHooks.runHooks(ApplicationShutdownHooks.java:106)
at java.lang.ApplicationShutdownHooks$1.run(ApplicationShutdownHooks.java:46)
at java.lang.Shutdown.runHooks(Shutdown.java:123)
at java.lang.Shutdown.sequence(Shutdown.java:167)
at java.lang.Shutdown.exit(Shutdown.java:212)
- locked <0x8603df28> (a java.lang.Class for java.lang.Shutdown)
at java.lang.Runtime.exit(Runtime.java:107)
at java.lang.System.exit(System.java:960)
It appears that you must call System.exit from the AWT event queue. Is this for real? There is no documentation of a thread requirement in the Sun docs Runtime.exit
I've hit other surprising cases where getting the AWT tree lock is required only on Linux, but this one takes the cake. Is this a bug, or have I just missed something in the documentation?
It depends, the runHooks method will start any hook threads registered through Runtime.addShutdownHook and wait for them to be finished. If any of your hook threads is locking some resources that the AWT event thread is requiring too, they may cause dead lock.
If you have to call System.exit in your AWT event thread,I suggest you call it in another thread like:
new Thread(){
public void run() {
System.exit(0);
}
}.start();
It is impossible to say whether this is a bug in the runtime without knowing more about what the application is doing (ideally, this would take the form of an SSCCE).
For example, the following demonstrates a similar deadlock involving System.exit(). However, it is clearly a bug in the application, not in System.exit():
public class OhNo {
final static Object lock = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
synchronized (lock) {
for (;;) {
}
}
}
}).start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
synchronized (lock) {
System.out.println("in shutdown hook");
}
}
}));
System.out.println("about to call System.exit()");
System.exit(0);
}
}
Could you let me know the reason for this error in SWT
"org.eclipse.swt.SWTException" Invalid Thread access ?
And How to fix such errors.
It happens when you try to act upon an interface item from a thread that's not the UI thread.
To run a code on the UI thread you have to use a Runnable and ask the display thread to run it. This way:
Display.getDefault().syncExec( new Runnable() {
#Override
public void run() {
// Do your job here
}
} );
As stated by the syncExec method javadoc,
the thread which calls this method is suspended until the runnable completes.
Also, you might check the asyncExec method.
In SWT you can access GUI resources only from the display thread. For example when setting the text in a org.eclipse.swt.widgets.Text control you must already be in the display thread or call
final Text text = ...;
Display.getCurrent().syncExec(new Runnable() {
#Override
public void run() {
text.setText("test");
}
});
I have a program which runs a thread. The thread performs processing all the time and it uses some synchronized queue.
The class snapshot is as follows:
public class MyClass:IDisposable
{
private Thread myThread = new Thread(threadFunc);
private volatile bool runThread = true;
public MyClass()
{
myThread.Start();
}
public Dispose()
{
runThread = false;
}
private void threadFunc()
{
try
{
while(runThread){
queue.Take(); //This method blocks the thread if queue is empty. It uses Monitor class
//do some processing
}
}
catch(Exception e){...}
}
private void otherFunc()
{
queue.enqueue(...);//this method is executed by main thread and uses lock while adding element to the queue.
}
}
When I call Dispose() method, the thread exists threadFunc() method, but after a sec I get an execption from this func "Unable to avaluate expression...", as if the tread was terminated while doing some work. Maybe it has just released from queue.Take() blocking and has no context to run. I know I'm missing something...
How can I solve such problem and terminate the thread from the Dispose method.
Many thanks!!!
Use the overload of Take that accepts a CancellationToken. You can get a reference to a token by using the CancellationTokenSource which also has the Cancel method that you can call from Dispose to unblock the Take method. You can read more cancellation here.
Use the poison pill approach: See this thread