resolve merge conflicts of d043a840f7 to nyc-mr2-dev-plus-aosp

Test: Clean merge
Change-Id: Ib2420ff793fdf22fd80cfaed7848ff6b8be8d382
This commit is contained in:
Philip P. Moltmann
2017-02-14 09:43:23 -08:00
3 changed files with 58 additions and 169 deletions

View File

@@ -16,197 +16,86 @@
package android.app; package android.app;
import android.os.Handler; import java.util.concurrent.ConcurrentLinkedQueue;
import android.os.HandlerThread; import java.util.concurrent.ExecutorService;
import android.os.Looper; import java.util.concurrent.Executors;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import com.android.internal.annotations.GuardedBy;
import java.util.LinkedList;
/** /**
* Internal utility class to keep track of process-global work that's outstanding and hasn't been * Internal utility class to keep track of process-global work that's
* finished yet. * outstanding and hasn't been finished yet.
* *
* New work will be {@link #queue queued}. * This was created for writing SharedPreference edits out
* * asynchronously so we'd have a mechanism to wait for the writes in
* It is possible to add 'finisher'-runnables that are {@link #waitToFinish guaranteed to be run}. * Activity.onPause and similar places, but we may use this mechanism
* This is used to make sure the work has been finished. * for other things in the future.
*
* This was created for writing SharedPreference edits out asynchronously so we'd have a mechanism
* to wait for the writes in Activity.onPause and similar places, but we may use this mechanism for
* other things in the future.
*
* The queued asynchronous work is performed on a separate, dedicated thread.
* *
* @hide * @hide
*/ */
public class QueuedWork { public class QueuedWork {
private static final String LOG_TAG = QueuedWork.class.getSimpleName();
/** Delay for delayed runnables */ // The set of Runnables that will finish or wait on any async
private static final long DELAY = 50; // activities started by the application.
private static final ConcurrentLinkedQueue<Runnable> sPendingWorkFinishers =
new ConcurrentLinkedQueue<Runnable>();
/** Lock for this class */ private static ExecutorService sSingleThreadExecutor = null; // lazy, guarded by class
private static final Object sLock = new Object();
/** Finishers {@link #addFinisher added} and not yet {@link #removeFinisher removed} */
@GuardedBy("sLock")
private static final LinkedList<Runnable> sFinishers = new LinkedList<>();
/** {@link #getHandler() Lazily} created handler */
@GuardedBy("sLock")
private static Handler sHandler = null;
/** Work queued via {@link #queue} */
@GuardedBy("sLock")
private static final LinkedList<Runnable> sWork = new LinkedList<>();
/** If new work can be delayed or not */
@GuardedBy("sLock")
private static boolean sCanDelay = true;
/** /**
* Lazily create a handler on a separate thread. * Returns a single-thread Executor shared by the entire process,
* * creating it if necessary.
* @return the handler
*/ */
private static Handler getHandler() { public static ExecutorService singleThreadExecutor() {
synchronized (sLock) { synchronized (QueuedWork.class) {
if (sHandler == null) { if (sSingleThreadExecutor == null) {
HandlerThread handlerThread = new HandlerThread("queued-work-looper", // TODO: can we give this single thread a thread name?
Process.THREAD_PRIORITY_BACKGROUND); sSingleThreadExecutor = Executors.newSingleThreadExecutor();
handlerThread.start();
sHandler = new QueuedWorkHandler(handlerThread.getLooper());
} }
return sHandler; return sSingleThreadExecutor;
} }
} }
/** /**
* Add a finisher-runnable to wait for {@link #queue asynchronously processed work}. * Add a runnable to finish (or wait for) a deferred operation
* started in this context earlier. Typically finished by e.g.
* an Activity#onPause. Used by SharedPreferences$Editor#startCommit().
* *
* Used by SharedPreferences$Editor#startCommit(). * Note that this doesn't actually start it running. This is just
* * a scratch set for callers doing async work to keep updated with
* Note that this doesn't actually start it running. This is just a scratch set for callers * what's in-flight. In the common case, caller code
* doing async work to keep updated with what's in-flight. In the common case, caller code * (e.g. SharedPreferences) will pretty quickly call remove()
* (e.g. SharedPreferences) will pretty quickly call remove() after an add(). The only time * after an add(). The only time these Runnables are run is from
* these Runnables are run is from {@link #waitToFinish}. * waitToFinish(), below.
*
* @param finisher The runnable to add as finisher
*/ */
public static void addFinisher(Runnable finisher) { public static void add(Runnable finisher) {
synchronized (sLock) { sPendingWorkFinishers.add(finisher);
sFinishers.add(finisher); }
}
public static void remove(Runnable finisher) {
sPendingWorkFinishers.remove(finisher);
} }
/** /**
* Remove a previously {@link #addFinisher added} finisher-runnable. * Finishes or waits for async operations to complete.
* (e.g. SharedPreferences$Editor#startCommit writes)
* *
* @param finisher The runnable to remove. * Is called from the Activity base class's onPause(), after
*/ * BroadcastReceiver's onReceive, after Service command handling,
public static void removeFinisher(Runnable finisher) { * etc. (so async work is never lost)
synchronized (sLock) {
sFinishers.remove(finisher);
}
}
/**
* Trigger queued work to be processed immediately. The queued work is processed on a separate
* thread asynchronous. While doing that run and process all finishers on this thread. The
* finishers can be implemented in a way to check weather the queued work is finished.
*
* Is called from the Activity base class's onPause(), after BroadcastReceiver's onReceive,
* after Service command handling, etc. (so async work is never lost)
*/ */
public static void waitToFinish() { public static void waitToFinish() {
Handler handler = getHandler(); Runnable toFinish;
while ((toFinish = sPendingWorkFinishers.poll()) != null) {
synchronized (sLock) { toFinish.run();
if (handler.hasMessages(QueuedWorkHandler.MSG_RUN)) {
// Force the delayed work to be processed now
handler.removeMessages(QueuedWorkHandler.MSG_RUN);
handler.sendEmptyMessage(QueuedWorkHandler.MSG_RUN);
}
// We should not delay any work as this might delay the finishers
sCanDelay = false;
}
try {
while (true) {
Runnable finisher;
synchronized (sLock) {
finisher = sFinishers.poll();
}
if (finisher == null) {
break;
}
finisher.run();
}
} finally {
sCanDelay = true;
} }
} }
/** /**
* Queue a work-runnable for processing asynchronously. * Returns true if there is pending work to be done. Note that the
* * result is out of data as soon as you receive it, so be careful how you
* @param work The new runnable to process * use it.
* @param shouldDelay If the message should be delayed
*/
public static void queue(Runnable work, boolean shouldDelay) {
Handler handler = getHandler();
synchronized (sLock) {
sWork.add(work);
if (shouldDelay && sCanDelay) {
handler.sendEmptyMessageDelayed(QueuedWorkHandler.MSG_RUN, DELAY);
} else {
handler.sendEmptyMessage(QueuedWorkHandler.MSG_RUN);
}
}
}
/**
* @return True iff there is any {@link #queue async work queued}.
*/ */
public static boolean hasPendingWork() { public static boolean hasPendingWork() {
synchronized (sLock) { return !sPendingWorkFinishers.isEmpty();
return !sWork.isEmpty();
}
}
private static class QueuedWorkHandler extends Handler {
static final int MSG_RUN = 1;
QueuedWorkHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
if (msg.what == MSG_RUN) {
LinkedList<Runnable> work;
synchronized (sWork) {
work = (LinkedList<Runnable>) sWork.clone();
sWork.clear();
// Remove all msg-s as all work will be processed now
removeMessages(MSG_RUN);
}
work.forEach(Runnable::run);
}
}
} }
} }

