I’ve created a class which is an extension of Thread. This class hits a web service and throws some data on screen. I don’t care about persisting this data (the screen displays search results).
Currently, the user simply types into an EditText and clicks a search button. I’d like to take away the search button and implement something similar to Google’s Instant Search where, as you type, the search results get updated.
This means, as the user types, the search parameters change. I want to be able to kill the currently running thread (if one is currently running) and spawn a new one with the new search string. How can this be achieved? Can I do it with Thread or will I need to use a new object?
This is more difficult than simply killing a thread. You can call interrupt() on the thread, but the thread will have to check its interrupt status periodically and self-terminate.
Secondly, you will not want to start a thread immediately on a user typing. You will quickly overwhelm the system with thread spawning. Implement a wait period of 100-200 milliseconds before doing the search so that you can be reasonably sure the user is done typing. Google’s server can handle the load, but the handset won’t be able to.
EDIT: to expand on my first point, threads can be difficult to cancel. In this case the event dispatch thread will need to somehow tell the running thread it needs to stop. You can use the
interruptfacility built into threads, but it tends to be touchy as pointed out by this article. Instead, I would simply have abooleanvariable that can be set tocancelledby some outside thread. The trick (like shown in that link) will be that you will need to periodically check if the thread has been cancelled, and if so you will need to manually abort.The next problem you will run into is if a web call has already been made to some outside server. It will block in that thread until it comes back and the thread will not be able to kill itself. This could take several seconds.
So let’s play this out – what if a user types a character, and your timeout period expires for whatever reason and a web call is made, then the user types another character where the timeout period expires so another web call is made? If your web calls take 5 seconds, then the first thread will continue to run, even if the event dispatch thread cancels it, for at least 5 seconds. You now have two threads making web calls.
Now expand that. What if a user does this and makes 4 or 5 threads? This is where you overwhelm the resources of your handset. I am not telling you not to pursue this, just trying to point out the potential problems that come with the territory.