Doing a Timed action without Interrupting the Main Thread - java

I have a Thread that needs to continuously run, however when a certain action is called, I want to wait 500ms, and then do another action, without interrupting the main Thread. Is there any way to do so?
I immediately thought of creating an just restarting a new Thread each time, but this doesn't seem to work.
EDIT: There seems to be a confusion with the question, so let me elaborate. I have a thread that is contiously working. When and action is preformed, a method is called. In that method I need to wait for 500ms and then call another method, without interrupting the main thread. This also has to be re-usable.

Quartz is an scheduler that allows you to:
... create simple or complex schedules for executing tens, hundreds,
or even tens-of-thousands of jobs; jobs whose tasks are defined as
standard Java components that may execute virtually anything you may
program them to do. The Quartz Scheduler includes many
enterprise-class features, such as support for JTA transactions and
clustering.
You can implement scheduled jobs to run in a certain given time. Here you can find some tutorials and more info:
http://quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/

This might give you the idea of how to handle similar situations:
How to Pause and Resume a Thread in Java from another Thread

Related

RunLater on current thread or give a task to current thread to run later

I want to achieve what Platform.runLater() does but on the current thread and the program isn't related to JavaFX, it's a Tomcat server.
I tried to do Platform.runLater(this::foo); but I'm pretty sure it doesn't do anything. Probably because there's no JavaFX thread to do it.
I'd rather not open a ScheduledExecutorService because it's going to be another thread on many instances (so many threads), not to mention the method it would need to run is synchronized so I smell a deadlock.
I couldn't find any useful methods on Thread.currentThread() (run and start don't take parameters).
Is there another option to do this?
I used a newSingleThreadExecutor to achieve this, since it can take multiple runnables to a queue and run them sequentially, it can be given tasks from several places and it will run them one by one, it's similar to platform.runLater.
Having a single thread that all instances of the class hold a reference to, solves the "many threads" problem.
It also won't cause a deadlock because it will at most wait for just one other thread to finish the synchronized function and then run just this one function.

Two short-lived threads vs. Executor

I have only two short-lived tasks to run in the background upon the start of the application. Would it make sense to use a thread for each task or an Executor, for instance, a single thread executor to submit these two tasks.
Does it make sense to create two threads that die quickly as opposed to having a single threaded executor waiting for tasks throughout the lifecycle of the application when there are none?
One big benefit of using a threadpool is that you avoid the scenario where you have some task that you perform repeatedly then, if something goes wrong with that task that causes the thread to hang, you're at risk of losing a thread every time the task happens, resulting in running the application out of threads. If your threads only run once on startup then it seems likely that risk wouldn't apply to your case.
You could still use Executor, but shut it down once your tasks have both run. It might be preferable to use Futures or a CompletionService over raw threads.
If you do this more than once in your application, ThreadPoolExecutor is definitely worth a look.
One benefit is the pooling of threads. This releaves the runtime to create and destroy OS objects every time you need a thread. Additionally you get control of the amount of threads spawned - but this seems not the big issue for you - and threads running/done.
But if you actually really only spawn two threads over the runtime of your application, the executors may be oversized, but they are nevertheless very comfortable to work with.
Since Nathan added Futures, there is also Timer and TimerTask. Also very convenient for "Fire and Forget" type of background action :-).

Excecuting two Async Tasks parallely at the same time ( Do i really need this?)

