3333import java .util .List ;
3434import java .util .concurrent .TimeUnit ;
3535import java .util .regex .Pattern ;
36- import org .junit .After ;
37- import org .junit .Before ;
36+ import org .junit .AfterClass ;
37+ import org .junit .BeforeClass ;
3838import org .junit .ClassRule ;
3939import org .junit .Test ;
4040import org .junit .experimental .categories .Category ;
@@ -47,13 +47,13 @@ public class ITSpannerOptionsTest {
4747 @ ClassRule public static IntegrationTestEnv env = new IntegrationTestEnv ();
4848 private static Database db ;
4949
50- @ Before
51- public void setUp () throws Exception {
50+ @ BeforeClass
51+ public static void setUp () throws Exception {
5252 db = env .getTestHelper ().createTestDatabase ();
5353 }
5454
55- @ After
56- public void tearDown () throws Exception {
55+ @ AfterClass
56+ public static void tearDown () throws Exception {
5757 db .drop ();
5858 }
5959
@@ -65,9 +65,9 @@ public void tearDown() throws Exception {
6565
6666 @ Test
6767 public void testCloseAllThreadsWhenClosingSpanner () throws InterruptedException {
68- // The IT environment has already started some worker threads.
6968 int baseThreadCount = getNumberOfThreadsWithName (SPANNER_THREAD_NAME );
7069 for (int i = 0 ; i < NUMBER_OF_TEST_RUNS ; i ++) {
70+ waitForStartup ();
7171 assertThat (getNumberOfThreadsWithName (SPANNER_THREAD_NAME )).isAtMost (baseThreadCount );
7272 // Create Spanner instance.
7373 // We make a copy of the options instance, as SpannerOptions caches any service object
@@ -136,6 +136,7 @@ public void testCloseAllThreadsWhenClosingSpanner() throws InterruptedException
136136
137137 @ Test
138138 public void testMultipleSpannersFromSameSpannerOptions () throws InterruptedException {
139+ waitForStartup ();
139140 int baseThreadCount = getNumberOfThreadsWithName (SPANNER_THREAD_NAME );
140141 SpannerOptions options = env .getTestHelper ().getOptions ().toBuilder ().build ();
141142 try (Spanner spanner1 = options .getService ()) {
@@ -167,6 +168,17 @@ public void testMultipleSpannersFromSameSpannerOptions() throws InterruptedExcep
167168 assertThat (getNumberOfThreadsWithName (SPANNER_THREAD_NAME )).isAtMost (baseThreadCount );
168169 }
169170
171+ private void waitForStartup () throws InterruptedException {
172+ // Wait until the IT environment has already started all base worker threads.
173+ int threadCount ;
174+ Stopwatch watch = Stopwatch .createStarted ();
175+ do {
176+ threadCount = getNumberOfThreadsWithName (SPANNER_THREAD_NAME );
177+ Thread .sleep (100L );
178+ } while (getNumberOfThreadsWithName (SPANNER_THREAD_NAME ) > threadCount
179+ && watch .elapsed (TimeUnit .SECONDS ) < 5 );
180+ }
181+
170182 private int getNumberOfThreadsWithName (String serviceName ) {
171183 Pattern pattern = Pattern .compile (String .format (THREAD_PATTERN , serviceName ));
172184 ThreadGroup group = Thread .currentThread ().getThreadGroup ();
0 commit comments