java-urlconnections停止连接?

eimct9ow  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(119)

我正在做一个家庭作业,这个作业的目的是展示增加线程的数量如何帮助或损害程序的性能。其基本思想是通过线程处理来自网站的单个数据请求,然后确定同时运行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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题