Run a class instance as a thread by itself - java

I have this piece of code:
Timeout s = new Timeout();
Timer timer = new Timer();
timer.schedule(s, 1000L); // fires after 1 second
How can I launch the following piece of code as a thread by itself? Would I need to pass the timer and Timeout to a Runnable and then start it? What happens if the thread's Run() ends before the timer is fired?
I am thinking of doing this instead:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
Timeout s = new Timeout(); // Timeout is a runnable
ses.schedule(s, 10, TimeUnit.SECONDS);
but how do I exit the thread after the timeout? I run out of thread after a while
Thanks

I'm not exactly sure what you're asking, but I'll give it a shot.
How can I launch the following piece of code as a thread by itself?
In short...
Timeout.java
public class Timeout extends TimerTask {
boolean isDone = false;
#Override
public void run() {
// TODO something
synchronized(this) {
isDone=true;
this.notifyAll();
}
}
public synchronized void join() throws InterruptedException {
while(!this.isDone)
this.wait();
}
}
TimeoutRunner.java
public class TimerRunner implements Runnable {
#Override
public void run() {
Timeout timeout = new Timeout();
Timer timer = new Timer();
timer.schedule(timeout, 1000L);
try {
timeout.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
timer.cancel();
}
}
}
Run the TimeoutRunner using:
new Thread(new TimeoutRunner()).start();
The join method will block the thread until the timeout task has completed execution. At that time you can close the Timer. This is, however, a lot of thread creation, and IMO bad programming.
When you create a Timer instance, a thread is created to execute the Timeout#run() method. The timer has it's own run method that blocks until your task is ready for execution. After the given timeout period elapses, the timer unblocks and executes your timeout.
Your TimeoutRunner thread will block until the timeout operation completes. Only then can this thread die.
The Timer class is very limited. You need to create a new instance for every task. In my option, the ScheduledExecutorService is a better option. Keep the ScheduledExecutorService open for as long as you plan on executing tasks. If you need something like a scheduled cached thread pool, feel free to use this class from one of my open-source projects (Scheduler). This works great with a cached thread pool.

Related

How to make a thread accessible from another thread in java?

I have two thread, taskThread, a thread with a long-running task, and a timerThread, a recurrent timer every n milliseconds. I am trying to trigger any function call on taskThread from timerThread.
#Override
public Task<List<Schedule>> createTask() {
return new Task<List<Schedule>>() {
#Override
protected List<Schedule> call() throws Exception {
Task currentTask = this;
Thread taskThread = Thread.currentThread(); //Thread-1,Task thread
Timer checker = new Timer();
checker.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
if(currentTask.isDone()) cancel();
System.out.println("Task thread "+taskThread+" is : "+taskThread.getState());
System.out.println("Timer thread" + Thread.currentThread()+" is : "+Thread.currentThread().getState());
taskThread.wait(); //throws IllegalMonitorStateException
Thread.sleep(300);
Thread.currentThread().notifyAll();
} catch (InterruptedException ex){
System.out.println(ex);
}
}
},0,500);
List<Schedule> result = solveMakespan(this); //Blocking call
checker.cancel(); //cancel timer
return result;
}
};
}
The scenario I am trying to achieve, is making the taskThread wait for the timerThread before continuing, I read about synchronized blocks but I am not sure how to make the timer block acquire the lock since the solveMakespan is declared outside its thread, and declaring it inside the timer would make it execute multiple times.
EDIT : Concerning the nuance about "accessing the task's thread", I'd like to either be able to call .wait() or join() on the Thread that I want to wait from the Timer thread, or for the Task instance to provide a method that would run on its existing thread, but triggerable from the timer instance. The code snippet should hopefully make the goal I'm trying to achieve clear.

Java how to timeout a thread WITHOUT using future.get and without blocking parent thread

I am looking for ways to time out a thread execution and found below example: https://stackoverflow.com/a/16231834/10015830
Future<?> future = service.submit(new MyCallable());
try {
future.get(100, TimeUnit.MILLISECONDS);
} catch (Exception e){
e.printStackTrace();
future.cancel(true); //this method will stop the running underlying task
}
But my need is different from above example: I do not want the parent thread to be blocked at future.get. In other words, I do not need to get the result of my callable. Because in my actual application, the parent thread is executed periodically (a scheduled task, say, 5 sec periodically).
Is there a way timeout a thread WITHOUT using future.get and without blocking parent thread? (It seems invokeAll is also blocking).
You can cancel long running task from a timer task:
import java.util.Timer;
import java.util.TimerTask;
Timer timer = new Timer();
Future<?> future = service.submit(new MyCallable());
TimerTask controlTask = new TimerTask(){
#Override
public void run() {
if (!future.isDone()) {
future.cancel(true);
}
}
};
long delay = 100;
timer.schedule(task, delay);

