Variable interference with threads - java

Thread t1= new Thread(new Runnable() {
public void run() {
//perform Database stuff
}
});
t1.start();
initCache();//perform other Database stuff (Can this code be executed while thread 1 is running?)
How can I make sure the initCache method is forced to wait after t1 finishes?

Don't run it in a different thread to start with?
You could call t1.join() but really, if you want to run task X and then task Y, just run them in the same thread...

If you want initCache() to only run after t1 has finished running, then why do you start t1 in the first place?
Simply execute the code in run() and then initCache().
If there's some other action happening between t1.start() and initCache(), then you could use t1.join() to wait for t1 to finish before calling initCache().

Using join()? Seriously? Did the 90's called because they want their low-level synchronization facilities back?
What about something a bit more high-level? Like a CountDownLatch?
final CountDownLatch cdl = new CountDownLatch(1);
Thread t1= new Thread(new Runnable() {
public void run() {
//perform Database stuff
cdl.countDown();
}
});
t1.start();
cdl.await();
initCache();
Can also be configured with a timeout etc.

while (t1.isAlive()) {
try {
Thread.currentThread().sleep();
}
catch (InterruptedException e) {
//check again
}
}
initCache();
That should do it. Although actually the t1.join() method is a hell of a lot simpler.

Related

Method call from thread does not finish - How to end the thread - Workaround

I have a following code.
ReadWriteLock someLock = new ReentrantReadWriteLock();
Condition someCondition = someLock.writeLock().newCondition();
public someMethod() {
// do some stuff
someCondition.await(); //Lock here.
System.out.prinltn("This never prints");
}
public doSomeStuff() {
new Thread(new Runnable() {
#Override
public void run() {
try {
someMethod();
System.out.println("thread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread is going to die");
}
}).start();
}
When the thread calls the method someMethod() it gets executed. But since there is an await() method on that function. It never ends / it does not print 'This never prints', unless its woken up by singnalAll(). But I want the thread to be finished once its executed.
I cannot refactor the whole thing. I just need a workaround to this problem. Its used in Swing application. So thread is important.
I think, this will do:
Thread thread =
new Thread(new Runnable() {
#Override
public void run() {
try {
someMethod();
System.out.println("thread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread is going to die");
}
});
thread.start( );
final long reasonableTimeout = ...;
thread.join( reasonableTimeout );
// THIS WILL SHAKE IT UP
thread.interrupt( );
thread.join( );
// At this point, it is guaranteed that the thread has finished
I am not sure if I understood your question correctly but I think you want to start the someMethod() function and then make the caller exit without waiting for someMethod() to finish. This means you are basically branching your execution flow into two, one where the someMethod() running waiting for its due awakening and the other where the caller just continues on(which it will need to do if you want it to finish) after calling someMethod(). To do this you will have to run someMethod() in a separate thread. Something like this.
public doSomeStuff() {
new Thread(new Runnable() {
#Override
public void run() {
try {
new Thread(){
public void run(){
someMethod();
}
}.start();
System.out.println("thread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread is going to die");
}
}).start();
}
Two ways you can sort this out.
1) Design your task with Interruption Policy
Do a defensive coding. If your task is interrupted by any means, the program should know how to deal with that.
2) Add a POISON PILL as in this example, Once you
public someMethod() {
while(condition predicate){
someCondition.await(TIME_OUT); //Lock here.
}
//ADD Poison pill here
System.out.prinltn("This never prints");
}
As Per Java Concurrency in Practice
When using condition waits (Object.wait or Condition.await):
1)Always have a condition predicate some test of object state that must hold before
proceeding;
2)Always test the condition predicate before calling wait, and again after returning from
wait;
3)Always call wait in a loop;
4)Ensure that the state variables making up the condition predicate are guarded by the lock
associated with the condition queue;
5) Hold the lock associated with the the condition queue when calling wait, notify, or
notifyAll; and
6)Do not release the lock after checking the condition predicate but before acting on it.

Calling wait() after posting a runnable to UI thread until completion

