Latency when pausing/stopping WaveAudioStream - java

I have just found the code to a small WAV player.
It works well but when clicking the "Pause" and "Stop" buttons there's like a 2 seconds delay which makes the app look really unprofessional. I have no idea what is causing this but I'd really like to have it fixed, could anyone inspect the code and tell me where it comes from? Thanks!

I wrote this sample for a time and don't remember very well.
In my opinion the latency comes mainly from the update frame functions. In the class VisualPlayer, UI are update by a timer which pick up the current values from the thread. It's not very efficient but faster for write this sample.
The best way to update UI is implementing a Runnable class and call it with SwingUtilities.invokeLater().
Also have you try to reduce read buffer size ?

Related

wait loading message while function is executing

I have a jframe with "search button", when the user clicks it, a function will be called to search through several databases for the specified search criterion. What I want is to have a "wait/loading message" to appear while the function is searching, and disappears once the function is done executing. I searched for similar ideas and all of them are using thread programming. Can someone insight me if it is possible to use threads on my situation and if there are any other options?
thank you
You should perform the search in a background thread, and notify the UI using for example invokeLater.
You can find more informations and an example here http://www.javamex.com/tutorials/threads/invokelater.shtml
You could do the search process on the UI thread, but since it apearantly takes long to complete, the GUI would freeze. So for a fluid using expirience i would reccomend doing the search in another thread. Mulit-Thread programming is not as difficult as you might think.
See this tutorial

JFrame gets locked completely while method is running

I have a GUI(JFrame), with two Buttons and 1 Panel to show the result. One Button is to start the algorithm, one for stopping it. By pressing start, a method is called and it starts running. The runtime of this method varies from couple of seconds to 2-3 minutes, depending on the input.
The problem I have hereby is, by pressing the start-button, the GUI gets completely locked. I cannot press any button till the algorithm terminates. It would be great to be able to stop the algorithm and to visualize parts of the solution after a certain amound of time.
I checked every single line of the Frame, there is nothing that disables it.
//If needed I can provide code, but its pretty long and just some hints and reasons for the problem would be great and I try to fix it by myself.
thanks in advance.
Don't put long-running tasks on the EDT, or the Event Dispatching Thread. Use threading or a SwingWorker instead. Hopefully that's enough google keywords to get you started. :)
It sounds like your algorithm is running in the same thread as the UI components. You probably want to read up on Concurrency and Concurrency in Swing to better understand how to create threads, monitor execution, integrating these concepts with a Swing-based user interface, and so forth. At a very high level, you are going to need to somehow spawn a new thread when your algorithm starts and observe it for intermediate state changes to update the UI. You only want user interface related code running in the event dispatch thread.

Display objects in JFrame one at a time, or frame by frame

I've made a program in Java (eclipse) that displays squares and triangles on a grid using JFrame. The program determines where the objects go in a "for loop". I would like to have the objects appear one at a time (in a frame by frame type of approach). It seems like a "sleep loop" should be used to solve this problem. However I feel that a lack of understanding of java.awt*; is causing me problems. I adding the following to my "for loop"
try
{
Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
}
catch(InterruptedException e)
{
e.printStackTrace();
}
The program waits, but draws the objects all at once after it is done sleeping. I have gone through my program and found that this "sleep" command is working to some extent (waiting before processing the next command) I put a println statement within said "for loop" to test it and the program waits one second before printing each println. But I don't know why JFrame draws everything only once at the end. Should I be using something like repaint() every time I want to display a new frame?
MY project structure is 3 classes. Main which simply calls DisplayFrame. DisplayFrame which sets up the Frame. And MyComponent which contains my "for loop" and the "sleep command".
Any help would be appreciated.
There is a tutorial here that uses a Timer to update an image at regular intervals. The example program is an applet, but the principle is the same.
sleep is probably a bad idea. Use a Timer instead:
http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html
From your description it is a little hard to guess what is going on, but I'm almost sure at least one of two bad things is happening:
you are sleeping in the EDT (Event Dispatch Thread) this locks the complete GUI and might be the reason for you not seeing any updates during sleep.
you are changing swing components from outside the EDT which is a sure way into concurrency hell.
Make sure you follow this approach:
Setup a Time to call you in the desired time intervall ( lets say every 0.1 seconds). In the method that is called manipulate you component/object to reflect the new state and call repaint.
let us know if it works. I'm not exactly sure about the repaint call ... might be wrong ..
Interestingly enough, the Applet Tutorial at the Oracle site has an example of an applet that performs an animation using SwingWorkers and Timers. Perhaps it can be useful to you.
Or you can take control of the rendering of the JFrame using concepts from the gaming world, as explained here

Best way to update an Android widget every 20-30 secs: Handler, Service or Alarm?

