Skip to content

Commit

Permalink
Fixing a bug that caused BackgroundThreadPosterTestDouble to hang whe…
Browse files Browse the repository at this point in the history
…n multiple runnables with interdependencies and nested calls to BackgroundThreadPosterTestDouble were involved.
  • Loading branch information
techyourchance committed Jun 12, 2019
1 parent d71e956 commit 5a45218
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@
@Override
public void post(Runnable runnable) {
synchronized (MONITOR) {
mRunnables.add(runnable);
mNonCompletedRunnables++;
MONITOR.notifyAll();
}
mRunnables.add(runnable);
}

@Override
Expand Down Expand Up @@ -61,12 +62,11 @@ public void run() {
}

/**
* Call to this method will block until all {@link Runnable}s sent for execution by this
* "test double" BEFORE THE MOMENT OF A CALL will be completed.<br>
* Call to this method allows to establish a happens-before relationship between the
* {@link Runnable}s sent for execution and any subsequent code.
* Execute all {@link Runnable}s posted to this "test double". The caller will block until the operation completes<br>
* Call to this method allows to establish a happens-before relationship between the previously
* posted {@link Runnable}s and subsequent code.
*/
public void join() {
/* pp */ void join() {
synchronized (MONITOR) {
Runnable runnable;
while (mNonCompletedRunnables > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public void post(final Runnable runnable) {
* Call to this method allows to establish a happens-before relationship between the previously
* posted {@link Runnable}s and subsequent code.
*/
public void join() {
/* pp */ void join() {
final Thread fakeUiThread = new Thread() {
@Override
public void run() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,40 @@ public void run() {
assertThat(counter.getCount(), is(2));
}

@Test
public void executeThenJoin_multipleNestedRunnablesInterdependent_sideEffectsVisibleAfterJoin() throws Exception {
// Arrange
final Counter counter = new Counter();
final Semaphore semaphore = new Semaphore(0);
final Runnable runnable1 = new Runnable() {
@Override
public void run() {
semaphore.release();
counter.increment();
}
};
final Runnable runnable2 = new Runnable() {
@Override
public void run() {
SUT.post(runnable1);
semaphore.acquireUninterruptibly();
counter.increment();
}
};
final Runnable runnable3 = new Runnable() {
@Override
public void run() {
SUT.post(runnable2);
counter.increment();
}
};
// Act
SUT.post(runnable3);
// Assert
SUT.join();
assertThat(counter.getCount(), is(3));
}

/**
* This class will be used in order to check side effects in tests
*/
Expand Down

0 comments on commit 5a45218

Please sign in to comment.