When to Thread. When not to Thread - java

I'm new to the idea of Threading, but not asynchronous behavior. My Android app is taking ~180 millisecond to start up and ~550 milli when I use GoogleAnalytics trackViewPage method and MobFoxView constructor. Coming from Actionscript 3, anything that "took time" was automatically async and I was forced to handle it with listeners which is a bit different in Android it appears. It seems I'M responsible for deciding when something should be asynchronous. So I guess my question is, HOW do I decide what should be async? Is it by milliseconds of executing? But perhaps that changes greatly between devices. Perhaps it should be by ... or is it by ....?

You need to know one important thing - by default everything you do without starting separate thread is executed on "main" thread (also knows as UI-thread).
If you do something, which can block - your UI will lag and users will suffer.
If you doing something, which is not about UI but about database query, network call or potentially long blocking operation - you need to start thread directly or use AsyncTask.
Also you must note, if you try to do something with UI (e.g. set value to a TextView) from not-main thread you will fail. UI can be acessed only from UI-Thread.

Related

Asynchronous processing with a single thread

Even after reading http://krondo.com/?p=1209 or Does an asynchronous call always create/call a new thread? I am still confused about how to provide asynchronous calls on an inherently single-threaded system. I will explain my understanding so far and point out my doubts.
One of the examples I read was describing a TCP server providing asynch processing of requests - a user would call a method e.g. get(Callback c) and the callback would be invoked some time later. Now, my first issue here - we have already two systems, one server and one client. This is not what I mean, cause in fact we have two threads at least - one in the server and one on the client side.
The other example I read was JavaScript, as this is the most prominent example of single-threaded asynch system with Node.js. What I cannot get through my head, maybe thinking in Java terms, is this:If I execute the code below (apologies for incorrect, probably atrocious syntax):
function foo(){
read_file(FIle location, Callback c) //asynchronous call, does not block
//do many things more here, potentially for hours
}
the call to read file executes (sth) and returns, allowing the rest of my function to execute. Since there is only one thread i.e. the one that is executing my function, how on earth the same thread (the one and only one which is executing my stuff) will ever get to read in the bytes from disk?
Basically, it seems to me I am missing some underlying mechanism that is acting like round-robin scheduler of some sort, which is inherently single-threaded and might split the tasks to smaller ones or call into a multiothraded components that would spawn a thread and read the file in.
Thanks in advance for all comments and pointing out my mistakes on the way.
Update: Thanks for all responses. Further good sources that helped me out with this are here:
http://www.html5rocks.com/en/tutorials/async/deferred/
http://lostechies.com/johnteague/2012/11/30/node-js-must-know-concepts-asynchrounous/
http://www.interact-sw.co.uk/iangblog/2004/09/23/threadless (.NET)
http://ejohn.org/blog/how-javascript-timers-work/ (intrinsics of timers)
http://www.mobl-lang.org/283/reducing-the-pain-synchronous-asynchronous-programming/
The real answer is that it depends on what you mean by "single thread".
There are two approaches to multitasking: cooperative and interrupt-driven. Cooperative, which is what the other StackOverflow item you cited describes, requires that routines explicitly relinquish ownership of the processor so it can do other things. Event-driven systems are often designed this way. The advantage is that it's a lot easier to administer and avoids most of the risks of conflicting access to data since only one chunk of your code is ever executing at any one time. The disadvantage is that, because only one thing is being done at a time, everything has to either be designed to execute fairly quickly or be broken up into chunks that to so (via explicit pauses like a yield() call), or the system will appear to freeze until that event has been fully processed.
The other approach -- threads or processes -- actively takes the processor away from running chunks of code, pausing them while something else is done. This is much more complicated to implement, and requires more care in coding since you now have the risk of simultaneous access to shared data structures, but is much more powerful and -- done right -- much more robust and responsive.
Yes, there is indeed a scheduler involved in either case. In the former version the scheduler is just spinning until an event arrives (delivered from the operating system and/or runtime environment, which is implicitly another thread or process) and dispatches that event before handling the next to arrive.
The way I think of it in JavaScript is that there is a Queue which holds events. In the old Java producer/consumer parlance, there is a single consumer thread pulling stuff off this queue and executing every function registered to receive the current event. Events such as asynchronous calls (AJAX requests completing), timeouts or mouse events get pushed on to the Queue as soon as they happen. The single "consumer" thread pulls them off the queue and locates any interested functions and then executes them, it cannot get to the next Event until it has finished invoking all the functions registered on the current one. Thus if you have a handler that never completes, the Queue just fills up - it is said to be "blocked".
The system has more than one thread (it has at least one producer and a consumer) since something generates the events to go on the queue, but as the author of the event handlers you need to be aware that events are processed in a single thread, if you go into a tight loop, you will lock up the only consumer thread and make the system unresponsive.
So in your example :
function foo(){
read_file(location, function(fileContents) {
// called with the fileContents when file is read
}
//do many things more here, potentially for hours
}
If you do as your comments says and execute potentially for hours - the callback which handles fileContents will not fire for hours even though the file has been read. As soon as you hit the last } of foo() the consumer thread is done with this event and can process the next one where it will execute the registered callback with the file contents.
HTH

File API is causing ANR's

