Should SyncAdapter.onPerformSync be blocking? - java

I am aware that SyncAdapters are executed on a different thread than the main thread but are there any guidelines on how to design the execution?
The docs about it only state that I need to implement the logic by myself, fine but any details?
Any advices on how to use SyncResult?
Should onPerformSync actually be a blocking call or rather not? For instance if I need to execute some async tasks like fetching data from a server, should I or must I not block onPerformSync?
Can I prevent a re-scheduling of the sync with SyncResult in a reliable way instead of using delayUntil?
Or should I entirely guard the multi-threading critical parts of onPerformSync with a synchronized object by myself because concurrent or even re-entrant execution can happen at any time?

Related

How to suspend a specific thread in kernel?

Is there a way to suspend and resume a thread (what is created by a thread class exists from java) using KID in the kernel? I was thinking of something like pthread_kill, but that function doesn't work at kernel level. Please tell me how to do it per thread, not per process. (Unfortunately, per-process pause/resume works fine through the kill() function. but what I want is per thread, not per process.)
As far as I know there is no way to do that without code changes and without exposing this as option to control externally.
If you decide to introduce code changes that will manage the thread state read first here about deprecated methods Thread.suspend and resume and follow the proposed examples:
https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

Detect java thread starting to wait and run some code

Is there any way to put any sort of event listener that will be called when some thread - for example, the current thread - stops its activity and starts waiting or terminates?
I need this for the object to be notified and release some resources, when it is not in active use in this thread but still stored in memory somewhere that prevents it from being garbage collected - otherwise I'd place that resource releasing code in finalise() method.
UPD
Use case: an object that keeps a reference to a jdbc resultset or a database connection; the respective close() or commit() should be called automatically when the object is set aside temporarily or discarded at all without requiring the program to call any sort of cleanup method.
(There is no question how do I lock the object to be accessed from only one thread at a time, it is solved.)
The distinct non-answer: wrong design point. Threads don't "own" resources.
Threads are simply "threads of execution". They run the code you tell them to run. Therefore a thread doesn't own any of the objects it comes by.
As a consequence, there are no built-in mechanisms to help with your requirement. You would have to implement something yourself, relying on monitoring threads, and their states. Which would be a hard and challenging task. Mainly because: multi threading is hard.
The serious recommendation here: step back from this design. Rather think about other, different ways to deal with such "resources".
This is indeed a wrong approach.
You can obviously lock the object and unlock it in a finally block like this:
private Lock lock = new ReentrantLock();
public void useObject() {
lock.lock();
try {
//do something with your resource.
}
finally {
lock.unlock();
}
}
This way if the thread that runs useObject terminates, it will execute the finally block, and unlock the lock that protects the resource.
But there's NO way to detect the thread is not having any activity. If the thread is preempted by the Operation System, there's no way for you to know about it. That's below the abstraction level, you as a developer, operate.
If you want to gain more understanding on how the OS works with threads, and what you can cannot do you should check out
Java Multithreading, Concurrency & Performance Optimization
course on Udemy.
It also talks about how to properly use the right locks to do this kind of safe synchronization, and get the best performance from your application when you have to share resources such as database connections.
I hope it helps

Is Thread to be favoured over Executor here?

As far as I understand Executors help handling the execution of runnables. E.g. I would choose using an executor when I have several worker threads that do their job and then terminate.
The executor would handle the creation and the termination of the Threads needed to execute the worker runnables.
However now I am facing another situation. A fixed number of classes/objects shall encapsulate their own thread. So the thread is started at the creation of those objects and the Thread shall continue running for the whole life time of these objects.
The few objects in turn are created at the start of the programm and exist for the whole run time.
I guess Threads are preferable over Executors in this situation, however when I read the internet everybody seems to suggest using Executors over Threads in any possible situation.
Can somebody please tell me if I want to choose Executors or Threads here and why?
Thanks
You're somewhat mixing things. Executor is just an interface. Thread is a core class. There's nothing which directly implies that Executor implementations execute tasks in separate threads.
Read the first few lines of the JavaDoc.
Executor
So if you want full control, just use Thread and do things on your own.
Without knowing more about the context, it's hard to give a good answer, but generally speaking I'd say that the situations that calls for using Thread are pretty few and far between. If you start trying to synchronize your program "manually" using synchronized I bet things will get out of hand quickly. (Not to mention how hard it will be to debug the code.)
Last time I used a thread was when I wanted to record some audio in the background. It was a "start"/"stop" kind of thing, and not "task oriented". (I tried long and hard to try to find an audio library that would encapsulate that for me but failed.)
If you choose to go for a thread-solution, I suggest you try to limit the scope of the thread to only execute within the associated object. This will to an as large extent as possible avoid forcing you to think about happens-before relations, thread-safe publishing of values etc throughout the code.
ExecutorService can have thread pool
It optimizes performance, because creating a Thread is expensive.
ExecutorService has life cycle control
shutdown(), shutdownNow() etc are provided.
ExecutorService is flexible
You could invoke variety of behaviors: customize ThreadFactory, set thread pool size, delay behavior ScheduledThreadPoolExecutor etc...

Android AsyncTask.THREAD_POOL_EXECUTOR vs custom ThreadPool with Runnables

