This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Fork join
pyricau edited this page Jan 14, 2012
·
8 revisions
Since AndroidAnnotations 1.0
Let's say you want to split a background operation into two separate operations that run concurrently, and then do something on the UI thread when both are done.
Here is a simple way to implement this, thanks to @Background
and @UiThread
.
@EActivity
public class MyActivity extends Activity {
// Instances should only be accessed from the UI Thread to guarantee thread safety
static class ResultHolder {
ResultA resultA;
ResultB resultB;
}
// Multiple clicks will start multiple distinguished computations
@Click(R.id.myButton)
void startForkableComputation() {
ResultHolder resultHolder = new ResultHolder();
computeResultA(resultHolder);
computeResultB(resultHolder);
}
@Background
void computeResultA(ResultHolder resultHolder) {
ResultA resultA = new ResultA();
// Do some stuff with resultA
joinWork(resultHolder, resultA, null);
}
@Background
void computeResultB(ResultHolder resultHolder) {
ResultB resultB = new ResultB();
// Do some stuff with resultB
joinWork(resultHolder, null, resultB);
}
@UiThread
void joinWork(ResultHolder resultHolder, ResultA resultA, ResultB resultB) {
if (resultA != null)
resultHolder.resultA = resultA;
if (resultB != null)
resultHolder.resultB = resultB;
if (resultHolder.resultA == null || resultHolder.resultB == null) {
return;
}
// Show the results on the UI Thread
}
}
This works because we are joining the work in the Ui Thread, which is always the same thread. We also ensure that we always access ResultHolder
from the Ui Thread.
Note by @pyricau: although I'm quite sure everything here is right and safe, I just received Java Concurrency in Practice from Amazon, so I'll read it with this fork / join use case in mind!
19/11/2020 The 4.8.0 release is out !
- Get started!
- Cookbook, full of recipes
- Customize annotation processing
- List of all available annotations
- Release Notes
- Examples
- Read the FAQ
- Join the Mailing list
- Create an issue
- Tag on Stack Overflow
- Ask on Gitter