A small part of my application checks if files exist on the user's device. The list of files is potentially quite long - apparently long enough to cause ANR's with a few users. A thousand files is by no means impossible.
The code is quite simple:
new File(fileUrl).exists()
I'm currently doing it on the main thread, as I need the operations to be blocking. I could do it using an AsyncTask class and then continue the rest of the work once it's done, but I'm wondering if that's a valid cause?
All the work is being done in a background Service, if that changes anything. I'm also potentially going to experience orientation changes, and that might be annoying with AsyncTask. Would a Handler be better?
So, to sum things up: Should I do use an AsyncTask for a potentially long-running operation in a background Service, where orientation changes may occur?
Firstly, a Service isn't affected by orientation change - it's only the currently running Activity class which is destroyed / recreated.
Secondly, an AsyncTask isn't of much advantage in a Service as it's designed to be able to interact with the UI. It would give the advantage of doing work on a separate thread but the rest of the methods would basically be redundant.
I'd recommend using an IntentService which manages its own worker thread to do work. See the IntentService documentation

Events or Handlers? Invoking methods from a thread

Consider a simple Android application: there are two TabActivities and a thread in the background getting integer values from a server. If the number is even, it must be displayed in the first tab otherwise in the second. Obviously I will be doing something more complicated, but this is the basic pattern. How do I go about doing this? I have been scratching my head for about a day now and here are things I have come across:
Use of EventHandlers. The two TabActivities register for listening for my_events and when a value is received by the thread, it 'throws my_event' and then specific methods in both these activites are called and the value is passed.
The use of Handlers.
I have not used both of these concepts before and I would like to know which might be the better/correct route to take. Further, any more tips along the chosen route will be appreciated. Also, should this thread be run from a service class?
When you create your thread just pass the objects of your tabs into it, then in your execution you can easily put the text you want into tabs.
Possibly you want to look at using an AysncTask. If you do this you want to insert the values into the appropriate tab in the onProgressUpdate() method. Since the arguments passed to this method may not actually be able to represent the incoming data sufficiently you'll just want to put the new data somewhere that it can be accessed from the onProgressUpdate() method, probably in a member variable. Keep in mind that access to this member variable probably needs to be synchronized because code in onProgressUpdate is running on the application's main thread, while code in doInBackground is running on a background thread so code in these methods will be running concurrently.
AsyncTask uses Handlers transparently for you, but you could use raw Handlers if you wanted. The basic things you need to keep in mind are
You can/should only update the UI from the main application thread
Code in a Handler will always run on the Thread that created the Handler
Handlers must be created on a Thread that has a Looper (the main Thread has a Looper)
Be careful if creating the Handler as an anonymous inner class or handing it a reference to a Context since this creates the potential for a memory leak
Possibly the Thread should be invoked by a Service, but if the Thread only needs to exist when there is a UI for it to update there may be little point to this.

Multithreading or observer pattern when waiting for dns lookup?

I'm designing a system in java which utilizes a dns lookup class.
My question is, when calling the class's dnsLookup(), whether to do it in a new thread or use the observer pattern and let the dns class tell me when it's done.
This isn't a problem as long as the lookup returns a value almost instantly but when it takes a few seconds (when it doesn't get a response), I don't want to freeze the GUI while waiting.
So, new thread or observer. Appreciate some good links on the subjects as well.
Thanks beforehand - Dennis
You will have to employ both the observer pattern and more than one thread. There's no way to have the DNS invoking callback method in the same thread.
Your GUI is an event driver system so asynchronous notifications are good.
On the other hand, it's a lot easier to do network I/O (particularly if it's just a single DNS lookup) if you use synchronous (blocking) network calls.
Hence I would tend to go for the separate thread option, but then have that thread notify the main GUI thread when it's done.
Since it's a GUI that is making the call, I think it's best that you off-load the call to a different string. In fact, you want to make sure that you're not using the AWT-Thread to make a call that is blocking the GUI from refreshing. I would suggest using something like an ExecutorService to execute your commands and then upon the return, use SwingUtilities and call the invokeLater(Runnable doRun) method to update the GUI with the response.

Implementing java FixedTreadPool status listener

It's about an application which is supposed to process (VAD, Loudness, Clipping) a lot of soundfiles (e.g. 100k). At this time, I create as many worker threads (callables) as I can put into memory, and then run all with a threadPool.invokeAll(), write results to file system, unload processed files and continue at step 1. Due to the fact it's an app with a GUI, i don't want to user to feel like the app "is not responding" while processing all soundfiles. (which it does at this time cause invokeAll is blocking). I'm not sure what is a "good" way to fix this. It shall not be possible for the user to do other things while processing, but I'd like to show a progress bar like "10 of 100000 soundfiles are done". So how do I get there? Do I have to create a "watcher thread", so that every worker hold a callback on it? I'm quite new to multi threading, and don't get the idea of such a mechanism.
If you need to know: I'm using SWT/JFace.
You could use an ExecutorCompletionService for this purpose; if you submit each of the Callable tasks in a loop, you can then call the take method of the completion service - receiving tasks one at a time as they finish. Every time you take a task, you can update your GUI.
As another option, you could implement your own ExecutorService that is also an Observable, allowing the publication of updates to subscribing Observers whenever a task is completed.
You should have a look at SwingWorker. It's a good class for doing lengthy operations whilst reporting back progress to the gui and maintaining a responsive gui.
Using a Swing Worker Thread provides some good information.

Categories

Resources