SofaTracerRunnable implements Runnable { @Override public void run() { if (Thread.currentThread().getId() != tid) { if (currentSpan != null) { traceContext.push(currentSpan); SpanExtensionFactory.logStartedSpan(currentSpan); } } try { wrappedRunnable.run(); } finally { if (Thread.currentThread().getId() != tid) { if (currentSpan != null) { traceContext.pop(); } } } } SofaTracerRunnable(Runnable wrappedRunnable);  SofaTracerRunnable(Runnable wrappedRunnable, SofaTraceContext traceContext); @Override void run();  }
@Test public void testInstrumentedRunnable() { Runnable wrappedRunnable = mock(Runnable.class); SofaTracerRunnable runnable = new SofaTracerRunnable(wrappedRunnable, traceContext); runnable.run(); verify(traceContext, times(1)).getCurrentSpan(); verify(traceContext, times(1)).isEmpty(); verify(wrappedRunnable, times(1)).run(); verifyNoMoreInteractions(traceContext, wrappedRunnable); }
@Test public void testInstrumentedRunnableNoCurrentSpan() { when(traceContext.isEmpty()).thenReturn(true); Runnable wrappedRunnable = mock(Runnable.class); SofaTracerRunnable runnable = new SofaTracerRunnable(wrappedRunnable, traceContext); runnable.run(); verify(traceContext, times(1)).isEmpty(); verify(wrappedRunnable, times(1)).run(); verifyNoMoreInteractions(traceContext, wrappedRunnable); }
@Test public void sofaTracerRunnableSamples() throws InterruptedException { SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); SofaTracerSpan sofaTracerSpan = mock((SofaTracerSpan.class)); sofaTraceContext.push(sofaTracerSpan); RunnableTread runnableTread = new RunnableTread(); SofaTracerRunnable sofaTracerRunnable = new SofaTracerRunnable(runnableTread, sofaTraceContext); sofaTracerRunnable.run(); assertEquals(1, sofaTraceContext.getThreadLocalSpanSize()); assertEquals(Thread.currentThread().getId(), runnableTread.getThreadId()); assertEquals(Thread.currentThread().getName(), runnableTread.getThreadName()); Thread thread = new Thread(sofaTracerRunnable); thread.start(); Thread.sleep(3 * 1000); assertEquals(1, sofaTraceContext.getThreadLocalSpanSize()); assertEquals(2, runnableTread.atomicLong.get()); assertNotEquals(Thread.currentThread().getId(), runnableTread.getThreadId()); assertNotEquals(Thread.currentThread().getName(), runnableTread.getThreadName()); }