Is it possible in java to make the program to sleep or wait for a particular time peroid ?
As in C++ we do delay(1000);.
I am writing a java applet which does not include threads, but I want it to delay the execution of some statements. Its a clock(Digital) applet. so I need to make part of my applet code to delay for 1 second.
You don't want to do that. sleeping for a second in the Event Dispatching Thread will prevent any event processing during that time. One second may not be that much, but in general this is not a good practice.
What you want to do is setup a timer with a 1s period.
Yes. It is possible. Do a little research into the Thread.sleep() method as well as Timers as well as...
Related
I am writing a simple application for practice that I want to show a message every N minutes and then sleep for a while.
My question here: what are the most efficient ways of designing applications that have this functionality: sleep for a while and then wake up and do something. I am a student and at school we write applications with threads and after writing a basic kernel I understand some basics of scheduling and time slicing.
My goal is to better understand how to write a small program that has a very small footprint (and how to reach that small footprint in this small example), but can run for weeks.
I can use Thread.sleep(N) in Java or equivalent. But that has does not guarantee precision of sleep and in fact (from what I read), might not sleep nowhere near N seconds. Articles like this seem to discourage sleep().
I thought about creating a thread that I can signal to wake up every N seconds. But then the main() thread will be constantly working and counting time. That's also very wasteful since I'd be wasting cycles on counting time.
I guess ideally I want the process to not run for N minutes and then wake up (by OS) after some number of time slices, but I am not sure there is another way of doing it besides sleep(). I am writing it in Java, but I could go with C or Python if those can do better (I feel that shouldn't matter). I am still researching, but I thought I'd get a hint from the community as well.
The program is a simple reminder that tells me to stretch and use a standing desk. :) Understanding threading a bit better is the actual goal.
The comments around Thread.sleep are really about more precision than your usecase entails, IMO. Thread.sleep should be precise enough for your needs. You could look at a ScheduledThreadPoolExecutor which gets you out of the some of the nitty gritty thread management, which is an easy thing to get wrong as a program grows in complexity.
Sleeping a thread is most of the cases a bad way to desing an application, in java there are Timers that you can define to execute a taks periodically. look like:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
doStuff();
}
}, <delay>, <period>);
Check out the java Timer and TimerTask classes in the docs
Well, From application perspective as you mentioned you can use the Thread.sleep(N).
However the accuracy totally relied on the underlying machine.
(Read the docs on http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#currentTimeMillis())
You can also use this SOF to get more options : http://stackoverflow.com/questions/824110/accurate-sleep-for-java-on-windows
on the under relying machine.
In my application I have a main frame window GUI, that launches a task in an executor service.
The submitted task generates output and stores in a file on Disk.
As soon as the o/p is generated GUI (observer) is informed of the o/p generated.
Here the problem is I am keeping a wait loop inside the main frame and as soon as a notification is received, the main panel is repainted on the main frame.
For small tasks this works fine, but as the size of the threaded task increases. The wait loop time increases and the GUI main window turns black till computations are done.
Can you please help me in correcting the design. Also How can a SwingWorker thread help in this case.
The wait loop time increases and the GUI main window turns black till computations are done.
Then you long running task is executing on the Event Dispatch Thread (EDT) which prevents the GUI from repainting itself. You need to execute the long running task in a separate Thread. A SwingWorker is a separate Thread which has an API that also allows you to execute code on the EDT as required, for example when the code finishes executing or when you have intermediate results.
Read the section from the Swing tutorial on Concurrency for more information. You can always search the forums for example of using a SwingWorker.
1)
Wait loops are the bane of all that is GUI. They are OK in other threads you have spawned, tricky in Executors (as they sometimes have limits on number of Threads, depending on which you use), and are completely out of the question on the EDT. That is the reason for your "blackscreen"
2)
Instead of using a custom (I assume it's custom) signal protocol and a wait loop, you could use one of the utility classes in Swing. For example, SwingUtilities has a couple of nice methods - invokeLater and invokeAndWait that take a Runnable and execute it on the EDT as soon as they can. Using this instead of the signal you have will allow you to not block the EDT and make your GUI responsive.
3)
If you really want to use a SwingWorkeryou may want to look through the documentation for it. It is essentially a way to do background tasks and report progress or completion/result to the EDT. Currently it uses an ExecutorService with 2 background threads, so having a lot of long running tasks on them is not a good idea (they will block each other). When creating a SwingWorker you would specify the method to be ran in the background, the method to be ran on the EDT when intermediate results are available, and the method to be ran on the EDT when you're finished either successfully or in error.
4)
This does not pertain to the question at hand, but if you ever get into a situation where you need a wait loop in the EDT and cannot avoid it using another design or technique, you can always switch to using a Timer. It can be setup to be called every x milliseconds without blocking the EDT and turned off once you are satisfied with some condition.
When i enclose Thread.wait() in a while loop my IDE (NetBeans) tells me that this may cause perfomance issues, how can it and is there a way arround it?
Example:
while (timing){
Thread.wait(10);
foo++;
}
//Started in a seperate thread before activating.
EDIT: Thanks for the help, I will try to use the 'ScheduledExecutorService' instead!
You probably wanted to just make the thread sleep, and that is the name of the method you needed to call.
You called Object#wait(), which is a thread coordination method, and you used an explicit timeout on it (a rather short one). My guess is that NetBeans is warning you about that timeout because normally we use Object#wait without a timeout, and if we use the timeout, we don't wait in a loop.
Now, NetBeans will also warn you about using Thread.sleep() in a loop because normally, if you want to schedule a repeated task (that is what you are doing), you will use a ScheduledExecutorService. That service is able to serve a lot of different scheduled tasks around your application, all with a single thread. Writing Thread.sleep() explicitly in a loop needlessly hogs a whole thread (a heavyweight system resource) to do nothing but sleep most of the time.
How should I implement a function like that on my Swing editor?
I was thinking of a thread started on a releaseKey event. This thread should have a timer of a second. Every time I have the releaseKey I either start the thread or just reset the timer if it is already running.
I'm not convinced though. It seems like too heavy on the UI.
How should I do it?
A Timer starting/stopping every second is not a big weight on the UI at all. The "building" is what is going to possibly take some time. I think looking for a pause in keystokes is a fine solution.
I have 3 timers running on my application which takes care of different action. Timer 1 will deals with automatic logout of the application, timer 2 deals with updating a table, timer 3 deals with updating the color of swing buttons. First timer uses the calculation based on the variables and its values, second and third timers works out of MYSQL queries.
Now when i run this application on an average performance machine the application is not moving .I need to wait for few seconds to a normal click to happen or a window to open. Is it something to do with the timers ? If yes do I have any alternative suggestions to get rid of this timer problem?
It could well be the timers, if they are performing considerable work when fired. It's not usually a good idea to use swing timers for long-running tasks, since they will block the EDT and freeze the UI.
Here are some suggestions to avoid this:
Use a java.util.Timer rather than the swing timer. This will run the database code on a background thread, avoiding blocking the event queue.
Continue to use the swing timer, but have the timer action simply start a SwingWorker to perform the task. This gives the benefit of background processing with the ability to post updates to your UI, if it's a operation that takes more than a second or so to execute.
The problem isn't how many timers you have, but how long each timer takes to do it's work, since the timer's actionPerformed method is run on the swing event thread, meaning that while a timer is doing it's thing, no UI updates can happen.
That should not be related to the Swing timers, that is something else in your code. You need to debug the application to see what is causing the delay.
From what I remember, swing timers fire events on the same thread used for rendering, so you dont tend to get exceptions due to incorrect thread interractions - I have used them in the past for animations without issue - I suspect the answer lies elsewhere in your code. Have you tried profiling the code at the point where you are having an issue?
Is it OK if I run 5 timers at the same time?
All instances of javax.swing.Timer "perform their waiting using a single, shared thread." The limit occurs when the tread becomes saturated. As a practical matter, each Timer may have multiple listeners, but "the handlers must execute quickly to keep the GUI responsive."