I have a 4x4 widget and i want to update a little piece of it every 15-20 seconds. Clearly i don't want it to be updated when the phone is in standby. The widget needs also to respond to some system events other than my timer. So, which is the best option?
An AlarmManager: nice but probably cpu intensive if it needs to be run every 20 seconds
An Handler: light but i dont know how to stop it when phone sleeps
A service: also here i need to understand how to stop it when phone sleeps
I will also need to update a little part of my widget without updating all its screen area, is this possible??
Thanks everybody.
I have a 4x4 widget and i want to
update a little piece of it every
15-20 seconds.
Please make this optional or configurable.
So, which is the best option?
A Handler has nothing to do with app widgets.
An always-running service is bad for business and is the sort of thing that causes users to attack you with task killers.
The best of the bad options is AlarmManager.
Frankly, the best answer is "don't update a little piece of it every 15-20 seconds".

How do I give this CPU-intensive Java application a GUI?

I'm writing a little genetic algorithm in Java, as a school assignment. Up until now I've pretty much stuck to doing console applications. However I think a UI would be really helpful for this program, so I'd like to make one. I'm having trouble figuring out how to reconcile a GUI which is event-driven, and a console application which has a beginning and end.
Ideally I'd like to have a bunch of text boxes for settings, and then a Start button. Once you hit Start, the algorithm would start running and the GUI would update on a set interval with the latest program state. How the heck do I accomplish this without the algorithm freezing the GUI or vice-versa? I don't want either one waiting on the other.
How do I get my main loop to not freeze the GUI while the algorithm is running? I assume they need to be in separate threads, but I've never messed with threads before. That seems too complex for this task, which must be commonplace.
You're on to something with threads. GUI programming mandates threads, in most cases -- luckily, Java's threading API isn't too terrible (Python's is modeled on it, so it's doing something right).
Don't be intimidated by threading, though -- it's intermediate, I'd say, but is something that every programmer should understand.
There's a lot of information out there that would predispose you against threads. GUI applications, however, are one area where they are phenomenally useful. Opponents of threading would lead you to believe that an event-programming model would help you in this case, when really, it will not. The solutions that most who say "threading sucks" propose are often worse than threading itself.
You could try to kludge your solution into a single thread, but it would require your CPU-intensive code to yield to the GUI at a predictable interval. That solution sucks. EDIT: Since others are suggesting that approach, let me elaborate on why it sucks: Unbeknownst to you, something is always being updated in a GUI. When you move a window on top and then back off, the entire region under that window is invalidated and code must execute -- in your process -- to redraw that section. Even if you are updating the GUI very quickly, this provides a negative user experience as simple GUI operations block entirely. Buttons highlight when you mouse over, sometimes. A user right clicks. All of these things require CPU time to implement, and if your solitary thread is chewing away on your GA, they will not happen. GUI code being executed is not only your code.
Here's what appears to be a very useful article on the topic.
Two lessons in the trail on the topic are:
Concurrency
Concurrency in Swing
Sorry - it would seem like background tasks would be an easy and obvious sort of thing. Unfortunately, the Java Swing GUI threading model is a bit complicated. There have been some improvements in this area, but one still has to have some knowledge of threading first.
If you have time, I'd suggest reading the chapter on threading in Filthy Rich Clients - Painless Threading through SwingWorker.
If your impatient, just read the JavaDoc on SwingWorker. If you're really impatient, just copy the meaning of life example from the JavaDoc sample usage.
When I was writing a ray-tracer for one of my computer graphics classes in college, I had a long-running task, and I wanted to update the display periodically as the tracer was drawing. I used two separate threads - one thread sleeps, and updates (say every 500 ms); the other thread does the actual raytracing. The key is to synchronize on a common object - in my case, accessing my image buffer was the point of synchronization (one thread can't make changes to the image buffer without first waiting until the other thread is done reading).
For your GA processing, you might have something like this (pseudocode):
Supposing you have some object, generationHistoryObject, which stores the state that you want to display in your GUI, then:
(in Thread #1:)
Generation newGeneration = doMutationAndTestThisGeneration(lastGeneration);
synchronized (generationHistoryObject) {
generationHistoryObject.updateWithNextGeneration(newGeneration);
}
(in Thread #2:)
while (!programIsDone()) {
synchronized (generationHistoryObject) {
drawGuiForCurrentState(generationHistoryObject);
}
Thread.sleep(500);
}
The idea is that you do the time-consuming work for each generation in isolation, then update the part that the GUI has to access in the synchronized block (making the GUI wait to draw until the update is done).
Your problem with Swing is that it is single threaded (which is a good thing) so you want to get your work out of the Swing thread so your application stays responsive.
The thing you need to do is to convert your core algorithm to a Runnable as it can be handled easily by a SwingWorker and with the newer Executors (see Executors for a lot of preconfigured ones). You can also create investigate how to make a PrintStream to a JTextPanel so you can just use standard println statements to output your current status information.
If you want to add a stop button you need to understand the thread model, so you know how to control it. The Java Tutorial has good material on this as well as Swing programming in general. Strongly recommended.
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html
Since your application has to do with genetic algorithms, you could update the GUI every generation or so. You could accomplish this by implementing a next() method in your algorithm code, and calling it from the GUI. This should be simple enough.
However, if you really don't want the GUI to freeze while waiting for the algorithm, you should go for threads.

Categories

Resources