Events or Handlers? Invoking methods from a thread - java

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.

Related

Android - What is a Handler Message?

I'm talking about this class.
The main documentation states:
Defines a message containing a description and arbitrary data object
that can be sent to a Handler. This object contains two extra int
fields and an extra object field that allow you to not do allocations
in many cases.
So I would assume that it is some kind of communication between
different threads, maybe a Bundle?
There are also a few snippets in the main documentation. But I
can't see how are they built and what is their structure.
Why to use them instead of using SharedPreferences or maybe a Singleton class? Testing?
I would love to see a little and compact example on when and how to use them.
So I would assume that it is some kind of communication between different threads
You can attach a Handler to the main application thread (a.k.a., UI thread), and you can create separate HandlerThread instances for other threads with associated Handler instances.
One thread can send a Message, via a Handler, where the Handler will process the Message on its own thread, in the handleMessage() method. For example, a regular background Thread could package the results of its work (e.g., downloaded data) into a Message, and give that to a Handler attached to the main application thread. That Handler will get the Message in handleMessage(), called on the main application thread, and can then update the UI safely using the data from the background thread.
This is a very low-level means of inter-thread communication in Android. More often, you are better served using something a bit higher-order, like an event bus.
Why to use them instead of using SharedPreferences
SharedPreferences are for data storage, not inter-thread communication.
or maybe a Singleton class?
While a singleton can provide a central point of data, on its own, it does not provide any sort of inter-thread communication.
I would love to see a little and compact example on when and how to use them.
For 99% of Android developers, the answer is: don't use them. Use something that is built on top of Handler and Message, such as:
AsyncTask
LocalBroadcastManager
Square's Otto
greenrobot's EventBus
etc.
A Thread can have one handler and one messageQueue only, a message is some arbitrary data that is handled by the handler whom put on it's messageQueue, the messageQueue loop every message and process them until it has no more message, all data are versatile and executed asap, no need to save it on HDD, it's low level code you dont deal with it often

Two different classes A and B on their own thread calling a method of the same class instance C

So I've got a simple Server class that creates an instance of a Listener class for every connection made to the "server". The Listeners run on their own thread.
I get that there might be a concurrency control problem when invoking methods on the Server class that alter files/variables. But what happens if 2 Listeners try to invoke a method that e.g. only returns some information about the server status?
Can the same Server instance handle 2 calls at the same time? Or will one of the listeners have to wait till the server is done executing the method of the first caller?
Thanks for any help you guys might be able to provide!
If the method is not synchronized, the server can handle the two calls concurrently.
But if they ask for status, this means that the status changes over time. And if it changes over time, then all accesses, read and write, to this status should be done in a synchronized way. Otherwise, the listener threads could see an obsolete value of the status.
So the method should be synchronized, or the status should be an AtomicXxx value, or it should be volatile. The best, and correct solution is hard to give without seeing the code and knowing how the status is read and modified.
For something like that, that I imagine doesnt change that often, I'd consider using a ReadWriteLock - so most of the time you can have multiple threads reading the status concurrently, and only have to block them when you want to update the value.

How to properly create and implement a ThreadPool type class in Java

I would like to make my own ThreadPool type class in Java (I tried in the past and kept getting concurrent exceptions - I forgot the specific error) and i'm back to it again.
This would be used to on the fly, easily create different threads to run different processes concurrently and then when a task finishes in the thread it was passed to, it would be recycled and reused for another purpose. This is for a 2d game engine in Java that I coded myself.
This would be used for things such as collision, audio, animation management, timing, controls, etc. These are just options for the reason i need a ThreadPool class.
Problem: The last time I tried this, I created a ThreadPool class that held an Array of type "AudioThread" (or something similar) that was an inner class that overrided the "run" method. When creating a ThreadPool class, I would pass a number of threads to be created and that would be stored in the array for later manipulation.
I would then try to create methods such as "assignTask(ThreadTask task)", "freeThread()", getFreeThread(). etc. But from making changes to the threads, I got concurrent errors of some sort.
Bottom line, does anyone have experience making a ThreadPool type class that can offer experience to what I can and cant do? Suggestions for fixing this problem? Advice? Thoughts?
Thank you.
You probably want to use ThreadPoolExecutor. It sounds like it does exactly what you want.

When to Thread. When not to Thread

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.

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.

Categories

Resources