How do I schedule a task to run once?

I want to delay doing something, along the lines of setting a countdown timer that will "do a thing" after a certain amount of time.
I want the rest of my program to keep running while I wait, so I tried making my own Thread that contained a one-minute delay:
public class Scratch {
private static boolean outOfTime = false;
public static void main(String[] args) {
Thread countdown = new Thread() {
#Override
public void run() {
try {
// wait a while
System.out.println("Starting one-minute countdown now...");
Thread.sleep(60 * 1000);
// do the thing
outOfTime = true;
System.out.println("Out of time!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
countdown.start();
while (!outOfTime) {
try {
Thread.sleep(1000);
System.out.println("do other stuff here");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
While this worked, more-or-less, it seemed like there should be a better way of doing this.
After some searching, I found a bunch of questions like these but they don't really address what I'm trying to do:
How do I schedule a task to run at periodic intervals?
How i can run my TimerTask everyday 2 PM
How to run certain task every day at a particular time using ScheduledExecutorService?
Java execute task with a number of retries and a timeout
I don't need anything this complicated; I just want to do a single thing after a certain amount of time while letting the rest of the program still run.
How should I go about scheduling a one-time task to "do a thing"?
While the java.util.Timer used to be a good way to schedule future tasks, it is now preferable1 to instead use the classes in the java.util.concurrent package.
There is a ScheduledExecutorService that is designed specifically to run a command after a delay (or to execute them periodically, but that's not relevant to this question).
It has a schedule(Runnable, long, TimeUnit) method that
Creates and executes a one-shot action that becomes enabled after the given delay.
Using a ScheduledExecutorService you could re-write your program like this:
import java.util.concurrent.*;
public class Scratch {
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
System.out.println("Starting one-minute countdown now...");
ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
#Override
public void run() {
// do the thing
System.out.println("Out of time!");
}}, 1, TimeUnit.MINUTES);
while (!countdown.isDone()) {
try {
Thread.sleep(1000);
System.out.println("do other stuff here");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
scheduler.shutdown();
}
}
One of the nice things you get by doing things this way is the ScheduledFuture<?> object you get back from calling schedule().
This allows you to get rid of the extra boolean variable, and just check directly whether the job has run.
You can also cancel the scheduled task if you don't want to wait anymore by calling its cancel() method.
1See Java Timer vs ExecutorService? for reasons to avoid using a Timer in favor of an ExecutorService.
Thanks it worked for me. I used scheduler to schedule a task at a batchinterval calculated at runtime.
manualTriggerBatchJob.setSchedulingProperties(pblId, batchInterval);
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(5);
#SuppressWarnings("unchecked")
ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(manualTriggerBatchJob,
batchIntervalInMin,TimeUnit.MILLISECONDS);

Multithreading concept

I am learning multi-threading concepts now. I can run a single thread with the help of handler and Runnable(). I want my code to run two threads, say Thread1 runs method1() and thread2 runs method2(). Thread1 should run for 2seconds and then sleep for 1second. In the mean time, thread2 should wakeup and run for 1second. Again, thread1 should run for 2seconds. This process should be done continuously. I am doing this in Android.
The question might look straight forward, but I have no other way, other than posting a question here, as I have gone through many tutorials and questions in this website. No post suits my context. Any suggestions will be appreciated. Thanks in advance.
You can do this by using ScheduledThreadPoolExecutor, with which you can achieve parallel execution of your tasks. A small sample example to schedule the tasks:
//creates a thread pool of size 2
int poolSize = 2;
// creates ScheduledThreadPoolExecutor object with number of thread 2
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(poolSize);
//starts executing after 1 second
ScheduledFuture<Callable-Type> sf = stpe.schedule(new TaskOne(), 1,TimeUnit.SECONDS);
//starts executing after 2 seconds
ScheduledFuture<Callable-Type> sf1 = stpe.schedule(new TaskTwo(), 2,TimeUnit.SECONDS);
And you can define your tasks as below:
class TaskOne implements Callable<Callable-Type> {
#Override
public Callable-Type call() throws Exception {
//DO YOUR WORK HERE
return callable-type;
}
}
class TaskTwo implements Callable<Callable-Type> {
#Override
public Callable-Type call() throws Exception {
//DO YOUR WORK HERE
return callable-type;
}
}
The advantages of using ScheduledThreadPoolExecutor over Timer are :
A Timer creates only a single thread for executing timer tasks. Scheduled
thread pools address this limitation by letting you provide multiple threads for executing deferred and periodic tasks.
Another problem with Timer is that it behaves poorly if a TimerTask throws an unchecked exception. The Timer thread doesn't catch the exception, so an unchecked exception thrown from a TimerTask terminates the timer thread.
Ref: Java Concurrency in Practice
Sample
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code
}
});
}
}, 2000, 1000); // 2000 is delay and 1000 is call period
There is also another schedule() methods that you can use to map your criteria.

Timer in Java Thread

I have a thread which is in charge of doing some processes. I want make it so that these processing would be done every 3 seconds. I've used the code below but when the thread starts, nothing happens.
I assumed that when I define a task for my timer it automatically execute the ScheduledTask within time interval but it doesn't do anything at all.
What am I missing?
class temperatureUp extends Thread
{
#Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
increaserTimer.schedule(increaseTemperature, 3000);
}
};
A few errors in your code snippet:
You extend the Thread class, which is not really good practice
You have a Timer within a Thread? That doesnt make sense as the a Timer runs on its own Thread.
You should rather (when/where necessary), implement a Runnable see here for a short example, however I cannot see the need for both a Thread and Timer in the snippet you gave.
Please see the below example of a working Timer which will simply increment the counter by one each time it is called (every 3seconds):
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
System.out.println("TimerTask executing counter is: " + counter);
counter++;//increments the counter
}
};
Timer timer = new Timer("MyTimer");//create a new Timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//this line starts the timer at the same time its executed
}
}
Addendum:
I did a short example of incorporating a Thread into the mix. So now the TimerTask will merely increment counter by 1 every 3 seconds, and the Thread will display counters value sleeping for 1 seconds every time it checks counter (it will terminate itself and the timer after counter==3):
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
static Timer timer;
public static void main(String[] args) {
//create timer task to increment counter
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
// System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
};
//create thread to print counter value
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
System.out.println("Thread reading counter is: " + counter);
if (counter == 3) {
System.out.println("Counter has reached 3 now will terminate");
timer.cancel();//end the timer
break;//end this loop
}
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
timer = new Timer("MyTimer");//create a new timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//start timer in 30ms to increment counter
t.start();//start thread to display counter
}
}
import java.util.Timer;
import java.util.TimerTask;
public class ThreadTimer extends TimerTask{
static int counter = 0;
public static void main(String [] args) {
Timer timer = new Timer("MyTimer");
timer.scheduleAtFixedRate(new ThreadTimer(), 30, 3000);
}
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
}
In order to do something every three seconds you should use scheduleAtFixedRate (see javadoc).
However your code really does nothing because you create a thread in which you start a timer just before the thread's run stops (there is nothing more to do). When the timer (which is a single shoot one) triggers, there is no thread to interrupt (run finished before).
class temperatureUp extends Thread
{
#Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
//start a 3 seconds timer 10ms later
increaserTimer.scheduleAtFixedRate(increaseTemperature, 3000, 10);
while(true) {
//give it some time to see timer triggering
doSomethingMeaningful();
}
}
I think the method you've used has the signature schedule(TimerTask task, long delay) . So in effect you're just delaying the start time of the ONLY execution.
To schedule it to run every 3 seconds you need to go with this method schedule(TimerTask task, long delay, long period) where the third param is used to give the period interval.
You can refer the Timer class definition here to be of further help
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
Timer & TimerTask are legacy
The Timer & TimerTask classes are now legacy. To run code at a certain time, or to run code repeatedly, use a scheduled executor service.
To quote the Timer class Javadoc:
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
Executor framework
In modern Java, we use the Executors framework rather than directly addressing the Thread class.
Define your task as a Runnable or Callable. You can use compact lambda syntax seen below. Or you can use conventional syntax to define a class implementing the Runnable (or Callable) interface.
Ask a ScheduledExecutorService object to execute your Runnable object’s code every so often.
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor() ;
Runnable task = () -> {
System.out.println( "Doing my thing at: " + Instant.now() );
};
long initialDelay = 0L ;
long period = 3L ;
TimeUnit timeUnit = TimeUnit.SECONDS ;
scheduledExecutorService.submit( task , initialDelay, period , timeUnit ) ;
…
scheduledExecutorService.shutdown() ; // Stops any more tasks from being scheduled.
scheduledExecutorService.awaitTermination() ; // Waits until all currently running tasks are done/failed/canceled.
Notice that we are not directly managing any Thread objects in the code above. Managing threads is the job of the executor service.
Tips:
Always shutdown your executor service gracefully when no longer needed, or when your app exits. Otherwise the backing thread pool may continue indefinitely like a zombie 🧟‍♂️.
Consider wrapping your task's working code in a try-catch. Any uncaught exception or error reaching the scheduled executor service results in silently halting the further scheduling of any more runs.

Categories