I have some tasks that I need to process concurrently on Android and I would like to use some sort of a thread pool to do so. I couldn't find in the documentation what actually happens "behind the scenes" when executing an AsyncTask with AsyncTask.THREAD_POOL_EXECUTOR.
My question is: What do I lose by using AsyncTasks with AsyncTask.THREAD_POOL_EXECUTOR as opposed to implementing a custom ThreadPool with Runnables? (Let's talk post-honeycomb).
I realize the question is rather general, but I'm fairly new to doing concurrent programming (besides AsyncTask itself). I'm not looking for a tutorial on concurrent programming! I only seek to understand how the Android specific AsyncTask.THREAD_POOL_EXECUTOR is different. I think an explanation would be helpful for others in the future as they weigh the pros and cons of choosing to use AsyncTask vs Thread/Runnable. Thanks in advance!
AsyncTasks provide you with possibility to execute actions on UI thread before and after executing worker task. So, if you dont need communicating with UI then use your own executor - you can always implement this using handler. AsyncTasks are being executed serially since api 11 because parallel execution was considered to difficult to properly implement.
If you need more flexibility, then executors are a way to go, they will allow you to freely specify how many tasks to execute in parallel, how many to put in queue etc.
If you are interested in details, you can always look into sources:
http://androidxref.com/4.4.3_r1.1/xref/development/samples/training/bitmapfun/BitmapFun/src/main/java/com/example/android/bitmapfun/util/AsyncTask.java
Non-UI work might be taken by anything including AsyncTasks, HandlerThreads, IntentServices etc.
The reason it's suggested AsyncTasks for UI-related works (works that affect UI) is that AsyncTask has helper callbacks that lets you to transfer the control to the UI thread.
However, it's not suggested for longer running operations since it's, by default, uses a global executor and this may cause app-global waiting threads to be stalled while executing long-runnings ops. So you can switch to a custom executor and get rid of global affect.
At the end of the day, HandlerThreads are threads again that gives a Looper to keep the thread alive. Executions will still be done in serial so what's the real reason to use them ? I believe it's the power of ability to execute Runnables like Executors but more in light-weight fashion.
IntentServices are again - the way to execute tasks serially but you've more power and isolation since they're entirely different components has seperate lifecycles. They automatically destroyed so you don't have to worry about destroying them to reduce your app process priority ( off the topic but causes some memory performance problems, trashing etc. )

Does the android.os.Handler class eliminate the need to declare certain methods as synchronized?

In putting together a simple "Clock" application I discovered that Android requires you to use android.os.Handler that lives in Thread A in order to update View objects in Thread A with the results of data that come from Thread B.
I'm still relatively new to Java, and this is the first time I've dealt explicitly with Threads before, but I know that ordinarily you'd declare methods and/or operations as synchronized if two different threads want to access the same data. It appears though, that android.os.Handler is an Android-specific way of synchronizing data between threads such that you avoid the classic concurrency errors detailed in the Oracle documentation I just linked to. Is this really true?
If I were to find myself in a situation such that I were required by the Android OS to use android.os.Handler to ferry data from one thread to another, does that mean I don't have to declare the methods used to derive that data as synchronized?
My understanding:
A Handler is just a mechanism for delivering information between two threads. It's not the only mechanism, but it is the mechanism Google chose to use for adding easy to use methods to Activities to do common tasks.
From the doc
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.
The main thread is running a Handler. The handler is responsible for running your activities and managing the application environment. The Handler is just a message loop which dispatches things from a MessageQueue. This is why your thread has to be running a Looper to create a Handler. To synchronize other stuff you want to do with this effort, you have to insert your requests into this message queue so the main application thread does your work. The ui is written so as long as only one thread accesses the objects, it functions.
I guess the point of this was to point out that the Handler is one mechanism for doing synchronization. Surely, the internals of the MessageQueue are written to take synchronization into account, though its a gross simplification to say 'if multiple threads access it it needs to be synchronized.' Although the UI is the most frequent example, using a Handler and Looper is simply a mechanism for designing a multi-threaded application which provides single thread synchronization for the processing of events.
Whether or not you need to synchronize what you send to a Handler depends greatly on what you are sending. If you are talking about synchronizing the calls to post stuff, then no, the handler takes care of that. If you're talking about code inside a Runnable that you post to a Handler, realize that the only guarantee of the Handler is that your runnable will be executed using the thread that created the Handler. You will need to continue to provide synchronization with other resources.
You only ever need synchronized if you have a shared resource, like an ArrayList or something that can be read from two threads at the same time.
The Handler by itself doesn't prevent any concurrency, it just makes it a lot easier to perform things that need to happen in the UI thread even though a worker thread is trying to do them.
To answer your question: If you use a Handler, it typically means that you do certain critical things in the UI thread. As an example, you have an ArrayList that you initialize in onCreate and then maybe update in a click handler or something. Now if you use a Handler to modify that, then ALL access to the ArrayList will occur in the UI thread, so there is no need for synchronized.
However, as soon as you access that ArrayList from within a worker thread, you WILL need to synchronize every single access to it.
Synchronized, wait and notify are low level concurrency constructs on top of which high level concurrency constructs like semaphores, blocking queues, barriers and Looper/Handler are implemented.
Most of what you see in java.util.concurrent (which implements high level concurrency patterns/constructs) is implemented on top of synchronized, wait and notify (if you ignore the lock free algorithms)
Looper/Handler mechanism in basically a lightweight implementation of producer-consumer pattern where you have one consumer but multiple producers. It was created to easily exchange messages between the UI thread and non UI threads. UI thread in android runs as a single threaded loop (i.e single consumer) but can take in updates from multiple non UI threads (i.e multiple producers via handlers).

Categories