我'm working on a homework assignment that has the purpose of showing how increasing the number of threads can help or hurt a program'的表现 . 基本思想是对来自网站的各个数据请求进行处理,然后确定在同时运行n个查询时执行所有查询所需的时间 .

我认为我已经正确完成了线程和时钟,但是有些奇怪的事情正在发生 . 我正在使用 java.net.URLConnection 来连接数据库 . 我的前三千个左右的连接将成功并加载 . 然后,几百个左右的调用失败,没有任何Java在指定的超时期限内尝试过的证据 .

我在一个线程中运行的代码如下:

/* This code to get the contents from an URL was adapted from a
 * StackOverflow question found at http://goo.gl/QPqR4 .
 */
private static String loadContent(String address) throws Exception {
  String toReturn = "";

  try {
    URL url = new URL(address);
    URLConnection con = url.openConnection();
    con.setConnectTimeout(5000);
    con.setReadTimeout(5000);
    InputStream stream = con.getInputStream();
    Reader r = new InputStreamReader(stream, "ISO-8859-1");

    while (true) {
      int ch = r.read();
      if (ch < 0) {
        break;
      }
      toReturn += (char) ch;
    }

    r.close();
    stream.close();
  } catch (Exception e) {
    System.out.println(address + ": " + e.getMessage());
    throw e;
  }

  return toReturn;
}

运行线程的代码如下 . NormalPerformance 类是我为简化计算一系列观察的均值和方差而编写的类 .

/* This code is patterned after code provided by my professor.
 */
private static NormalPerformance performExperiment(int threads, int runs)
  throws Exception
{
  NormalPerformance toReturn = new NormalPerformance();

  for (int i = 0; i < runs; i++) {
    final List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
    for (int j = 0; j < URLS.length; j++) {
      final String url = URLS[i];
      tasks.add(new Callable<Void>() {
        public Void call() throws Exception {
          loadContent(url);
          return null;
        }
      });
    }

    long start = System.nanoTime();
    final ExecutorService exectuorPool = Executors.newFixedThreadPool(threads);
    executorPool.invokeAll(tasks);
    executorPool.shutdown();
    double time = (System.nano() - start) / 1000000000.;
    toReturn.addObservation(time);

    System.out.println("" + threads + " " + (i + 1) + ": " + time);
  }

  return toReturn;
}

为什么我会看到这种奇怪的成功和失败模式?甚至更奇怪的是,有时杀死程序并重新启动无助于阻止故障的运行 . 我已经尝试过强迫线程休眠,调用 System.gc() ,增加连接和读取超时值的事情,但是没有一个单独或组合修复了这个问题 .

我怎样才能保证我的连接最有可能连接?

环境:Windows 7 64位,Eclipse Juno 64位,JRE 7