I'm developing an application where i need to execute a countdown, have a certain counter go down every second, and display in a widget.
No problem, that is done easily using the java class javax.swing.Timer, but the performance are poor.
There are other graphical object on screen and it is not accurate enough, letting it go down from 10 minute to 0 takes more than 10 minutes.
First thing i tried is a Timer with a 1000ms delay, that makes me lose a lot of seconds and sometimes it is not fast enough in updating the view.
Second, i tried with a Timer with a delay of 20ms and a logic inside that let my action run only if the System.nanoTime() report a second from last execution.
This gives me a better accuracy, but yet in an environment where the java application is in execution with other applications on old systems, it performs even worse.
Is there a way to achieve a scheduler indipendent Timer in Java?
I'm up for really anything. OS indipendence isn't really an issue, so native code is an option if it gives me a good result.
UPDATE:
I created an example and uploaded it on gist:
https://gist.github.com/bracco23/c160c9591ac216a2eb9452ef9e7d6d95
Badly, the example isn't really as bad as the full project, i let it run for the full 10 minutes and it took about 602s, a 2s delay that's less than 0.4%, not really bad, i wouldn't mind that.
I'm uploading it to show the schema of the application, the same in the example and in the full application.
thank you very much anyway :D
Related
What I want to do is generate a call tree with CPU timing information for a Java application as it goes through a scripted task. The idea is to see how much time is spent in each part of the code, and how this changes when I change the code or the task, but to do so in a consistently repeatable way.
In Java VisualVM I can do this interactively by clicking to start and stop profiling, but I would like to automate the process so I can get more consistent results (and not get so bored). Can VisualVM do this, or is there another profiler that can?
If I were a profiler vendor I would have to be concerned about providing people what they think they want, even if what they think they want does not solve the problem they have.
The thing is, only some problems can be found by knowing how long routines typically take, and if you ignore the ones you don't find that way, they will become the dominant part of how much time your program takes.
An example of what I mean is this recent example:
A program spends 50% of its wall-clock time reading .dll files to look up string resources to get the names of files so that the strings can be displayed on a splash screen so the user can see that something is happening during application startup. That means, if there were some other way to provide eye-candy to the user, the app could start up twice as fast.
During this process, the call stack is typically 15-20 functions deep, so it's really hard to tell what's going on just by having timing numbers for the functions.
What makes the problem difficult is that it is semantic. No particular routine is "hot" in a way that it could be speeded up.
The only "hot" thing is the general description, overall, of what the program is doing, and no tool can isolate it for you.
Only you can recognize it.
However, if you simply interrupted the program and examined the call stack during startup, the probability is 50% that you would see the entire explanation for the time being spent.
If you do it several times, it's the basis of the random pausing technique that some programmers rely on because it will find every problem profilers can find, and more, and others look down on because it isn't a tool.
And do it interactively, either that or extract a small number of stack samples by using something analogous to pstack.
In my Android app, I need a certain bit of code to execute every minute, whether the phone is active or not.
(For those curious, the app is meant for a personal project, a "talking" clock which will need to check every minute if that time has a corresponding sound file to play. It's not something I plan to release to the world, so battery considerations are not in play.)
My current approach is to use Timer.scheduleAtFixedRate() to schedule a task.
This seems to work whenever I am looking at the app, and interacting with it occasionally to keep the screen from blanking, but if the phone turns the screen off to save power, it seems like my call happens sporadically.
I tried setting the interval to be every 30 seconds, but even then it seems like I miss some minutes. Are there specific considerations to using Timer on Android? Is there a better way to achieve what I need?
Question: are you 100% absolutely sure you need to be doing this every minute? It just sounds to me that you'll be hogging the battery like crazy and will get quite a few unhappy users.
But if you answer yes to that question:
After your activity is paused, there's not guarantee from the system that anything on it (including your task) will be kept running; that way as soon as the systems needs a couple of megabytes to do anything it will kill your activity and stop your timer.
You should implement the timer/task in a Service. Services are much less likely to be killed by the system and you might ask that if the system needs to kill it to re-created it as soon as possible.
Have you tried using AlarmManager, this will let you do a task every X amount of time even if the phone is in standby mode or off
Here are the docs for it
If you want a nice example of using an AlarmManager, here it is... This one does not work if the phone is turned off but you can enable this easily if you want
I use java.util.Timer to trigger jobs in my app, but I found that it is depend on system time: if system time is adjusted, timer's trigger will be affected.
For example, if system time goes back by 80 seconds, the timer will stop working for 80 seconds.
Java has a System.nanoTime method which is independent of system time, but it seems that it
cannot be used in Timer.
Is there Timer library that supports what I need? Or I have to implement it myself?
Notice that I don't need a precise current time(date), I need a precise time interval
you have 2 options:
Write your one timer, relatively trivial. Before anyone tell reinvent the wheel, being able to carry the task yourself is always important. Especially when it's around 20 lines of code.
Use java.util.concurrent.ScheduledThreadPoolExecturor and use scheduleAtFixedRate, the queue impl. is based on System.nanoTime.
Install ntp daemon that adjusts the time by tuning (slowing down, speeding up) the system clock in very slight fashion during long time span.
Few other things, perfect 100ms is a tall order in non-real time GC environment as GC may STW (stop the world) for seconds sometimes. Sun's GCs can't do that super reliably. IBM's Metronome running on modified Linux kernel is supposed to be able to. You may wish to pay attention to if your application is truly real-time demanding.
If your computer is isolated and off the Internet i think there is not much you can do if the user tampers with the clock.
On the other hand, if this is not the case, you will find quite many API's and Mashups that will allow you to read the correct time. You could read the time from there. You could read the time from time.gov. Also twinsun.com you give you lots of additional options.
100ms seems like too low for Internet time-access.
I'm trying to profile my java app, just to find out the methods in which most time is being spent. Given the poor reactions here to TPTP, I thought I'd give Java VisualVM a go.
It all seemed rather simple to use - except that I can't seem to get anything consistent or useful out of it.
I can't seem to see anything relating to MY OWN code - all I get is a whole bunch of calls to things like java.* methods.
I've tried restricting instrumentation to only my own packages, which seems to cut down the number of methods instrumented, but still I don't ever seem to see my own.
Each time I run, I get varying numbers of methods instrumented, ranging from 10's to 1000's.
I've tried putting in a sleep at the start of my app, to make sure I get VisualVM up and running before my app starts to do anything interesting, to make sure it's profiling when the interesting stuff is running.
Is there something I have to do to ensure my classes get instrumented ?
Are there timing issues ? ..like, have to wait for classes to be loaded etc ?
I've also tried running the guts of the code twice, to make sure all the code does get exercised...
I'm just running an app, with a main, from Eclipse. I've tried using the Eclipse integration so that VisualVM starts up when I start the app - results are the same.
I've also tried exporting the app as a runnable app, and running it standalone from the command line, rather than through Eclipse - same result.
My app is not a long running web app etc - just a main that calls some other of my own classes to do some processing, then quits.
I'd be grateful for any advice about what I might be doing wrong ! :)
Thanks !
I too am struggling with VisualVM, which is a shame because its user interface is fantastic while its profiling output seems horrific. You can seem my question here.
Java VisualVM giving bizarre results for CPU profiling - Has anyone else run into this?
I can tell you a couple of odd things that I have learned about VisualVM and the way it seems to do its profiling.
VisualVM appears to be counting the total time spent inside a method (wall-clock time). I have a thread in my application which starts a number of other threads and then immediately blocks waiting for a message on a queue. VisualVM will not register this method in the profiler until one of the other threads sends the message the first thread was waiting for (when the application terminates). Suddenly the blocking method call dominates the profiling output and is recorded as taking up more than 80% of the application time.
Other profilers, such as JProfiler and the one used by Azul do not count a blocked thread as taking up time for the profiler. This means that blocking methods which probably aren't interesting (situation dependant) for performance profiling are obscuring your view of that code that is eating your CPU time.
When I am running my profiling I end up with
sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run()
obscuring my profiling right up until that message comes back to the waiting thread and then the top spot is shared between these two totally irrelevant methods, as well as various other uninteresting methods which don't appear on other profilers.
Secondly and I think quite importantly the method filtering mechanism doesn't work as I would have expected. This means that I can't filter out the I am trying to track down what the story is with this right now.
Not a really helpful answer. The solution as I see it right now is to pay for JProfiler - VisualVM just doesn't seem trustworthy for this task.
you could take a look at Appdynamics lite , it's has a nice features such as business transaction discovery which can samples all call made to a specific method in your code.
The lite version has a lot of limitation such as 10min sampling max and 30 business transaction discovery max.
It's would be nice to have a free tools that do the same
I assume this isn't just an academic question - you would like to see if you could make the app run faster. I assume you also wouldn't mind a little "out of the box" thinking. There are many popular ideas about performance that are actually pretty fuzzy.
For example, you say you're looking for "methods in which most time is being spent". If by that you mean "self time" (program counter actually in the method) there is probably very little, unless you've got some intense loops. Methods generally spend time by calling other methods, sometimes doing I/O.
Another fuzzy idea is that measuring method time or counting the number of calls can tell you very much about where bottlenecks are. Bottlenecks are specific lines of code, not methods, so even if you know approximately where to look, you're still playing detective.
So those are a few of the fuzzy ideas. Here is a bunch more. Let me suggest how one should think about it, and how that leads to results.
When you eventually fix something, it will reduce execution time by some percent, like (pick a number) 30%, right? (Otherwise you didn't fix anything.) OK, during that 30% it was doing something, something that it didn't need to do because later you got rid of it. So, you don't need to measure. You do need to find out what it is doing in that time, so you know what to get rid of.
A very simple way is to "pause" it 10 (or some number of) times at random. Understand what it is doing and why, by looking at the call stack and possibly some of the data. On about 3 of those times you will see it doing something you could get rid of.
You will know approximately how much it will save by seeing what percent of samples is showing it. Approximate is good enough. You can easily see exactly how much time is saved by stopwatching it before and after.
Then, don't stop. You've made the app faster. Do it again, and make it faster yet. Sooner or later you get to a point where you can't make it any faster, but it's probably in more than one step.
I'm developing an application which requires Contents of the database to be written to an ms-excel file at the end of each day. I've written the code for copying the contents into ms-excel file but Now how to proceed further? Whether threads are to be used to check for the completion of 24 hours or there's some other mechanism? Please provide me some guidance.
If you need to facility to run things at set times during the day, you should consider the Quartz Scheduler. It might be overkill, but it's very capable.
For example, you can use its CronTrigger to configure a job to run on a schedule defined by a cron expression, e.g. 0 23 55 * * ? (or something like that) would run your job at 5 to midnight every night (see examples).
Quartz recently got a boost to its future and fortunes by being acquired by the Terracotta folks. Hopefully it'll get some real active development now.
I agree with the others that using something like crontab would be better. However, if you can't do that, I would use the java.util.concurrent package added in Java 1.5. The class you would need is ScheduledThreadPoolExecutor. Specifically, the scheduleAtFixedRate() method.
I think that from the design perspective it is better to use crontab on linux platform or task scheduler on windows platform. It will keep your java program small, and simple. While the solution with thread waiting for the specific time seems simple it will add one serious concern - you will have to monitor its health.
In addition - I would suggest to carefully plan logs your job is writing each time it is run. It is important to have logs for both successful and unsuccessful runs.
It makes sense to make separate file for such logs.
One more case to be considered - what to do if database was not available exactly in the time when job run? Is it acceptable to wait another 24 hours?