Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 16d2494a authored by Treehugger Robot's avatar Treehugger Robot Committed by Android (Google) Code Review
Browse files

Merge "Wait until the thread is waiting before issuing next task" into main

parents 176c5931 670df0a2
Loading
Loading
Loading
Loading
+28 −0
Original line number Diff line number Diff line
@@ -86,6 +86,34 @@ class PersisterQueue {
        mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThread");
    }

    /**
     * Busy wait until {@link #mLazyTaskWriterThread} is in {@link Thread.State#WAITING}, or
     * times out. This indicates the thread is waiting for new tasks to appear. If the wait
     * succeeds, this queue waits at least {@link #mPreTaskDelayMs} milliseconds before running the
     * next task.
     *
     * <p>This is for testing purposes only.
     *
     * @param timeoutMillis the maximum time of waiting in milliseconds
     * @return {@code true} if the thread is in {@link Thread.State#WAITING} at return
     */
    @VisibleForTesting
    boolean waitUntilWritingThreadIsWaiting(long timeoutMillis) {
        final long timeoutTime = SystemClock.uptimeMillis() + timeoutMillis;
        do {
            Thread.State state;
            synchronized (this) {
                state = mLazyTaskWriterThread.getState();
            }
            if (state == Thread.State.WAITING) {
                return true;
            }
            Thread.yield();
        } while (SystemClock.uptimeMillis() < timeoutTime);

        return false;
    }

    synchronized void startPersisting() {
        if (!mLazyTaskWriterThread.isAlive()) {
            mLazyTaskWriterThread.start();
+6 −5
Original line number Diff line number Diff line
@@ -177,15 +177,16 @@ public class PersisterQueueTests {
        assertTrue("Target didn't call callback enough times.",
                mListener.waitForAllExpectedCallbackDone(TIMEOUT_ALLOWANCE));

        // Wait until writing thread is waiting, which indicates the thread is waiting for new tasks
        // to appear.
        assertTrue("Failed to wait until the writing thread is waiting.",
                mTarget.waitUntilWritingThreadIsWaiting(TIMEOUT_ALLOWANCE));

        // Second item
        mFactory.setExpectedProcessedItemNumber(1);
        mListener.setExpectedOnPreProcessItemCallbackTimes(1);
        dispatchTime = SystemClock.uptimeMillis();
        // Synchronize on the instance to make sure we schedule the item after it starts to wait for
        // task indefinitely.
        synchronized (mTarget) {
        mTarget.addItem(mFactory.createItem(), false);
        }
        assertTrue("Target didn't process item enough times.",
                mFactory.waitForAllExpectedItemsProcessed(PRE_TASK_DELAY_MS + TIMEOUT_ALLOWANCE));
        assertEquals("Target didn't process all items.", 2, mFactory.getTotalProcessedItemCount());