开发者

Java: Best way to retrieve timings form multiple threads

We have 1000 threads that hit a web service and time how long the call takes. We wish for each thread to return their own timing result to the main application, so that various statistics can be recorded. Please note that various tools were considered for this, but for various reasons we need to write our own. What would be the best way for each thread to return the timing - we have considered two options so far :- 1. once a thread has its timing result it calls a singleton that provides a synchronised 开发者_如何学Pythonmethod to write to the file. This ensures that all each thread will write to the file in turn (although in an undetermined order - which is fine), and since the call is done after the timing results have been taken by the thread, then being blocked waiting to write is not really an issue. When all threads have completed, the main application can then read the file to generate the statistics. 2. Using the Executor, Callable and Future interfaces Which would be the best way, or are there any other better ways ? Thanks very much in advance Paul


Use the latter method.

Your workers implement Callable. You then submit them to a threadpool, and get a Future instance for each.

Then just call get() on the Futures to get the results of the calculations.

import java.util.*;
import java.util.concurrent.*;

public class WebServiceTester {

  public static class Tester
        implements Callable {
    public Integer call() {
      Integer start = now();
      //Do your test here
      Integer end = now();
      return end - start;
    }
  }

  public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(1000);
    Set<Future<Integer>> set = new HashSet<Future<Integer>>();
    for (int i =0 ; i < 1000 i++) {
      set.add(pool.submit(new Tester()));
    }
    Set<Integer> results = new Set<Integer>();
    for (Future<Integer> future : set) {
      results.put(future.get());
    }

    //Manipulate results however you wish....
  }
}


Another possible solution I can think of would be to use a CountDownLatch (from the java concurrency packages), each thread decrementing it (flagging they are finished), then once all complete (and the CountDownLatch reaches 0) your main thread can happily go through them all, asking them what their time was.


The executor framework can be implemented here. The time processing can be done by the Callable object. The Future can help you identify if the thread has completed processing.


You could pass an ArrayBlockingQueue to the threads to report their results to. You could then have a file writing thread that takes from the queue to write to the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