BlockingQueue on main Service thread - java

My android app has a long running background service, which I also understand runs in the application's main thread and for that reason, any time consuming or blocking task should be moved to a separate thread.
Now, here is the situation, I don't understand/confused about:
When I bind to the service from an activity, i receive an reference to the service which allows me to invoke service methods from my activity. One of the methods allows me to pass a String object from the activity to the service, which is then added to a BlockingQueue. A separate worker thread which is started in the Service's onCreate method, checks the queue for available data and then performs the required task.
What I want to understand is, if at some point, the queue becomes full and an attempt to the queue blocks, will it affect the main thread the service is running on?

Yes. In this situation, if the queue becomes full, the calling thread will block (in your situation, the main thread). So this is a bad design.
The produced data coming from a field of an Activity doesn't force you to use it on the main thread. I suggest you use some Handler for your producer running on its own thread which will allow you to make the processing (and eventually waiting on the queue) outside of the main thread.
This is also good for communicating with your Service since you can use Handlers to communicate with a Service (see Android Services' guide).
Finally, if applying the produced data can be passed directly to an Handler using either
Handler.post(Runnable) or Handler.send(Message)

Related

Android camera: Threads? Which should do what

I am trying to figure out which threads should do what in Android.
The only thing I have found stated in the official documentation is that camera.open() should be put into its own thread.
What about:
camera.startPreview()
camera.stopPreview()
camera.release()
It doesn't state which thread they need. Must they be run on the main thread (ui thread)? Or am I free to choose?
Why am I trying to figure this out? camera.startPreview() when run on the main thread is causing my app to jitter/lag for a short period of time, this heavily affects my application as it is put inside a viewPager and I do not wish to have the camera to always preview (which would cause no lag, but takes up system resources).
Any ideas?
The documentation for Camera states that the class is not thread safe and should not be called from multiple threads at once (I suppose, unless you are performing your own synchronization).
It says that the callbacks will be delivered to the thread that makes the call to open
From the reference (emphasis mine):
This class is not thread-safe, and is meant for use from one event thread. Most long-running operations (preview, focus, photo capture, etc) happen asynchronously and invoke callbacks as necessary. Callbacks will be invoked on the event thread open(int) was called from. This class's methods must never be called from multiple threads at once.
From the open(int) method reference:
Callbacks from other methods are delivered to the event loop of the thread which called open(). If this thread has no event loop, then callbacks are delivered to the main application event loop. If there is no main application event loop, callbacks are not delivered.
Caution: On some devices, this method may take a long time to complete. It is best to call this method from a worker thread (possibly using AsyncTask) to avoid blocking the main application UI thread.
The thread it needs is the one you use to call open(int).
So to answer your question, yes you are relatively free to choose, but you must remain consistent.

Android/Java sequence of serially executed tasks

How can I have a sequence of tasks that run one after another (Serially). I'm not using AsyncTasks, but the loopj AsyncHttpClient, but the question applies to other tasks as well.
The way it's structured is: Application has main method that performs multiple async calls. These calls are mutually serial, one must be run after another.
Main() calls FuncA() which fires an async request. Control is returned to Main()
The request handler calls OnFuncAComplete(), which triggers Main() to proceed:
Main() calls FuncB() which fires an async request. Control is returned to Main()
The request handler calls OnFuncBComplete(), which triggers Main() to proceed:
rinse, repeat
How can I write main to perform all these functions in lock-step, how can I pause Main() and in OnFuncXComplete "trigger" main back into action? My first thought was with ReentrantLock's, but I can't seem to get it to work.
Edit: I know I could just call FuncB() from OnFuncAComplete(), but then I'm getting down into callback hell and I want to avoid if possible.
It looks like there may be more than one solution for this. One possibility is to use SynchronousQueue for transferring tasks between your Main and a processor. AsyncTask probably will not be needed, instead your tasks can extend runnables and no need to make callbacks to "unlock" Main()
Create a processing thread that runs a loop and polls SynchronousQueue instance (possibly with timeout). Each element obtained from the queue is a Runnable that the processor thread just executes.
In your Main() you call FuncA(SynchronousQueue q, <...>), FuncB(SynchronousQueue q, <...>), etc. sequentially
Each of FuncX() inserts its runnable task into the queue (q)
Make sure that you can nicely finish your thread once there is no more tasks to run
Have a look at IntentService. It is a Worker service that has only one bg thread an requests are enqueued and processed in a FCFS manner. Responses from service to your Main can be delivered via a BroadcastReceiver that your Main should have registered beforehand.

Android multithreading and services

I am little bit confused with multithreading in Android. I am aware we can achieve using AsyncTask and Handler. Generally when should we implement by extending Thread Class in Android? Can anyone give an example that we need to do it only by extending thread class but not with AsyncTask or Handler.
Consider a example app, we have a bouncing ball in an activity(forget the animation part), I need to change the color of the ball every 20 minutes, and I need to get the color code from the server and update the ball UI. Now how can I achieve this ? Can someone explain using AsyncTask or Handler and also only using Thread Class(without Asynctask or Handler)?
How should I handle downloading large payloads from server using services.
Thread
Long task in general
Invoke by thread.start() method
Triggered from any thread
Runs on its own thread
Manual thread management/code may become difficult to read
AsyncTask
Small task having to communicate with main thread
Invoke by execute() method
Triggered from main thread
Runs on worker thread
Must be executed and created from the main Thread
Service
Task with no UI,but should not use for long Task. Use Thread within service for long Task
Invoke by onStartService()
Triggered from any Thread
Runs On Main Thread
May block main(UI) thread
IntentService
Long task usually no communication with main thread if communication is needed then it is done by Handler or broadcast
Invoke via Intent
Triggered from Main Thread (Intent is received on main Thread and worker thread is spawned)
Runs on separate thread
Can't run task in parallel and multiple intents are Queued on the same worker thread.
Thread: Use it to separate long running computation from Main Thread ( UI Thread). If you don't need to update UI or send messages back to UI Thread, use it for long running tasks. But you don't really need to extend Thread and write your logic by overriding Thread methods. But still HandlerThread is effective compared to java Thread.
AsyncTask : it is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few milli seconds at the most). Recommended for 5 milli seconds task execution.
Service: Use it to handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
HandlerThread/Handler: A HandlerThread is effectively a long-running thread that grabs work from a queue, and operates on it. You can use it even to send results back to UI Thread via Handler of UI Thread.
Have a look at below posts for more details:
Asynctask vs Thread vs Services vs Loader
Handler vs AsyncTask vs Thread
Creating Background Service in Android
Android: Toast in a thread
An AsyncTask is basically a thread. It has 3 callBack methods(main) and the are executed in this order top to bottom:
1. onPreExecute()
2. doInBackground()
3. onPostExecute()
4. onProgressUpdate()
The onPreExecute() and onPostExecute() are running on the UI thread and doInBackground() is a separate thread as such. If you spawn a thread(not a AsyncTask), and try to set a property of a UI element from it, this will raise an exception saying: the original thread(the UI thread) which created the view can only modify it. So only the UI thread has these two properties:
Only it can add/modify the UI of the App
It cannot be blocked for more than 5 secs(ANR exception)
So to over come both these limitations in one go, we have AsyncTask, it can run resource consuming operations(network access, implementing gaming logic etc) in doInBackground(), and still provide ability to alter the UI from onPreExecute() and onPreExecute().

