I have a two functions, one is the master and the other is the slave. Via master function I'm trying to learn behaviour of the other function. But I should do whatever calculation is a setted time interval. In this part, how can I set a timer, which is marked a boolean variable if timeout occur, and learn whether timeout occurs ?
func1 -----send message------> func2
start timer
if timeout occur, do something else
You can execute func2 in another Thread and let your original Thread join() with a specified timeout.
Of course you will need to take care of proper synchronization.
Simple example (left out InteruptedException handling)
void func1(){
Thread slave = new Thread(new Runnable(){
public void run(){
func2();
}
});
slave.start();
slave.join(100); // waits 100 milliseconds for slave to complete
if(!slave.isAlive()){
//slave completed its task
}else{
//slave not done yet, do something else
somethingElse();
}
}
Use the concurrent constructs in the JDK. In this case an ExecutorService and a CountDownLatch is a perfect match:
ExecutorService executor = Executors.newCachedThreadPool();
final CountDownLatch ready = new CountDownLatch(1);
executor.execute(new Runnable() {
#Override
public void run() {
// do something here
System.out.println("working ...");
ready.countDown();
}
});
boolean timeout = !ready.await(1, TimeUnit.MILLISECONDS);
if (timeout) {
doSomethingElse();
}
Related
I have a thread which executes code periodically, e. g. every 10 seconds. I'd like to have the option to also invoke the same code in a spontaneous way and not have to wait 10 seconds. But the code of the automatic and spontaneous execution must never run concurrently, instead they should run in sequence if the user presses the execute button while the thread is invoking the same method.
Does anyone know a good pattern or even a class that can address this kind of requirement?
First thing that comes to mind would be to make the work method synchronized. But in that case the manual execution (e. g. button press) is blocked and has to wait until the method in the thread is finished. Is there a better approach without blocking?
Example:
public class Executor extends Thread {
// endless loop, executes work method periodically with pause inbetween
#Override
public void run() {
while( true) {
work( "automatic");
pause(10000);
}
}
// Working method that's executed periodically or manually
private synchronized void work( String text) {
System.out.println( "Working " + text + " " + System.currentTimeMillis());
}
// helper method that pauses the thread
private static void pause( long sleepMs) {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// start automatic execution
Executor executor = new Executor();
executor.start();
// pause a while
pause(1000);
// manual execution
executor.work( "manual");
}
}
Edit: Solution for my requirement:
public class ScheduledExecutor {
public static void main(String[] args) throws InterruptedException {
ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
executor.scheduleWithFixedDelay(new Work("auto"), 0, 10, TimeUnit.SECONDS);
Thread.sleep(1000);
executor.execute(new Work("manual"));
}
public static class Work implements Runnable {
String text;
public Work(String text) {
this.text = text;
}
#Override
public void run() {
System.out.println("Working " + text + " " + System.currentTimeMillis());
}
}
}
I would create a new, single-thread executor service:
ExecutorService executorService = Executors.newFixedThreadPool(1);
Then, I would set up a timer that feeds the executorService a task once every 10 seconds.
new Timer(10000, new ActionListener {
public void actionPerformed(ActionEvent evt) {
executorService.execute(() -> doWhatever());
}
}).start();
Finally, you can call executorService.execute(() -> doWhatever()); in your button press handler, or wherever else you want in your code.
Only one activation of doWhatever() will run at a time because the executorService has only one thread on which to run them. And, your button press handler will never have to wait, because it does nothing but put a new object on a queue.
I have a thread which executes code periodically, e. g. every 10 seconds. I'd like to have the option to also invoke the same code in a spontaneous way and not have to wait 10 seconds.
A simple way to do this in your code is not to pause by using Thread.sleep(...) but rather do wait(...). Then whenever you want the command to wakeup and run manually it just does a notify().
So you code would look something like:
while( true) {
work( "automatic");
synchronized (this) {
try {
// wait for a bit but allow someone else to awake us to run manually
wait(10000);
} catch (InterruptedException ie) {
// always a good pattern
Thread.currentThread().interrupt();
return;
}
}
}
Then when you want to have it run manually you do:
synchronized (executor) {
executor.notify();
}
The notify will awaken the thread immediately so that it can run it's task. The work method then does not need to be synchronized because only the Executor thread is running it.
NOTE: As pointed out by #shinobi, using wait() like this could suffer from spurious wake-ups which can happen with certain OS thread implementations.
Lastly, it is a better practice to make Executor implement Runnable as opposed to extending Thread.
Share a semaphore between the server thread (the one that executes the task) and client threads (the ones that need to trigger immediate execution):
Semaphore sem = new Semaphore( 0 );
The server thread needs to execute the following code (note that it's an endless loop — you'll likely want to plug-in your program termination check as the condition to while()):
while( true ) {
try {
sem.tryAcquire( 10, TimeUnit.SECONDS );
} catch( InterruptedException e ) {
continue;
}
runTask();
sem.drainPermits();
}
Then, in order to trigger immediate execution, the client thread needs to do:
sem.release();
Thus, the server thread will execute the task upon either acquiring a permit from the semaphore as soon as a client thread releases one (triggered immediate execution,) or timing-out in Semaphore.tryAcquire() (periodic executions 10s apart, end-to-start.) Having executions 10s apart start-to-start will take some slightly more involved logic, as well as keeping track of last execution's starting time, but the basic idea remains the same.
You need to drain the permits each time in order to avoid multiple back-to-back executions of the task, in cases where it might be triggered for immediate execution while still being executed.
I need few of the functions in my program to run simultaneously. These processes returns records. But, the output of one is the input to the other. In such a case, if at a point of time function A takes some time to output some record to the function B, I need to the function B to wait till function A provides some records as input for this process. Can I achieve this simply by using the thread functionalities such as wait, join, etc.. Or Is there any other ways to achieve the same functionality.
Edited:
As per the below mentioned suggestions, If I use the producer-consumer algorithm with BlockingQueue,ExecutorService, Future and CountDownLatch, Can I achieve every functionalities I requested?
As mentioned above you can use blocking queue with producer consumer
OR
You can use countdown latch of the java concurrency to solve your problem.
How CountDownLatch works?
CountDownLatch.java class defines one constructor inside:
//Constructs a CountDownLatch initialized with the given count.
public void CountDownLatch(int count) {...}
This count is essentially the number of threads, for which latch should wait. This value can be set only once, and CountDownLatch provides no other mechanism to reset this count.
The first interaction with CountDownLatch is with main thread which is goind to wait for other threads. This main thread must call, CountDownLatch.await() method immediately after starting other threads. The execution will stop on await() method till the time, other threads complete their execution.
Other N threads must have reference of latch object, because they will need to notify the CountDownLatch object that they have completed their task. This notification is done by method : CountDownLatch.countDown(); Each invocation of method decreases the initial count set in constructor, by 1. So, when all N threads have call this method, count reaches to zero, and main thread is allowed to resume its execution past await() method.
Below is a simple example. After the Decrementer has called countDown() 3 times on the
CountDownLatch, the waiting Waiter is released from the await() call.
CountDownLatch latch = new CountDownLatch(3);
Waiter waiter = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch);
new Thread(waiter) .start();
new Thread(decrementer).start();
Thread.sleep(4000);
public class Waiter implements Runnable{
CountDownLatch latch = null;
public Waiter(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Waiter Released");
}
}
public class Decrementer implements Runnable {
CountDownLatch latch = null;
public Decrementer(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In your case you can use callable to create thread instead of runnable as you need to get the retrun value from one thread and have to pass that value to second thread.
In most cases you do not need to use wait etc. All you need to do is choose a good safe structure to use to communicate between your threads,
In this specific case I would suggest one of the concurrent queuue implementations, perhaps a BlockingQueue such as ArrayBlockingQueue.
Java's Fork and Join looks suitable for the usecase specified in your Question.
See http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
Have a look at BlockingQueue classes and producer/consumer patterns.
The first thread is getting the work unit from an input blocking queue and putting its output to an output blocking queue (with size restrictions).
The second thread is doing the using this output queue as an input.
With this method you can also easialy adjust the number of threads.
Ensure the the work load per work unit is not to small.
This is similar to producer-consumer problem. You can use Java's BlockingQueue.
The process A will enqueue its results and the process B will wait until A's output is ready in the queue. When output of A is available, then B can read and consume it.
This looks like the consumer-producer-problem. As suggested by others you can use a BlockingQueue. Here is an example for how to use it:
public static void main(final String[] args) {
final ExecutorService producer = Executors.newSingleThreadExecutor();
final ExecutorService consumer = Executors.newSingleThreadExecutor();
final BlockingQueue<Integer> workpieces = new LinkedBlockingQueue<>();
producer.submit(new Runnable() {
#Override
public void run() {
final Random rand = new Random();
for (;;) {
try {
workpieces.put(rand.nextInt());
Thread.sleep(1000);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
});
consumer.submit(new Runnable() {
#Override
public void run() {
for (;;) {
try {
System.out.println("Got " + workpieces.take());
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
});
}
It generates a random number every second in the producer-thread which is printed by the consumer-thread.
You can use BlockingQueue between producer and consumer threads. The producer will keep on adding results to queue if it is not full, concurrently the consumer thread can process pending messages from queue.
I can not use Executor and Future for trapping TimeOutException as it is 1.4
I need to timeout after 30 seconds if method is not complete.
//Caller class
public static void main() {
EJBMethod() // has to timeout after 30 seconds
}
//EJB method in some other class
public void EJBMethod() {
}
An approach that I am thinking is to wrap this method call in a Runnable and set some volatile boolean from run() after method is over. THen , in caller, we can sleep for 30 seconds after calling that method and once woke up, I will check the boolean in caller if it is SET. If not set, then we need to stop that thread.
In the simplest case, you could just go with a Thread + an arbitrary Runnable.
If you want to make the call blocking from the perspective of the caller, you can create a "service" class that runs a worker thread and uses Thread.join(long) to wait for the operation to complete or abandon it after the specified timeout (Pay special attention to the proper handling of InterruptedException so things don't get messed up).
Thread.isAlive() will tell you whether the Thread finished or not.
Retrieving the result is a separate concern; I guess you can deal with that...
[EDIT]
Quick-and-dirty example (do not use in production as is!):
/**
* Actually needs some refactoring
* Also, did not verify for atomicity - should be redesigned
*/
public V theServiceCall(final T param) {
final MyResultBuffer<V> buffer = new MyResultBuffer<V>();
Runnable task = new Runnable() {
public void run() {
V result = ejb.process(param);
buffer.putResult(result);
}
}
Thread t = new Thread(task);
t.setDaemon(true);
t.start();
try {
t.join(TASK_TIMEOUT_MILLIS);
} catch (InterruptedException e) {
// Handle it as needed (current thread is probably asked to terminate)
}
return (t.isAlive()) ? null : buffer.getResult();
}
NOTE: Instead of Thread.setDaemon() you can implement a shutdown flag in your Runnable as it would be a better solution.
[/EDIT]
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.
I have a processing loop of the form
while (true) {
doWork();
Thread.sleep(SLEEP_INTERVAL);
}
I want to make a Runnable out of this that can play well with ExecutorService and which will exit when ExecutorService.shutdownNow() is called.
I'm looking to write it this way:
public WorkerTask implements Runnable
{
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
doWork();
try {
Thread.sleep(SLEEP_INTERVAL);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
Simple testing shows it at least appearing to work in that the task gets interrupted and will exit and the ExecutorService will shut down, and appears to do so whether the interrupt arrives while doWork() is processing or during the sleep. (By varying how much work doWork() does and how big SLEEP_INTERVAL is I can pretty much control where the interrupt happens).
But when I google I see examples using Thread.interrupted() as well as Thread.currentThread().isInterrupted(). I understand that the former clears the interrupted flag while the latter leaves it, but is there any other difference I need to care about?
I also see versions where the result of Thread.currentThread().isInterrupted() or Thread.interrupted() is stored in a volatile variable and that variable is used as the while loop test condition. Is that just a style or is there a need to do that? In what I've written do I have to worry that somehow something can clear the interrupt flag between when it is set (whether by being received when the thread is live, or by my catching InterruptedException and reasserting the flag) and when Thread.currentThread().isInterrupted() is called in the loop test?
Your code looks fine to me. Introducing an additional volatile variable would be unnecessary complexity: the interrupt status does the job.
The recommended way, in Java Concurrency in Practice, to deal with interrupts in tasks is to either throw an InterruptedException (this is doable if the task is a Callable and not a Runnable), or to make sure the interrupt status is set and to exit from the task ASAP. Your code does that well.
Could you take a look at ScheduledExecutorService if it matches your requirements:
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}}
Basically you should take advantage of java.util.concurrent libraries here .You should submit your task via ExecutorService.submit()and then call blocking methods like Future.get() , then you can be sure that those methods will respond to interruption as soon as possible by throwing an ExecutionException() .You probably should get rid of that Thread.sleep() since it is doing nothing . You want to sniff an interrupt as quickly as possible .You possibly also want to wait for a timeout in case your task is doing something inifinitely . So if the task terminates with a TimeOutException , the task is cancelled via its Future.
I call cancel() unconditionally since cancelling a completed task has no effect.
In that case you can do some thing like :
public static void main(String[] args) {
WorkerTask runnable;
TimeUnit unit;
Future<?> task = executor.submit(workerTask);
try{
task.get(timeout,unit);
} catch(TimeoutException e){
}catch(ExecutionException e){
throw e.getCause();
} finally{
//Harmless if the task already completed
task.cancel(true);
}
}
}