View File

@@ -379,12 +379,12 @@ final class SharedPreferencesImpl implements SharedPreferences {
} }
}; };
QueuedWork.addFinisher(awaitCommit); QueuedWork.add(awaitCommit);
Runnable postWriteRunnable = new Runnable() { Runnable postWriteRunnable = new Runnable() {
public void run() { public void run() {
awaitCommit.run(); awaitCommit.run();
QueuedWork.removeFinisher(awaitCommit); QueuedWork.remove(awaitCommit);
} }
}; };
@@ -557,10 +557,10 @@ final class SharedPreferencesImpl implements SharedPreferences {
} }
if (DEBUG) { if (DEBUG) {
Log.d(TAG, "queued " + mcr.memoryStateGeneration + " -> " + mFile.getName()); Log.d(TAG, "added " + mcr.memoryStateGeneration + " -> " + mFile.getName());
} }
QueuedWork.queue(writeToDiskRunnable, !isFromSyncCommit); QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);
} }
private static FileOutputStream createFileOutputStream(File file) { private static FileOutputStream createFileOutputStream(File file) {

View File

@@ -211,16 +211,16 @@ public abstract class BroadcastReceiver {
// of the list to finish the broadcast, so we don't block this // of the list to finish the broadcast, so we don't block this
// thread (which may be the main thread) to have it finished. // thread (which may be the main thread) to have it finished.
// //
// Note that we don't need to use QueuedWork.addFinisher() with the // Note that we don't need to use QueuedWork.add() with the
// runnable, since we know the AM is waiting for us until the // runnable, since we know the AM is waiting for us until the
// executor gets to it. // executor gets to it.
QueuedWork.queue(new Runnable() { QueuedWork.singleThreadExecutor().execute( new Runnable() {
@Override public void run() { @Override public void run() {
if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG, if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
"Finishing broadcast after work to component " + mToken); "Finishing broadcast after work to component " + mToken);
sendFinished(mgr); sendFinished(mgr);
} }
}, false); });
} else { } else {
if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG, if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
"Finishing broadcast to component " + mToken); "Finishing broadcast to component " + mToken);