What the UI thread will do if Activity/UI is idle for some(may be long) time

I think title itself says what the my question is...
AFAIK, in Java, when work of a Thread is completed i.e. run() method has completed executing, Thread itself will finish and dies.
So, When my Activity(I mean UI) is idle for a long time, what the UI thread will do? does it sleeps? or does it do any other work?
Thanks to all...
I believe the question is not really about Java threads in general, but about the Android "main thread" (also called the "UI thread").
To quote from the JavaDoc for the Android Handler:
When a process is created for your application, its main thread is
dedicated to running a message queue that takes care of managing the
top-level application objects (activities, broadcast receivers, etc)
and any windows they create. You can create your own threads, and
communicate back with the main application thread through a Handler.
This is done by calling the same post or sendMessage methods as
before, but from your new thread. The given Runnable or Message will
then be scheduled in the Handler's message queue and processed when
appropriate.
In other words: The main thread is responsible for dequeuing messages/runnables from a queue and processing them. That main thread is blocked while the queue is empty (since there is nothing for it to do). If you use a Handler that was created in the main thread, that Handler's messages and runnables will actually be added to the same queue used by the main thread. Normally, the main thread will run as long as the process does.
Note: An Android app can actually have multiple processes, and each one will have its own main thread. However, most Android apps will only have one process (and therefore one main thread).

Java Thread to manage socket and run class method

I have a Java thread that I start so it keeps listening to a socket (considering the a socket read is blocking a thread is needed).
After the Thread receives the data from the socket it needs to call a method from a class.
Now I have two options to do this:
Declare an interface that is passed to the Thread and implemented in a class. When the thread calls the interface method the implementing classes will run it.
Or I can pass the class instance to the Thread as a parameter and then call the class method.
But I wanted to know if the thread blocks while the method is running.
I suppose so but I'm not sure.
I wanted the thread to have a Socket event behavior. What I mean is to only be responsible for reading the data from the socket and fire functions in the main Class, the one that called the Thread.
Yes, the thread will block while executing the method, so it can not read from the socket at the same time. No information will be lost, the transfer only takes longer and you can get a socket timeout if the computation takes too long.
If your method takes much time to run, you should execute it in another worker thread. I recommend to use an Executor for that.
You have various options :
Make your class a child class of Thread (easier code but you'll merge functionnal part - your main code - with a technical aspect (extending the Thread))
Make your class implements the Runnable interface and start a new thread with that Runnable (i often do like that). So your main code still remains in a overriden run method, but the inheritance tree is up to you (your main class can extend one of your other class)
Keep separated your main code / the thread with two classes (one for your main code, one for the thread), linking the two at your will (remember that if you make an inner thread inside another class, the inner thread can use any final properties, for example).
As stated in other answers, anything happening in your run() method is of course blocking the execution.
As a sidenote, if you're going to deal with threads and sockets, i strongly suggest you to have a look at NIO frameworks like Netty that are just there for this kind of behavior : event driven client/server application through NewIO sockets.
As another sidenote, i often use this pattern :
start an acquisition thread that will catch the event ;
push them in a linkedblockingqueue (queue.offer()) ;
have another thread that shares the same linkedblockingqueue (with queue.take()) : this operation is blocking, the threads will be blocked as long as the queue is empty ;
This is a very simple way to have one thread as "producer", and one thread as "consumer". You can even have various consumers awaiting on the same queue.
But I wanted to know if the thread blocks while the method is running
Yes it does block.
If inside run you call a method to process something it doesn't matter if that is an interface etc as you ask it only matters what does the method actually do
In your case you have only 1 option.
Make sure that you return the control back to your socket listening thread asap.
This can happen by designing/mandating the processing class to handle the processing in a different thread.
Actually your problem is not something new. In event based designs there is the requirement to process the event as fast as possible so as to not block the event queue based flow.
And this is how I would recommend you to design arround. Not use any interface to interact with the listening thread but register an event listener(s).
When an event occurs i.e. your listening thread reads data, it will pass the data as event to your listener(s) at which point of course it will block.
Then you should start a new thread to do the processing and the listening thread can continue with its work

Categories

Resources