I'm actually in need of waiting for the ui thread to execute a runnable before my application thread can continue. Is the wait()/notify() way a proper way to do it or is there something better for this? What I'm actually doing looks like this:
public void showVideoView() {
try {
final AtomicBoolean done = new AtomicBoolean(false);
final Runnable task = new Runnable() {
#Override
public void run() {
synchronized(this) {
mStartupCurtain.setVisibility(View.GONE);
mVideoView.setVisibility(View.VISIBLE);
mWebView.loadUrl("about:blank");
mWebView.setVisibility(View.GONE);
done.set(true);
notify();
}
}
};
mUiHandler.post(task);
synchronized(task) {
while(!done.get()) {
task.wait();
}
Log.d(TAG, "showVideoView done!");
}
} catch (InterruptedException e) {
Log.e(TAG, "Thread got interrupted while waiting for posted runnable to finish its task");
}
}
Also when I do this I have to be sure that the thread is not the one of the UI, which happens when I start calling methods from a listener method coming from an interface like MediaPlayer.OnCompletionListener.
What do you think?
Looks fine to me.
The "done" variable could be a regular Boolean instead of AtomicBoolean since you definitively get/set it's value within the lock. I like that you check the value of "done" prior to calling wait - since it is quite possible the task will have been completed before you ever enter the lock in the worker thread. If you had not done that, the wait() call would go indefinitely since the notify() had already happened.
There is one edge case to consider that may or may not be applicable to your design. What happens if the UI thread is attempting to exit (i.e. app exit) when the worker thread is still stuck waiting for the task to complete? Another variation is when the worker thread is waiting on the task to complete, but the UI thread is waiting on the worker thread to exit. The latter could be solved with another Boolean variable by which the UI thread signals the worker thread to exit. These issues may or may not be relevant - depending on how the UI is managing the thread to begin with.
Use AsyncTask!
AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers.
http://developer.android.com/reference/android/os/AsyncTask.html
Function:
public static void postOnUI(Runnable runnable,boolean wait) {
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// Is on UI thread.
runnable.run();
return;
}
Handler uiHandler = new Handler(Looper.getMainLooper());
AtomicBoolean done = new AtomicBoolean(false);
uiHandler.post(() -> {
runnable.run();
done.set(true);
});
if (wait) {
while (!done.get()) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
}
}
Usage Example:
Utils.postOnUI(headerView::updateUI,true);

Simple example to understand the concept of join() in Thread

