001/* 002 * SonarQube 003 * Copyright (C) 2009-2016 SonarSource SA 004 * mailto:contact AT sonarsource DOT com 005 * 006 * This program is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020package org.sonar.test; 021 022import java.util.ArrayList; 023import java.util.List; 024import java.util.concurrent.ExecutionException; 025import java.util.concurrent.ExecutorService; 026import java.util.concurrent.Executors; 027import java.util.concurrent.Future; 028import org.junit.rules.TestRule; 029import org.junit.runner.Description; 030import org.junit.runners.model.Statement; 031 032public class RunTestsMultipleTimes implements TestRule { 033 final int threads; 034 final int times; 035 036 public RunTestsMultipleTimes(int times, int threads) { 037 this.times = times; 038 this.threads = threads; 039 } 040 041 @Override 042 public Statement apply(final Statement base, Description description) { 043 return new Statement() { 044 @Override 045 public void evaluate() throws Throwable { 046 ExecutorService executor = Executors.newFixedThreadPool(threads); 047 048 List<Future<?>> results = new ArrayList<>(); 049 050 for (int i = 0; i < times; i++) { 051 final int index = i; 052 053 results.add(executor.submit(new Runnable() { 054 @Override 055 public void run() { 056 try { 057 System.out.println(index); 058 base.evaluate(); 059 } catch (RuntimeException e) { 060 throw e; 061 } catch (Throwable e) { 062 throw new IllegalStateException(e); 063 } 064 } 065 })); 066 } 067 068 for (Future<?> result : results) { 069 try { 070 result.get(); 071 } catch (ExecutionException e) { 072 throw e.getCause(); 073 } 074 } 075 076 executor.shutdown(); 077 } 078 }; 079 } 080}