I read probably every tutorial and every forum discussion on that subject but still can't make it happen! and it is very frustrating.
it seems that the way to do it is to use executeOnExecutor() method with - AsyncTask.THREAD_POOL_EXECUTOR, and so i did in my code. but still,the second task only beeing executed only after the first one has finished and not in the same time.
My min sdk version is 2.3 and the maximum is 4.2, so i did the check:
if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.HONEYCOMB) {
engine.setEnginesTurn(true);
engineThread = new EngineThread(board,engine,activity,boardView);
rt = new RotateTask(boardView);
engineThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
rt.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else{
engine.setEnginesTurn(true);
engineThread = new EngineThread(board,engine,activity,boardView);
rt = new RotateTask(boardView);
engineThread.execute();
rt.execute();
}
Ignore the boolean variable here..it is not relevant,and also the other code since you wondered why i didn't post it. it is a mess but all working just fine,execpt for the execution of the two tasks. what am i doing wrong?
The reason i want the two tasks running parallely is: the first tasks is a computation task and the other one is a custom Hourglass image rotating animation while the computer is thinking (Its a game app).
EDIT: Ah.. and just wanted to include that i don't do the animation on the main UI thread is because i use sleep() for the animation ,so can't freeze the main thread.
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
So for parallel execution you can't use asynctask. The above is quoted from the doc. So for parallel execution i suggest you look at executor.
http://developer.android.com/reference/java/util/concurrent/Executor.html
It sounds like you are modifying the UI from the background thread in your AsyncTask. This is not thread safe and is probably causing the problem.
Keep your computation task on a separate thread and move your animation back onto the UI thread and (unless I am missing something) that should do the trick. Remember that anything that is drawn to the screen must be published on the main UI thread.
Just too much text. Please remove, there is a lot that is not needed.
Your design is complex, simplify it.
Why dont you just start 2 Async Tasks. Why have 2 jobs in 1 async task ? In one async task you can do your background thingy, and the other async task in the Pre and Post you can start your animation and stop your animation.

Java Concurrency design

Here is what I want to do:
There are many threads start at any time, and each thread will run about 5s. When one thread is running, others must wait. And when the running thread ends, the newest thread start to run and other waiting threads just stop.
Of course, there will be situations: when one thread start, there's no other thread.
I tried to use FutureTask, but failed. It seems too complex for me.
Can anyone give me some idea?
you might want to take a look at single-threaded executor, which will take your tasks from task queue and invoke them sequentially.
it is more convenient to use this class if you will decide later to add some concurrency

Regarding stopwatch or timer or some other utility

I have a requirement to start a task..Now many threads can start this task and this task normally takes 4-5 seconds to complete. I want to prevent the starting of a task if this task has been already started by some other thread.
In order to implement this requirement, I am thinking of starting a timer or stopwatch in a different thread whenever the task is started by some thread. Now when the timer times out after a configured time-interval, another thread can starts a task.
So, is starting a timer or stopwatch in a different thread to see if the particular time has been reached is a good solution?Is there any good alternative for it?
If I understand correctly, this is a bad idea. Basically you are assumming your job will never run for more than 5 seconds so if the watch tells you that some job was started less than 5 seconds ago, you won't start another one. This is very unreliable.
Instead create some sort of flag that you set when job starts and unset when ends. AtomicBoolean is perfect for that:
private AtomicBoolean flag = new AtomicBoolean();
//...
if(!flag.getAndSet(true)) {
try {
//do your work
} finally {
flag.set(false);
}
} else {
//Already running
}
If you want another job to wait for the previous one instead of simply being discarded, just surround your task with synchronized or use some different locking mechanism.
Note: if your jobs are distributed you will need a distributed locking mechanism, like a databasse or hazelcast.
If you are trying to do this in java then you can consider using a synchronized block on the Object Oriented approach on JAVA.
So any task that you want to make sure is done by one thread at a time then make a class and a synchronized method in that class, also make sure you all the threads share the same object of the class and call this method in which they want to perform the task.
For Example
Class SyncTask{
synchronized void task1(){
//Perform your task here
}
}
Create the object of this class once during the lifetime of your application and then use this same object across all the threads and let them call this method to which you want to perform your task.
In the case of multiple threads invoking this method at the same time. JVM will take care of the sequence and if one thread is already performing a task, the others calling it will wait for the first one to finish.
In this way you will be sure that only on thread is performing the task at any given time.
I hope this helps.
If you want to schedule task the framework of choice is usually something similar to Quartz. It should allow you to do what you need and more. Regarding the issue of non running concurrent tasks, I would recommend you take a look at this previous SO post which should point you in the right direction.

Categories

Resources