I am studying the Threads in java.
I just want a simple example which explains the use of join() in Thread. I have seen this link..
Understanding join() method example
But still not able to understand the concept.
Can anybody explain me the concept of using the join() in Thread.
Any explanation retlated to this will be very helpful to me.
Thanks.
The simplest explanation I can come up is that join makes the caller thread wait for the completion of specified thread.
Say if you have a "main thread" and "thread A", if from the main thread you call A.join(), the main thread will wait until thread A finishes.
The java se manual page about concurrency should help you here: http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
Thread.join() causes the current thread to wait for the thread you call join() on to die before it resumes execution.
Thread.join() blocks (does not return) until the thread you joined on has finished.
This is not the only way to wait for a thread to finish, but it is the most CPU-usage friendly way. Imagine if you had a loop like this (pseudocode):
while(!thread.isAlive())
{
Sleep(1);
}
This supposedly does the same thing... but, 1000 times per second, it will wake up, check the variable and go back to sleep. This means 1000 context switches (which are expensive) and the program will be slower as a result. This is called 'spinlocking' or 'busywaiting' and is frowned upon in programming as it consumes CPU for no reason.
I did some experiment and here is the result: 1. first started thread t3. 2. started t1 then 3. created t2 and t2 joinned the running thread t1.
By definition, t2 should wait for t1 to die and then it should start.
Observation: I called wait on t1, so t1 is paused but not died but I see then t2 is started why ?
public class TestThreadJoin {
public static void main(String[] args) {
final Thread t3 = new Thread(new Runnable() {
public void run() {
System.out.println("R3");
}
});
t3.start();
final Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("R1 before");
try {
perform();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("R1 after");
}
private void perform() throws InterruptedException {
synchronized(this){
wait(5000);
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("R2");
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
}
}

How to acquire multiple locks without ordering constraints in Java?

So I have code similar to this
synchronized(objectOne){ do stuff }
synchronized(objectTwo){ do stuff }
The problem with this is the program will wait for the lock on objectOne, even if the lock for objectTwo is available. What I'm trying to do is say: try to lock both objectOne and objectTwo, and whichever lock you get first do the stuff for that lock. I've come up with a solution but I think it's rather hacky and I'm wondering if anybody has any better ideas.
Here's my idea: Start 2 threads, each one waiting on a lock and then the main thread will wait on a CountDownLatch. So you end up with something like this:
CountDownLatch latch = new CountDownLatch(2);
new Thread(new Runnable(){
public void run(){
synchronized(objectOne) { do stuff }
latch.countDown();
}).start();
new Thread(new Runnable(){
public void run(){
synchronized(objectTwo) { do stuff }
latch.countDown();
}).start();
latch.await();
I think you should use Lock which provides you with the method boolean tryLock().
Returns:
true if the lock was acquired and false otherwise
Proceed with do stuff when you have at least one of the locks.
You might want to have 2 queues of jobs, 2 threads each polling a queue and execute the jobs.
For jobs related to objectOne, you put it in queue#1; jobs related to objectTwo in queue#2.
worker1.queue.put( new Runnable(){ public void run() { do stuff } } );
worker2.queue.put( new Runnable(){ public void run() { do stuff } } );
----
class Worker extends Thread
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
public void run()
while(true)
queue.take().run();
Depending on the amount of stuff it could be more overhead to spin off multiple threads to do stuff. It might just be best to do stuff in a single thread if stuff is a fast enough operation. You will have to time it to know.
I kind of like your hack, at least if it's a one-off situation. That said...
If you're doing this sort of thing a lot and want something "less hacky", I'd suggest ExecutorService#invokeAll(). This takes a list of Callables, executes them on a thread pool and blocks until they're all done.
Sketch:
ExecutorService es = Executors.newCachedThreadPool(); // for example...
List<Future<Void>> results = es.invokeAll(new ArrayList {{
add(new Callable<Void> {
public Void call() { synchronized(objectOne) { do stuff } }
});
add(new Callable<Void> {
public Void call() { synchronized(objectTwo) { do stuff } }
});
}});
// both Callables are done when you get here
This obviously assumes that it's ok to call these methods from different threads at this point in your app. If for some reason you need to call both from the same thread, I think you're doomed to use tryLock and busy-wait as discussed in Bhesh Gurung's answer.

Make waiting thread skip the rest of the wait/continue

I have a scenario where I have one thread that loops between waiting and executing a task. However, I would like to interrupt the wait for the thread (skip the rest of the wait if you will) and continue on to doing the task.
Anyone have any ideas how this could be done?
I think what you need is implement wait()/notify() ! check it out this tutorial: http://www.java-samples.com/showtutorial.php?tutorialid=306
There are a lot of them out there! if you need a more specific case, post a bit of your code!
cheers
You could use wait() and notify(). If your thread is waiting, you'll need to resume it by calling notify() from a different thread.
This is what Thread.interrupt is for:
import java.util.Date;
public class Test {
public static void main(String [] args) {
Thread t1 = new Thread(){
public void run(){
System.out.println(new Date());
try {
Thread.sleep(10000); // sleep for 10 seconds.
} catch (InterruptedException e) {
System.out.println("Sleep interrupted");
}
System.out.println(new Date());
}
};
t1.start();
try {
Thread.sleep(2000); // sleep for 2 seconds.
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.interrupt();
}
}
Thread t1 will only sleep for 2 seconds, since the main thread interrupts it. Keep in mind that this will interrupt many blocking operations such as IO.

Categories

Resources