Merge "After joinReceiver, we don't expect more events so stop parsing"
diff --git a/src/com/android/tradefed/result/proto/StreamProtoReceiver.java b/src/com/android/tradefed/result/proto/StreamProtoReceiver.java
index df6df56..f674906 100644
--- a/src/com/android/tradefed/result/proto/StreamProtoReceiver.java
+++ b/src/com/android/tradefed/result/proto/StreamProtoReceiver.java
@@ -49,6 +49,12 @@
     private long mExtraWaitTimeForEvents = 0L;
 
     /**
+     * Stop parsing events when this is set. This allows to avoid a thread parsing the events when
+     * we don't expect them anymore.
+     */
+    private boolean mStopParsing = false;
+
+    /**
      * Ctor.
      *
      * @param listener the {@link ITestInvocationListener} where to report the results.
@@ -184,6 +190,8 @@
             } catch (InterruptedException e) {
                 CLog.e(e);
                 throw new RuntimeException(e);
+            } finally {
+                mStopParsing = true;
             }
         }
         return true;
@@ -195,6 +203,12 @@
     }
 
     private void parse(TestRecord receivedRecord) {
+        if (mStopParsing) {
+            CLog.i(
+                    "Skip parsing of %s. It came after joinReceiver.",
+                    receivedRecord.getTestRecordId());
+            return;
+        }
         try {
             TestLevel level = mParser.processNewProto(receivedRecord);
             if (TestLevel.MODULE.equals(level)) {
diff --git a/tests/src/com/android/tradefed/result/proto/StreamProtoResultReporterTest.java b/tests/src/com/android/tradefed/result/proto/StreamProtoResultReporterTest.java
index 640940b..64f2eac 100644
--- a/tests/src/com/android/tradefed/result/proto/StreamProtoResultReporterTest.java
+++ b/tests/src/com/android/tradefed/result/proto/StreamProtoResultReporterTest.java
@@ -125,6 +125,29 @@
         assertNull(receiver.getError());
     }
 
+    /** Once the join receiver is done, we don't parse any more events. */
+    @Test
+    public void testStream_stopParsing() throws Exception {
+        StreamProtoReceiver receiver =
+                new StreamProtoReceiver(mMockListener, mMainInvocationContext, true);
+        OptionSetter setter = new OptionSetter(mReporter);
+        try {
+            setter.setOptionValue(
+                    "proto-report-port", Integer.toString(receiver.getSocketServerPort()));
+            // No calls on the mocks
+            EasyMock.replay(mMockListener);
+            // If we join, then we will stop parsing events
+            receiver.joinReceiver(100);
+            mReporter.invocationStarted(mInvocationContext);
+            // Invocation ends
+            mReporter.invocationEnded(500L);
+        } finally {
+            receiver.close();
+        }
+        EasyMock.verify(mMockListener);
+        assertNull(receiver.getError());
+    }
+
     @Test
     public void testStream_noInvocationReporting() throws Exception {
         StreamProtoReceiver receiver =