I was wondering if there was a form of timer that I can use that doesn't pause all of my code Thread.sleep(ms) is not what I need because it pauses all of my code.
EDIT: Okay, I think I misworded that. Here's my edit:
Is there a way to measure a certain amount of time in Java without pausing my main method?
I like to using Executors class. It have a nice method that is newScheduledThreadPool. It gives you an ScheduledExecutorService instance, which have a lot of scheduling methods.
Check it out here here:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(threadToExecute, 10, TimeUnit.SECONDS);
This code will start threadToExecute thread after 10 seconds, without pausing your main thread.
Depends on which Frameworks you use. A pretty generic way would be to start a new Thread, pause that Thread via Thread.sleep(ms) and then do whatever you want to do after that delay, but of course that requires a little bit of care because of concurrency issues.
You might want to look into the Timer class. You can attach it to a thread, schedule events, and add delays. What you could do with this is you could create a thread to run along side your main thread and have it run from there. Because they will be on two completely different threads, you don't need to worry about them interfering with each other. To run the other thread, you could create a class that extends Thread and run it. Then use the Timer(String name) constructor to create a Timer for the thread.
Related
I am building simulator that run 1000(and more) clients, in each client i want to run task after X time, i tried TimerTask, the problem is that in each task(more than 1000) new thread is created.
Did there as any task timer without thread?
You can schedule multiple TimerTasks using a single Timer, they just can't run at the same time. Depending on your need, that may be good enough.
But, quoting the javadoc of Timer:
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.
If you want to simulate 1000(and more) clients acting simultaneously, you have to use Threads! Otherwise you would have a single Thread in which your definite logic specifies when what logic of what client is done - that really does not simulate the clients acting in parallel.
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
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.
The task I need to perform involves requesting some data from an external server, performing some (fairly lengthy) processing on the data, and then updating the GUI with the results of the processing. Because the server might be unresponsive, the task is well suited to a SwingWorker: the doInBackground() method gets the results, and then the done method updates the GUI.
I need this to happen once every few seconds. I know I can just use a while loop and Thread.sleep, and create a new SwingWorker after each sleep. But everything I've read frowns upon using loops and sleep. I'd like to use a timer but:
Using a swing timer seems counterproductive; since they run on the EDT, I would essentially have no reason to use SwingWorker's doInBackground method. If the server were not responsive, the GUI would be unresponsive.
Using a java.util.Timer seems a bit wasteful: it seems to create a background thread for the TimerTask(), and since I am just creating a SwingWorker to do the actual work, I'm essentially creating a background thread that creates another background thread.
Can anybody tell me what's the best solution? I'd like to stick with SwingWorker since it seems ideally suited to the task, but I would like to avoid using a while loop if I can help it.
Thanks
You could use a ScheduledExecutorService:
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
// get a scheduled executor service with one thread
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
// schedule the worker at an intervall of 5 seconds
scheduler.scheduleAtFixedRate(myWorker, 0, 5, TimeUnit.SECONDS);
I don't see why you couldn't use a Swing Timer to start a Swing Worker. What have you tried?
I think you're on the right track with SwingWorker. Now you need to look at its publish and process methods. As your processing progresses, you publish() an object from the background thread then the process() method is called on the Swing(EDT) thread so you can update the gui.
This way there aren't a bunch of timers and other threads to coordinate.
The javadocs have a straightforward example with prime numbers:
http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
How large is the set of data you are retrieving? If it is fairly small I would completely detach the task of fetching/processing and displaying.
Use some sort of in memory cache to hold the most recently processed set of data.
Use a javax.swing.Timer to update the GUI with the cached data.
Use a java.util.Timer to fetch the data from the database, process it and update the cache.
Be careful of synchronisation issues between the two times on your cache. You don't want your swing timer grabbing data at the same time as the other timer is updating it.
I have a thread that needs to be executed every 10 seconds. This thread contains several calls (12 - 15) to a database on another server. Additionally, it also accesses around 3 files. Consequently, there will be quite a lot of IO and network overhead.
What is the best strategy to perform the above?
One way would be to use the sleep method along with a while loop, but that would be a bad design.
Will a class similar to Timer be helpful in this case? Also, would it be better to create a couple of more threads (one for IO and one for JDBC), instead of having them run in one thread?
I find that a ScheduledExecutorService is an excellent way to do this. It is arguably slightly more complex than a Timer, but gives more flexibility in exchange (e.g. you could choose to use a single thread or a thread pool; it takes units other than solely milliseconds).
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
Runnable periodicTask = new Runnable() {
public void run() {
// Invoke method(s) to do the work
doPeriodicWork();
}
};
executor.scheduleAtFixedRate(periodicTask, 0, 10, TimeUnit.SECONDS);
One option is to create a ScheduledExecutorService to which you can then schedule your job:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
ex.scheduleWithFixedDelay(...);
If you did decide to have multiple threads, then you can create a ScheduledExecutorService with more threads (again, via the Executors class).
In terms of how many threads and what you put in each thread, in terms of performance, I'd say this depends on:
for your particular application, can one thread genuinely "do work" while another one is waiting for I/O?
would your multiple threads ultimately "thrash the same resource" (e.g. read from files in different locations on the same dsk) and thus slow one another down, or would they be simultaneously hitting different resources?
Have a look at the Timer and TimerTask classes. They are exactly what you want.
You can make a TimerTask implementation that takes your thread object in a constructor.
The run method will then call the threads run method.
// Perhaps something like this
Timer t = new Timer();
t.scheduleAtFixedRate(yourTimerTask, 0, 10 * 1000);
// Hopefully your task takes less than 12 seconds