View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.client;
21  
22  
23  import static org.junit.Assert.assertTrue;
24  
25  import java.io.IOException;
26  import java.io.InterruptedIOException;
27  import java.util.ArrayList;
28  import java.util.Arrays;
29  import java.util.HashMap;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.TreeSet;
34  import java.util.concurrent.BlockingQueue;
35  import java.util.concurrent.BrokenBarrierException;
36  import java.util.concurrent.CyclicBarrier;
37  import java.util.concurrent.ExecutorService;
38  import java.util.concurrent.Future;
39  import java.util.concurrent.LinkedBlockingQueue;
40  import java.util.concurrent.RejectedExecutionException;
41  import java.util.concurrent.SynchronousQueue;
42  import java.util.concurrent.ThreadFactory;
43  import java.util.concurrent.ThreadPoolExecutor;
44  import java.util.concurrent.TimeUnit;
45  import java.util.concurrent.atomic.AtomicBoolean;
46  import java.util.concurrent.atomic.AtomicInteger;
47  import java.util.concurrent.atomic.AtomicLong;
48  
49  import org.apache.commons.logging.Log;
50  import org.apache.commons.logging.LogFactory;
51  import org.apache.hadoop.conf.Configuration;
52  import org.apache.hadoop.hbase.CallQueueTooBigException;
53  import org.apache.hadoop.hbase.Cell;
54  import org.apache.hadoop.hbase.HConstants;
55  import org.apache.hadoop.hbase.HRegionInfo;
56  import org.apache.hadoop.hbase.HRegionLocation;
57  import org.apache.hadoop.hbase.RegionLocations;
58  import org.apache.hadoop.hbase.ServerName;
59  import org.apache.hadoop.hbase.TableName;
60  import org.apache.hadoop.hbase.client.AsyncProcess.AsyncRequestFuture;
61  import org.apache.hadoop.hbase.client.coprocessor.Batch;
62  import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback;
63  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
64  import org.apache.hadoop.hbase.testclassification.MediumTests;
65  import org.apache.hadoop.hbase.util.Bytes;
66  import org.apache.hadoop.hbase.util.Threads;
67  import org.junit.Assert;
68  import org.junit.BeforeClass;
69  import org.junit.Rule;
70  import org.junit.Test;
71  import org.junit.experimental.categories.Category;
72  import org.junit.rules.Timeout;
73  import org.mockito.Mockito;
74  
75  @Category(MediumTests.class)
76  public class TestAsyncProcess {
77    private final static Log LOG = LogFactory.getLog(TestAsyncProcess.class);
78    private static final TableName DUMMY_TABLE =
79        TableName.valueOf("DUMMY_TABLE");
80    private static final byte[] DUMMY_BYTES_1 = "DUMMY_BYTES_1".getBytes();
81    private static final byte[] DUMMY_BYTES_2 = "DUMMY_BYTES_2".getBytes();
82    private static final byte[] DUMMY_BYTES_3 = "DUMMY_BYTES_3".getBytes();
83    private static final byte[] FAILS = "FAILS".getBytes();
84    private static final Configuration conf = new Configuration();
85  
86    private static ServerName sn = ServerName.valueOf("s1:1,1");
87    private static ServerName sn2 = ServerName.valueOf("s2:2,2");
88    private static ServerName sn3 = ServerName.valueOf("s3:3,3");
89    private static HRegionInfo hri1 =
90        new HRegionInfo(DUMMY_TABLE, DUMMY_BYTES_1, DUMMY_BYTES_2, false, 1);
91    private static HRegionInfo hri2 =
92        new HRegionInfo(DUMMY_TABLE, DUMMY_BYTES_2, HConstants.EMPTY_END_ROW, false, 2);
93    private static HRegionInfo hri3 =
94        new HRegionInfo(DUMMY_TABLE, DUMMY_BYTES_3, HConstants.EMPTY_END_ROW, false, 3);
95    private static HRegionLocation loc1 = new HRegionLocation(hri1, sn);
96    private static HRegionLocation loc2 = new HRegionLocation(hri2, sn);
97    private static HRegionLocation loc3 = new HRegionLocation(hri3, sn2);
98  
99    // Replica stuff
100   private static HRegionInfo hri1r1 = RegionReplicaUtil.getRegionInfoForReplica(hri1, 1),
101       hri1r2 = RegionReplicaUtil.getRegionInfoForReplica(hri1, 2);
102   private static HRegionInfo hri2r1 = RegionReplicaUtil.getRegionInfoForReplica(hri2, 1);
103   private static RegionLocations hrls1 = new RegionLocations(new HRegionLocation(hri1, sn),
104       new HRegionLocation(hri1r1, sn2), new HRegionLocation(hri1r2, sn3));
105   private static RegionLocations hrls2 = new RegionLocations(new HRegionLocation(hri2, sn2),
106       new HRegionLocation(hri2r1, sn3));
107   private static RegionLocations hrls3 = new RegionLocations(new HRegionLocation(hri3, sn3), null);
108 
109   private static final String success = "success";
110   private static Exception failure = new Exception("failure");
111 
112   private static int NB_RETRIES = 3;
113 
114   @BeforeClass
115   public static void beforeClass(){
116     conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, NB_RETRIES);
117   }
118 
119   static class CountingThreadFactory implements ThreadFactory {
120     final AtomicInteger nbThreads;
121     ThreadFactory realFactory =  Threads.newDaemonThreadFactory("test-TestAsyncProcess");
122     @Override
123     public Thread newThread(Runnable r) {
124       nbThreads.incrementAndGet();
125       return realFactory.newThread(r);
126     }
127 
128     CountingThreadFactory(AtomicInteger nbThreads){
129       this.nbThreads = nbThreads;
130     }
131   }
132 
133   static class MyAsyncProcess extends AsyncProcess {
134     final AtomicInteger nbMultiResponse = new AtomicInteger();
135     final AtomicInteger nbActions = new AtomicInteger();
136     public List<AsyncRequestFuture> allReqs = new ArrayList<AsyncRequestFuture>();
137     public AtomicInteger callsCt = new AtomicInteger();
138 
139     @Override
140     protected <Res> AsyncRequestFutureImpl<Res> createAsyncRequestFuture(TableName tableName,
141         List<Action<Row>> actions, long nonceGroup, ExecutorService pool,
142         Batch.Callback<Res> callback, Object[] results, boolean needResults) {
143       // Test HTable has tableName of null, so pass DUMMY_TABLE
144       AsyncRequestFutureImpl<Res> r = super.createAsyncRequestFuture(
145           DUMMY_TABLE, actions, nonceGroup, pool, callback, results, needResults);
146       allReqs.add(r);
147       callsCt.incrementAndGet();
148       return r;
149     }
150 
151     public MyAsyncProcess(ClusterConnection hc, Configuration conf) {
152       this(hc, conf, new AtomicInteger());
153     }
154 
155     public MyAsyncProcess(ClusterConnection hc, Configuration conf, AtomicInteger nbThreads) {
156       super(hc, conf, new ThreadPoolExecutor(1, 20, 60, TimeUnit.SECONDS,
157           new SynchronousQueue<Runnable>(), new CountingThreadFactory(nbThreads)),
158             new RpcRetryingCallerFactory(conf), false, new RpcControllerFactory(conf));
159     }
160 
161     public MyAsyncProcess(
162         ClusterConnection hc, Configuration conf, boolean useGlobalErrors) {
163       super(hc, conf, new ThreadPoolExecutor(1, 20, 60, TimeUnit.SECONDS,
164         new SynchronousQueue<Runnable>(), new CountingThreadFactory(new AtomicInteger())),
165           new RpcRetryingCallerFactory(conf), useGlobalErrors, new RpcControllerFactory(conf));
166     }
167 
168     public MyAsyncProcess(ClusterConnection hc, Configuration conf, boolean useGlobalErrors,
169         @SuppressWarnings("unused") boolean dummy) {
170       super(hc, conf, new ThreadPoolExecutor(1, 20, 60, TimeUnit.SECONDS,
171               new SynchronousQueue<Runnable>(), new CountingThreadFactory(new AtomicInteger())) {
172         @Override
173         public void execute(Runnable command) {
174           throw new RejectedExecutionException("test under failure");
175         }
176       },
177           new RpcRetryingCallerFactory(conf), useGlobalErrors, new RpcControllerFactory(conf));
178     }
179 
180     @Override
181     public <Res> AsyncRequestFuture submit(TableName tableName, List<? extends Row> rows,
182         boolean atLeastOne, Callback<Res> callback, boolean needResults)
183             throws InterruptedIOException {
184       // We use results in tests to check things, so override to always save them.
185       return super.submit(DUMMY_TABLE, rows, atLeastOne, callback, true);
186     }
187 
188     @Override
189     protected RpcRetryingCaller<MultiResponse> createCaller(MultiServerCallable<Row> callable) {
190       callsCt.incrementAndGet();
191       final MultiResponse mr = createMultiResponse(
192           callable.getMulti(), nbMultiResponse, nbActions, new ResponseGenerator() {
193             @Override
194             public void addResponse(MultiResponse mr, byte[] regionName, Action<Row> a) {
195               if (Arrays.equals(FAILS, a.getAction().getRow())) {
196                 mr.add(regionName, a.getOriginalIndex(), failure);
197               } else {
198                 mr.add(regionName, a.getOriginalIndex(), success);
199               }
200             }
201           });
202 
203       return new RpcRetryingCaller<MultiResponse>(100, 10, 9) {
204         @Override
205         public MultiResponse callWithoutRetries(RetryingCallable<MultiResponse> callable,
206                                                 int callTimeout)
207         throws IOException, RuntimeException {
208           try {
209             // sleep one second in order for threadpool to start another thread instead of reusing
210             // existing one.
211             Thread.sleep(1000);
212           } catch (InterruptedException e) {
213             // ignore error
214           }
215           return mr;
216         }
217       };
218     }
219   }
220 
221   static class CallerWithFailure extends RpcRetryingCaller<MultiResponse>{
222 
223     private final IOException e;
224 
225     public CallerWithFailure(IOException e) {
226       super(100, 100, 9);
227       this.e = e;
228     }
229 
230     @Override
231     public MultiResponse callWithoutRetries(RetryingCallable<MultiResponse> callable, int callTimeout)
232         throws IOException, RuntimeException {
233       throw e;
234     }
235   }
236 
237 
238   static class AsyncProcessWithFailure extends MyAsyncProcess {
239 
240     private final IOException ioe;
241 
242     public AsyncProcessWithFailure(ClusterConnection hc, Configuration conf, IOException ioe) {
243       super(hc, conf, true);
244       this.ioe = ioe;
245       serverTrackerTimeout = 1;
246     }
247 
248     @Override
249     protected RpcRetryingCaller<MultiResponse> createCaller(MultiServerCallable<Row> callable) {
250       callsCt.incrementAndGet();
251       return new CallerWithFailure(ioe);
252     }
253   }
254 
255   class MyAsyncProcessWithReplicas extends MyAsyncProcess {
256     private Set<byte[]> failures = new TreeSet<byte[]>(new Bytes.ByteArrayComparator());
257     private long primarySleepMs = 0, replicaSleepMs = 0;
258     private Map<ServerName, Long> customPrimarySleepMs = new HashMap<ServerName, Long>();
259     private final AtomicLong replicaCalls = new AtomicLong(0);
260 
261     public void addFailures(HRegionInfo... hris) {
262       for (HRegionInfo hri : hris) {
263         failures.add(hri.getRegionName());
264       }
265     }
266 
267     public long getReplicaCallCount() {
268       return replicaCalls.get();
269     }
270 
271     public void setPrimaryCallDelay(ServerName server, long primaryMs) {
272       customPrimarySleepMs.put(server, primaryMs);
273     }
274 
275     public MyAsyncProcessWithReplicas(ClusterConnection hc, Configuration conf) {
276       super(hc, conf);
277     }
278 
279     public void setCallDelays(long primaryMs, long replicaMs) {
280       this.primarySleepMs = primaryMs;
281       this.replicaSleepMs = replicaMs;
282     }
283 
284     @Override
285     protected RpcRetryingCaller<MultiResponse> createCaller(
286         MultiServerCallable<Row> callable) {
287       final MultiResponse mr = createMultiResponse(
288           callable.getMulti(), nbMultiResponse, nbActions, new ResponseGenerator() {
289             @Override
290             public void addResponse(MultiResponse mr, byte[] regionName, Action<Row> a) {
291               if (failures.contains(regionName)) {
292                 mr.add(regionName, a.getOriginalIndex(), failure);
293               } else {
294                 boolean isStale = !RegionReplicaUtil.isDefaultReplica(a.getReplicaId());
295                 mr.add(regionName, a.getOriginalIndex(),
296                     Result.create(new Cell[0], null, isStale));
297               }
298             }
299           });
300       // Currently AsyncProcess either sends all-replica, or all-primary request.
301       final boolean isDefault = RegionReplicaUtil.isDefaultReplica(
302           callable.getMulti().actions.values().iterator().next().iterator().next().getReplicaId());
303       final ServerName server = ((MultiServerCallable<?>)callable).getServerName();
304       String debugMsg = "Call to " + server + ", primary=" + isDefault + " with "
305           + callable.getMulti().actions.size() + " entries: ";
306       for (byte[] region : callable.getMulti().actions.keySet()) {
307         debugMsg += "[" + Bytes.toStringBinary(region) + "], ";
308       }
309       LOG.debug(debugMsg);
310       if (!isDefault) {
311         replicaCalls.incrementAndGet();
312       }
313 
314       return new RpcRetryingCaller<MultiResponse>(100, 10, 9) {
315         @Override
316         public MultiResponse callWithoutRetries(RetryingCallable<MultiResponse> callable, int callTimeout)
317         throws IOException, RuntimeException {
318           long sleep = -1;
319           if (isDefault) {
320             Long customSleep = customPrimarySleepMs.get(server);
321             sleep = (customSleep == null ? primarySleepMs : customSleep.longValue());
322           } else {
323             sleep = replicaSleepMs;
324           }
325           if (sleep != 0) {
326             try {
327               Thread.sleep(sleep);
328             } catch (InterruptedException e) {
329             }
330           }
331           return mr;
332         }
333       };
334     }
335   }
336 
337   static MultiResponse createMultiResponse(final MultiAction<Row> multi,
338       AtomicInteger nbMultiResponse, AtomicInteger nbActions, ResponseGenerator gen) {
339     final MultiResponse mr = new MultiResponse();
340     nbMultiResponse.incrementAndGet();
341     for (Map.Entry<byte[], List<Action<Row>>> entry : multi.actions.entrySet()) {
342       byte[] regionName = entry.getKey();
343       for (Action<Row> a : entry.getValue()) {
344         nbActions.incrementAndGet();
345         gen.addResponse(mr, regionName, a);
346       }
347     }
348     return mr;
349   }
350 
351   private static interface ResponseGenerator {
352     void addResponse(final MultiResponse mr, byte[] regionName, Action<Row> a);
353   }
354 
355   /**
356    * Returns our async process.
357    */
358   static class MyConnectionImpl extends ConnectionManager.HConnectionImplementation {
359     final AtomicInteger nbThreads = new AtomicInteger(0);
360 
361 
362     protected MyConnectionImpl(Configuration conf) {
363       super(conf);
364     }
365 
366     @Override
367     public RegionLocations locateRegion(TableName tableName,
368         byte[] row, boolean useCache, boolean retry, int replicaId) throws IOException {
369       return new RegionLocations(loc1);
370     }
371 
372     @Override
373     public boolean hasCellBlockSupport() {
374       return false;
375     }
376   }
377 
378   /**
379    * Returns our async process.
380    */
381   static class MyConnectionImpl2 extends MyConnectionImpl {
382     List<HRegionLocation> hrl;
383     final boolean usedRegions[];
384 
385     protected MyConnectionImpl2(List<HRegionLocation> hrl) {
386       super(conf);
387       this.hrl = hrl;
388       this.usedRegions = new boolean[hrl.size()];
389     }
390 
391     @Override
392     public RegionLocations locateRegion(TableName tableName,
393         byte[] row, boolean useCache, boolean retry, int replicaId) throws IOException {
394       int i = 0;
395       for (HRegionLocation hr : hrl){
396         if (Arrays.equals(row, hr.getRegionInfo().getStartKey())) {
397           usedRegions[i] = true;
398           return new RegionLocations(hr);
399         }
400         i++;
401       }
402       return null;
403     }
404 
405   }
406 
407   @Rule
408   public Timeout timeout = Timeout.millis(10000); // 10 seconds max per method tested
409 
410   @Test
411   public void testSubmit() throws Exception {
412     ClusterConnection hc = createHConnection();
413     AsyncProcess ap = new MyAsyncProcess(hc, conf);
414 
415     List<Put> puts = new ArrayList<Put>();
416     puts.add(createPut(1, true));
417 
418     ap.submit(DUMMY_TABLE, puts, false, null, false);
419     Assert.assertTrue(puts.isEmpty());
420   }
421 
422   @Test
423   public void testSubmitWithCB() throws Exception {
424     ClusterConnection hc = createHConnection();
425     final AtomicInteger updateCalled = new AtomicInteger(0);
426     Batch.Callback<Object> cb = new Batch.Callback<Object>() {
427       @Override
428       public void update(byte[] region, byte[] row, Object result) {
429         updateCalled.incrementAndGet();
430       }
431     };
432     AsyncProcess ap = new MyAsyncProcess(hc, conf);
433 
434     List<Put> puts = new ArrayList<Put>();
435     puts.add(createPut(1, true));
436 
437     final AsyncRequestFuture ars = ap.submit(DUMMY_TABLE, puts, false, cb, false);
438     Assert.assertTrue(puts.isEmpty());
439     ars.waitUntilDone();
440     Assert.assertEquals(updateCalled.get(), 1);
441   }
442 
443   @Test
444   public void testSubmitBusyRegion() throws Exception {
445     ClusterConnection hc = createHConnection();
446     AsyncProcess ap = new MyAsyncProcess(hc, conf);
447 
448     List<Put> puts = new ArrayList<Put>();
449     puts.add(createPut(1, true));
450 
451     ap.incTaskCounters(Arrays.asList(hri1.getRegionName()), sn);
452     ap.submit(DUMMY_TABLE, puts, false, null, false);
453     Assert.assertEquals(puts.size(), 1);
454 
455     ap.decTaskCounters(Arrays.asList(hri1.getRegionName()), sn);
456     ap.submit(DUMMY_TABLE, puts, false, null, false);
457     Assert.assertEquals(0, puts.size());
458   }
459 
460 
461   @Test
462   public void testSubmitBusyRegionServer() throws Exception {
463     ClusterConnection hc = createHConnection();
464     AsyncProcess ap = new MyAsyncProcess(hc, conf);
465 
466     ap.taskCounterPerServer.put(sn2, new AtomicInteger(ap.maxConcurrentTasksPerServer));
467 
468     List<Put> puts = new ArrayList<Put>();
469     puts.add(createPut(1, true));
470     puts.add(createPut(3, true)); // <== this one won't be taken, the rs is busy
471     puts.add(createPut(1, true)); // <== this one will make it, the region is already in
472     puts.add(createPut(2, true)); // <== new region, but the rs is ok
473 
474     ap.submit(DUMMY_TABLE, puts, false, null, false);
475     Assert.assertEquals(" puts=" + puts, 1, puts.size());
476 
477     ap.taskCounterPerServer.put(sn2, new AtomicInteger(ap.maxConcurrentTasksPerServer - 1));
478     ap.submit(DUMMY_TABLE, puts, false, null, false);
479     Assert.assertTrue(puts.isEmpty());
480   }
481 
482   @Test
483   public void testFail() throws Exception {
484     MyAsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false);
485 
486     List<Put> puts = new ArrayList<Put>();
487     Put p = createPut(1, false);
488     puts.add(p);
489 
490     AsyncRequestFuture ars = ap.submit(DUMMY_TABLE, puts, false, null, true);
491     Assert.assertEquals(0, puts.size());
492     ars.waitUntilDone();
493     verifyResult(ars, false);
494     Assert.assertEquals(NB_RETRIES + 1, ap.callsCt.get());
495 
496     Assert.assertEquals(1, ars.getErrors().exceptions.size());
497     Assert.assertTrue("was: " + ars.getErrors().exceptions.get(0),
498         failure.equals(ars.getErrors().exceptions.get(0)));
499     Assert.assertTrue("was: " + ars.getErrors().exceptions.get(0),
500         failure.equals(ars.getErrors().exceptions.get(0)));
501 
502     Assert.assertEquals(1, ars.getFailedOperations().size());
503     Assert.assertTrue("was: " + ars.getFailedOperations().get(0),
504         p.equals(ars.getFailedOperations().get(0)));
505   }
506 
507 
508   @Test
509   public void testSubmitTrue() throws IOException {
510     final AsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false);
511     ap.tasksInProgress.incrementAndGet();
512     final AtomicInteger ai = new AtomicInteger(1);
513     ap.taskCounterPerRegion.put(hri1.getRegionName(), ai);
514 
515     final AtomicBoolean checkPoint = new AtomicBoolean(false);
516     final AtomicBoolean checkPoint2 = new AtomicBoolean(false);
517 
518     Thread t = new Thread(){
519       @Override
520       public void run(){
521         Threads.sleep(1000);
522         Assert.assertFalse(checkPoint.get()); // TODO: this is timing-dependent
523         ai.decrementAndGet();
524         ap.tasksInProgress.decrementAndGet();
525         checkPoint2.set(true);
526       }
527     };
528 
529     List<Put> puts = new ArrayList<Put>();
530     Put p = createPut(1, true);
531     puts.add(p);
532 
533     ap.submit(DUMMY_TABLE, puts, false, null, false);
534     Assert.assertFalse(puts.isEmpty());
535 
536     t.start();
537 
538     ap.submit(DUMMY_TABLE, puts, true, null, false);
539     Assert.assertTrue(puts.isEmpty());
540 
541     checkPoint.set(true);
542     while (!checkPoint2.get()){
543       Threads.sleep(1);
544     }
545   }
546 
547   @Test
548   public void testFailAndSuccess() throws Exception {
549     MyAsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false);
550 
551     List<Put> puts = new ArrayList<Put>();
552     puts.add(createPut(1, false));
553     puts.add(createPut(1, true));
554     puts.add(createPut(1, true));
555 
556     AsyncRequestFuture ars = ap.submit(DUMMY_TABLE, puts, false, null, true);
557     Assert.assertTrue(puts.isEmpty());
558     ars.waitUntilDone();
559     verifyResult(ars, false, true, true);
560     Assert.assertEquals(NB_RETRIES + 1, ap.callsCt.get());
561     ap.callsCt.set(0);
562     Assert.assertEquals(1, ars.getErrors().actions.size());
563 
564     puts.add(createPut(1, true));
565     // Wait for AP to be free. While ars might have the result, ap counters are decreased later.
566     ap.waitUntilDone();
567     ars = ap.submit(DUMMY_TABLE, puts, false, null, true);
568     Assert.assertEquals(0, puts.size());
569     ars.waitUntilDone();
570     Assert.assertEquals(2, ap.callsCt.get());
571     verifyResult(ars, true);
572   }
573 
574   @Test
575   public void testFlush() throws Exception {
576     MyAsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false);
577 
578     List<Put> puts = new ArrayList<Put>();
579     puts.add(createPut(1, false));
580     puts.add(createPut(1, true));
581     puts.add(createPut(1, true));
582 
583     AsyncRequestFuture ars = ap.submit(DUMMY_TABLE, puts, false, null, true);
584     ars.waitUntilDone();
585     verifyResult(ars, false, true, true);
586     Assert.assertEquals(NB_RETRIES + 1, ap.callsCt.get());
587 
588     Assert.assertEquals(1, ars.getFailedOperations().size());
589   }
590 
591   @Test
592   public void testMaxTask() throws Exception {
593     final AsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false);
594 
595     for (int i = 0; i < 1000; i++) {
596       ap.incTaskCounters(Arrays.asList("dummy".getBytes()), sn);
597     }
598 
599     final Thread myThread = Thread.currentThread();
600 
601     Thread t = new Thread() {
602       @Override
603       public void run() {
604         Threads.sleep(2000);
605         myThread.interrupt();
606       }
607     };
608 
609     List<Put> puts = new ArrayList<Put>();
610     puts.add(createPut(1, true));
611 
612     t.start();
613 
614     try {
615       ap.submit(DUMMY_TABLE, puts, false, null, false);
616       Assert.fail("We should have been interrupted.");
617     } catch (InterruptedIOException expected) {
618     }
619 
620     final long sleepTime = 2000;
621 
622     Thread t2 = new Thread() {
623       @Override
624       public void run() {
625         Threads.sleep(sleepTime);
626         while (ap.tasksInProgress.get() > 0) {
627           ap.decTaskCounters(Arrays.asList("dummy".getBytes()), sn);
628         }
629       }
630     };
631     t2.start();
632 
633     long start = System.currentTimeMillis();
634     ap.submit(DUMMY_TABLE, new ArrayList<Row>(), false, null, false);
635     long end = System.currentTimeMillis();
636 
637     //Adds 100 to secure us against approximate timing.
638     Assert.assertTrue(start + 100L + sleepTime > end);
639   }
640 
641   private static ClusterConnection createHConnection() throws IOException {
642     ClusterConnection hc = createHConnectionCommon();
643     setMockLocation(hc, DUMMY_BYTES_1, new RegionLocations(loc1));
644     setMockLocation(hc, DUMMY_BYTES_2, new RegionLocations(loc2));
645     setMockLocation(hc, DUMMY_BYTES_3, new RegionLocations(loc3));
646     setMockLocation(hc, FAILS, new RegionLocations(loc2));
647     return hc;
648   }
649 
650   private static ClusterConnection createHConnectionWithReplicas() throws IOException {
651     ClusterConnection hc = createHConnectionCommon();
652     setMockLocation(hc, DUMMY_BYTES_1, hrls1);
653     setMockLocation(hc, DUMMY_BYTES_2, hrls2);
654     setMockLocation(hc, DUMMY_BYTES_3, hrls3);
655     return hc;
656   }
657 
658   private static void setMockLocation(ClusterConnection hc, byte[] row,
659       RegionLocations result) throws IOException {
660     Mockito.when(hc.locateRegion(Mockito.eq(DUMMY_TABLE), Mockito.eq(row),
661         Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyInt())).thenReturn(result);
662   }
663 
664   private static ClusterConnection createHConnectionCommon() {
665     ClusterConnection hc = Mockito.mock(ClusterConnection.class);
666     NonceGenerator ng = Mockito.mock(NonceGenerator.class);
667     Mockito.when(ng.getNonceGroup()).thenReturn(HConstants.NO_NONCE);
668     Mockito.when(hc.getNonceGenerator()).thenReturn(ng);
669     Mockito.when(hc.getConfiguration()).thenReturn(conf);
670     return hc;
671   }
672 
673   @Test
674   public void testHTablePutSuccess() throws Exception {
675     BufferedMutatorImpl ht = Mockito.mock(BufferedMutatorImpl.class);
676     ht.ap = new MyAsyncProcess(createHConnection(), conf, true);
677 
678     Put put = createPut(1, true);
679 
680     Assert.assertEquals(0, ht.getWriteBufferSize());
681     ht.mutate(put);
682     Assert.assertEquals(0, ht.getWriteBufferSize());
683   }
684 
685   private void doHTableFailedPut(boolean bufferOn) throws Exception {
686     ClusterConnection conn = createHConnection();
687     HTable ht = new HTable(conn, new BufferedMutatorParams(DUMMY_TABLE));
688     MyAsyncProcess ap = new MyAsyncProcess(conn, conf, true);
689     ht.mutator.ap = ap;
690     if (bufferOn) {
691       ht.setWriteBufferSize(1024L * 1024L);
692     } else {
693       ht.setWriteBufferSize(0L);
694     }
695 
696     Put put = createPut(1, false);
697 
698     Assert.assertEquals(0L, ht.mutator.currentWriteBufferSize.get());
699     try {
700       ht.put(put);
701       if (bufferOn) {
702         ht.flushCommits();
703       }
704       Assert.fail();
705     } catch (RetriesExhaustedException expected) {
706     }
707     Assert.assertEquals(0L, ht.mutator.currentWriteBufferSize.get());
708     // The table should have sent one request, maybe after multiple attempts
709     AsyncRequestFuture ars = null;
710     for (AsyncRequestFuture someReqs : ap.allReqs) {
711       if (someReqs.getResults().length == 0) continue;
712       Assert.assertTrue(ars == null);
713       ars = someReqs;
714     }
715     Assert.assertTrue(ars != null);
716     verifyResult(ars, false);
717 
718     // This should not raise any exception, puts have been 'received' before by the catch.
719     ht.close();
720   }
721 
722   @Test
723   public void testHTableFailedPutWithBuffer() throws Exception {
724     doHTableFailedPut(true);
725   }
726 
727   @Test
728   public void testHTableFailedPutWithoutBuffer() throws Exception {
729     doHTableFailedPut(false);
730   }
731 
732   @Test
733   public void testHTableFailedPutAndNewPut() throws Exception {
734     ClusterConnection conn = createHConnection();
735     BufferedMutatorImpl mutator = new BufferedMutatorImpl(conn, null, null,
736         new BufferedMutatorParams(DUMMY_TABLE).writeBufferSize(0));
737     MyAsyncProcess ap = new MyAsyncProcess(conn, conf, true);
738     mutator.ap = ap;
739 
740     Put p = createPut(1, false);
741     mutator.mutate(p);
742 
743     ap.waitUntilDone(); // Let's do all the retries.
744 
745     // We're testing that we're behaving as we were behaving in 0.94: sending exceptions in the
746     //  doPut if it fails.
747     // This said, it's not a very easy going behavior. For example, when we insert a list of
748     //  puts, we may raise an exception in the middle of the list. It's then up to the caller to
749     //  manage what was inserted, what was tried but failed, and what was not even tried.
750     p = createPut(1, true);
751     Assert.assertEquals(0, mutator.getWriteBuffer().size());
752     try {
753       mutator.mutate(p);
754       Assert.fail();
755     } catch (RetriesExhaustedException expected) {
756     }
757     Assert.assertEquals("the put should not been inserted.", 0, mutator.getWriteBuffer().size());
758   }
759 
760   @Test
761   public void testBatch() throws IOException, InterruptedException {
762     ClusterConnection conn = new MyConnectionImpl(conf);
763     HTable ht = new HTable(conn, new BufferedMutatorParams(DUMMY_TABLE));
764     ht.multiAp = new MyAsyncProcess(conn, conf, false);
765 
766     List<Put> puts = new ArrayList<Put>();
767     puts.add(createPut(1, true));
768     puts.add(createPut(1, true));
769     puts.add(createPut(1, true));
770     puts.add(createPut(1, true));
771     puts.add(createPut(1, false)); // <=== the bad apple, position 4
772     puts.add(createPut(1, true));
773     puts.add(createPut(1, false)); // <=== another bad apple, position 6
774 
775     Object[] res = new Object[puts.size()];
776     try {
777       ht.processBatch(puts, res);
778       Assert.fail();
779     } catch (RetriesExhaustedException expected) {
780     }
781 
782     Assert.assertEquals(res[0], success);
783     Assert.assertEquals(res[1], success);
784     Assert.assertEquals(res[2], success);
785     Assert.assertEquals(res[3], success);
786     Assert.assertEquals(res[4], failure);
787     Assert.assertEquals(res[5], success);
788     Assert.assertEquals(res[6], failure);
789   }
790 
791   @Test
792   public void testErrorsServers() throws IOException {
793     Configuration configuration = new Configuration(conf);
794     ClusterConnection conn = new MyConnectionImpl(configuration);
795     BufferedMutatorImpl mutator =
796         new BufferedMutatorImpl(conn, null, null, new BufferedMutatorParams(DUMMY_TABLE));
797     configuration.setBoolean(ConnectionManager.RETRIES_BY_SERVER_KEY, true);
798 
799     MyAsyncProcess ap = new MyAsyncProcess(conn, configuration, true);
800     mutator.ap = ap;
801 
802     Assert.assertNotNull(mutator.ap.createServerErrorTracker());
803     Assert.assertTrue(mutator.ap.serverTrackerTimeout > 200);
804     mutator.ap.serverTrackerTimeout = 1;
805 
806     Put p = createPut(1, false);
807     mutator.mutate(p);
808 
809     try {
810       mutator.flush();
811       Assert.fail();
812     } catch (RetriesExhaustedWithDetailsException expected) {
813     }
814     // Checking that the ErrorsServers came into play and didn't make us stop immediately
815     Assert.assertEquals(NB_RETRIES + 1, ap.callsCt.get());
816   }
817 
818   @Test
819   public void testGlobalErrors() throws IOException {
820     ClusterConnection conn = new MyConnectionImpl(conf);
821     BufferedMutatorImpl mutator = (BufferedMutatorImpl) conn.getBufferedMutator(DUMMY_TABLE);
822     AsyncProcessWithFailure ap = new AsyncProcessWithFailure(conn, conf, new IOException("test"));
823     mutator.ap = ap;
824 
825     Assert.assertNotNull(mutator.ap.createServerErrorTracker());
826 
827     Put p = createPut(1, true);
828     mutator.mutate(p);
829 
830     try {
831       mutator.flush();
832       Assert.fail();
833     } catch (RetriesExhaustedWithDetailsException expected) {
834     }
835     // Checking that the ErrorsServers came into play and didn't make us stop immediately
836     Assert.assertEquals(NB_RETRIES + 1, ap.callsCt.get());
837   }
838 
839 
840   @Test
841   public void testCallQueueTooLarge() throws IOException {
842     ClusterConnection conn = new MyConnectionImpl(conf);
843     BufferedMutatorImpl mutator = (BufferedMutatorImpl) conn.getBufferedMutator(DUMMY_TABLE);
844     AsyncProcessWithFailure ap = new AsyncProcessWithFailure(conn, conf, new CallQueueTooBigException());
845     mutator.ap = ap;
846 
847     Assert.assertNotNull(mutator.ap.createServerErrorTracker());
848 
849     Put p = createPut(1, true);
850     mutator.mutate(p);
851 
852     try {
853       mutator.flush();
854       Assert.fail();
855     } catch (RetriesExhaustedWithDetailsException expected) {
856     }
857     // Checking that the ErrorsServers came into play and didn't make us stop immediately
858     Assert.assertEquals(NB_RETRIES + 1, ap.callsCt.get());
859   }
860   /**
861    * This test simulates multiple regions on 2 servers. We should have 2 multi requests and
862    *  2 threads: 1 per server, this whatever the number of regions.
863    */
864   @Test
865   public void testThreadCreation() throws Exception {
866     final int NB_REGS = 100;
867     List<HRegionLocation> hrls = new ArrayList<HRegionLocation>(NB_REGS);
868     List<Get> gets = new ArrayList<Get>(NB_REGS);
869     for (int i = 0; i < NB_REGS; i++) {
870       HRegionInfo hri = new HRegionInfo(
871           DUMMY_TABLE, Bytes.toBytes(i * 10L), Bytes.toBytes(i * 10L + 9L), false, i);
872       HRegionLocation hrl = new HRegionLocation(hri, i % 2 == 0 ? sn : sn2);
873       hrls.add(hrl);
874 
875       Get get = new Get(Bytes.toBytes(i * 10L));
876       gets.add(get);
877     }
878 
879     MyConnectionImpl2 con = new MyConnectionImpl2(hrls);
880     HTable ht = new HTable(con, new BufferedMutatorParams(DUMMY_TABLE));
881     MyAsyncProcess ap = new MyAsyncProcess(con, conf, con.nbThreads);
882     ht.multiAp = ap;
883 
884     ht.batch(gets, new Object[gets.size()]);
885 
886     Assert.assertEquals(ap.nbActions.get(), NB_REGS);
887     Assert.assertEquals("1 multi response per server", 2, ap.nbMultiResponse.get());
888     Assert.assertEquals("1 thread per server", 2, con.nbThreads.get());
889 
890     int nbReg = 0;
891     for (int i =0; i<NB_REGS; i++){
892       if (con.usedRegions[i]) nbReg++;
893     }
894     Assert.assertEquals("nbReg=" + nbReg, nbReg, NB_REGS);
895   }
896 
897   @Test
898   public void testReplicaReplicaSuccess() throws Exception {
899     // Main call takes too long so replicas succeed, except for one region w/o replicas.
900     // One region has no replica, so the main call succeeds for it.
901     MyAsyncProcessWithReplicas ap = createReplicaAp(10, 1000, 0);
902     List<Get> rows = makeTimelineGets(DUMMY_BYTES_1, DUMMY_BYTES_2, DUMMY_BYTES_3);
903     AsyncRequestFuture ars = ap.submitAll(DUMMY_TABLE, rows, null, new Object[3]);
904     verifyReplicaResult(ars, RR.TRUE, RR.TRUE, RR.FALSE);
905     Assert.assertEquals(2, ap.getReplicaCallCount());
906   }
907 
908   @Test
909   public void testReplicaPrimarySuccessWoReplicaCalls() throws Exception {
910     // Main call succeeds before replica calls are kicked off.
911     MyAsyncProcessWithReplicas ap = createReplicaAp(1000, 10, 0);
912     List<Get> rows = makeTimelineGets(DUMMY_BYTES_1, DUMMY_BYTES_2, DUMMY_BYTES_3);
913     AsyncRequestFuture ars = ap.submitAll(DUMMY_TABLE, rows, null, new Object[3]);
914     verifyReplicaResult(ars, RR.FALSE, RR.FALSE, RR.FALSE);
915     Assert.assertEquals(0, ap.getReplicaCallCount());
916   }
917 
918   @Test
919   public void testReplicaParallelCallsSucceed() throws Exception {
920     // Either main or replica can succeed.
921     MyAsyncProcessWithReplicas ap = createReplicaAp(0, 0, 0);
922     List<Get> rows = makeTimelineGets(DUMMY_BYTES_1, DUMMY_BYTES_2);
923     AsyncRequestFuture ars = ap.submitAll(DUMMY_TABLE, rows, null, new Object[2]);
924     verifyReplicaResult(ars, RR.DONT_CARE, RR.DONT_CARE);
925     long replicaCalls = ap.getReplicaCallCount();
926     Assert.assertTrue(replicaCalls >= 0);
927     Assert.assertTrue(replicaCalls <= 2);
928   }
929 
930   @Test
931   public void testReplicaPartialReplicaCall() throws Exception {
932     // One server is slow, so the result for its region comes from replica, whereas
933     // the result for other region comes from primary before replica calls happen.
934     // There should be no replica call for that region at all.
935     MyAsyncProcessWithReplicas ap = createReplicaAp(1000, 0, 0);
936     ap.setPrimaryCallDelay(sn2, 2000);
937     List<Get> rows = makeTimelineGets(DUMMY_BYTES_1, DUMMY_BYTES_2);
938     AsyncRequestFuture ars = ap.submitAll(DUMMY_TABLE, rows, null, new Object[2]);
939     verifyReplicaResult(ars, RR.FALSE, RR.TRUE);
940     Assert.assertEquals(1, ap.getReplicaCallCount());
941   }
942 
943   @Test
944   public void testReplicaMainFailsBeforeReplicaCalls() throws Exception {
945     // Main calls fail before replica calls can start - this is currently not handled.
946     // It would probably never happen if we can get location (due to retries),
947     // and it would require additional synchronization.
948     MyAsyncProcessWithReplicas ap = createReplicaAp(1000, 0, 0, 1);
949     ap.addFailures(hri1, hri2);
950     List<Get> rows = makeTimelineGets(DUMMY_BYTES_1, DUMMY_BYTES_2);
951     AsyncRequestFuture ars = ap.submitAll(DUMMY_TABLE, rows, null, new Object[2]);
952     verifyReplicaResult(ars, RR.FAILED, RR.FAILED);
953     Assert.assertEquals(0, ap.getReplicaCallCount());
954   }
955 
956   @Test
957   public void testReplicaReplicaSuccessWithParallelFailures() throws Exception {
958     // Main calls fails after replica calls start. For two-replica region, one replica call
959     // also fails. Regardless, we get replica results for both regions.
960     MyAsyncProcessWithReplicas ap = createReplicaAp(0, 1000, 1000, 1);
961     ap.addFailures(hri1, hri1r2, hri2);
962     List<Get> rows = makeTimelineGets(DUMMY_BYTES_1, DUMMY_BYTES_2);
963     AsyncRequestFuture ars = ap.submitAll(DUMMY_TABLE, rows, null, new Object[2]);
964     verifyReplicaResult(ars, RR.TRUE, RR.TRUE);
965     Assert.assertEquals(2, ap.getReplicaCallCount());
966   }
967 
968   @Test
969   public void testReplicaAllCallsFailForOneRegion() throws Exception {
970     // For one of the region, all 3, main and replica, calls fail. For the other, replica
971     // call fails but its exception should not be visible as it did succeed.
972     MyAsyncProcessWithReplicas ap = createReplicaAp(500, 1000, 0, 1);
973     ap.addFailures(hri1, hri1r1, hri1r2, hri2r1);
974     List<Get> rows = makeTimelineGets(DUMMY_BYTES_1, DUMMY_BYTES_2);
975     AsyncRequestFuture ars = ap.submitAll(DUMMY_TABLE, rows, null, new Object[2]);
976     verifyReplicaResult(ars, RR.FAILED, RR.FALSE);
977     // We should get 3 exceptions, for main + 2 replicas for DUMMY_BYTES_1
978     Assert.assertEquals(3, ars.getErrors().getNumExceptions());
979     for (int i = 0; i < ars.getErrors().getNumExceptions(); ++i) {
980       Assert.assertArrayEquals(DUMMY_BYTES_1, ars.getErrors().getRow(i).getRow());
981     }
982   }
983 
984   private MyAsyncProcessWithReplicas createReplicaAp(
985       int replicaAfterMs, int primaryMs, int replicaMs) throws Exception {
986     return createReplicaAp(replicaAfterMs, primaryMs, replicaMs, -1);
987   }
988 
989   private MyAsyncProcessWithReplicas createReplicaAp(
990       int replicaAfterMs, int primaryMs, int replicaMs, int retries) throws Exception {
991     // TODO: this is kind of timing dependent... perhaps it should detect from createCaller
992     //       that the replica call has happened and that way control the ordering.
993     Configuration conf = new Configuration();
994     ClusterConnection conn = createHConnectionWithReplicas();
995     conf.setInt(AsyncProcess.PRIMARY_CALL_TIMEOUT_KEY, replicaAfterMs * 1000);
996     if (retries > 0) {
997       conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, retries);
998     }
999     MyAsyncProcessWithReplicas ap = new MyAsyncProcessWithReplicas(conn, conf);
1000     ap.setCallDelays(primaryMs, replicaMs);
1001     return ap;
1002   }
1003 
1004   private static List<Get> makeTimelineGets(byte[]... rows) {
1005     List<Get> result = new ArrayList<Get>();
1006     for (byte[] row : rows) {
1007       Get get = new Get(row);
1008       get.setConsistency(Consistency.TIMELINE);
1009       result.add(get);
1010     }
1011     return result;
1012   }
1013 
1014   private void verifyResult(AsyncRequestFuture ars, boolean... expected) throws Exception {
1015     Object[] actual = ars.getResults();
1016     Assert.assertEquals(expected.length, actual.length);
1017     for (int i = 0; i < expected.length; ++i) {
1018       Assert.assertEquals(expected[i], !(actual[i] instanceof Throwable));
1019     }
1020   }
1021 
1022   /** After reading TheDailyWtf, I always wanted to create a MyBoolean enum like this! */
1023   private enum RR {
1024     TRUE,
1025     FALSE,
1026     DONT_CARE,
1027     FAILED
1028   }
1029 
1030   private void verifyReplicaResult(AsyncRequestFuture ars, RR... expecteds) throws Exception {
1031     Object[] actuals = ars.getResults();
1032     Assert.assertEquals(expecteds.length, actuals.length);
1033     for (int i = 0; i < expecteds.length; ++i) {
1034       Object actual = actuals[i];
1035       RR expected = expecteds[i];
1036       Assert.assertEquals(actual.toString(), expected == RR.FAILED, actual instanceof Throwable);
1037       if (expected != RR.FAILED && expected != RR.DONT_CARE) {
1038         Assert.assertEquals(expected == RR.TRUE, ((Result)actual).isStale());
1039       }
1040     }
1041   }
1042 
1043   /**
1044    * @param regCnt  the region: 1 to 3.
1045    * @param success if true, the put will succeed.
1046    * @return a put
1047    */
1048   private Put createPut(int regCnt, boolean success) {
1049     Put p;
1050     if (!success) {
1051       p = new Put(FAILS);
1052     } else switch (regCnt){
1053       case 1 :
1054         p = new Put(DUMMY_BYTES_1);
1055         break;
1056       case 2:
1057         p = new Put(DUMMY_BYTES_2);
1058         break;
1059       case 3:
1060         p = new Put(DUMMY_BYTES_3);
1061         break;
1062       default:
1063         throw new IllegalArgumentException("unknown " + regCnt);
1064     }
1065 
1066     p.add(DUMMY_BYTES_1, DUMMY_BYTES_1, DUMMY_BYTES_1);
1067 
1068     return p;
1069   }
1070 
1071   static class MyThreadPoolExecutor extends ThreadPoolExecutor {
1072     public MyThreadPoolExecutor(int coreThreads, int maxThreads, long keepAliveTime,
1073         TimeUnit timeunit, BlockingQueue<Runnable> blockingqueue) {
1074       super(coreThreads, maxThreads, keepAliveTime, timeunit, blockingqueue);
1075     }
1076 
1077     @Override
1078     public Future submit(Runnable runnable) {
1079       throw new OutOfMemoryError("OutOfMemory error thrown by means");
1080     }
1081   }
1082 
1083   static class AsyncProcessForThrowableCheck extends AsyncProcess {
1084     public AsyncProcessForThrowableCheck(ClusterConnection hc, Configuration conf,
1085         ExecutorService pool) {
1086       super(hc, conf, pool, new RpcRetryingCallerFactory(conf), false, new RpcControllerFactory(
1087           conf));
1088     }
1089   }
1090 
1091   @Test
1092   public void testUncheckedException() throws Exception {
1093     // Test the case pool.submit throws unchecked exception
1094     ClusterConnection hc = createHConnection();
1095     MyThreadPoolExecutor myPool =
1096         new MyThreadPoolExecutor(1, 20, 60, TimeUnit.SECONDS,
1097             new LinkedBlockingQueue<Runnable>(200));
1098     AsyncProcess ap = new AsyncProcessForThrowableCheck(hc, conf, myPool);
1099 
1100     List<Put> puts = new ArrayList<Put>();
1101     puts.add(createPut(1, true));
1102 
1103     ap.submit(DUMMY_TABLE, puts, false, null, false);
1104     Assert.assertTrue(puts.isEmpty());
1105   }
1106 
1107   @Test
1108   public void testWaitForMaximumCurrentTasks() throws Exception {
1109     final AtomicLong tasks = new AtomicLong(0);
1110     final AtomicInteger max = new AtomicInteger(0);
1111     final CyclicBarrier barrier = new CyclicBarrier(2);
1112     final AsyncProcess ap = new MyAsyncProcess(createHConnection(), conf);
1113     Runnable runnable = new Runnable() {
1114       @Override
1115       public void run() {
1116         try {
1117           barrier.await();
1118           ap.waitForMaximumCurrentTasks(max.get(), tasks, 1, null);
1119         } catch (InterruptedIOException e) {
1120           Assert.fail(e.getMessage());
1121         } catch (InterruptedException e) {
1122           // TODO Auto-generated catch block
1123           e.printStackTrace();
1124         } catch (BrokenBarrierException e) {
1125           // TODO Auto-generated catch block
1126           e.printStackTrace();
1127         }
1128       }
1129     };
1130     // First test that our runnable thread only exits when tasks is zero.
1131     Thread t = new Thread(runnable);
1132     t.start();
1133     barrier.await();
1134     t.join();
1135     // Now assert we stay running if max == zero and tasks is > 0.
1136     barrier.reset();
1137     tasks.set(1000000);
1138     t = new Thread(runnable);
1139     t.start();
1140     barrier.await();
1141     while (tasks.get() > 0) {
1142       assertTrue(t.isAlive());
1143       tasks.set(tasks.get() - 1);
1144     }
1145     t.join();
1146   }
1147 }