サービスのパフォーマンステストを実行しようとしています。そこで、そのためのマルチスレッドプログラムを作成しました。いくつかのスレッドで並行してサービスにアクセスし、各スレッドが戻るのにかかる時間を測定します。
私が更新を行ってマップに乗る方法はスレッドセーフになります。右?このMutltithreadingプログラムをデバッグして、プログラムが正しく機能しているかどうかを確認するのは非常に難しいと感じています。誰かがこのマルチスレッドプログラムで私を助けることができますか
private static ConcurrentHashMap<Long, Long> histogram = new ConcurrentHashMap<Long, Long>();
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1 * 1000; i++) {
service.submit(new ThreadTask(i, histogram));
}
service.shutdown();
while (!service.isTerminated()) {
}
ThreadTask.report();
}
class ThreadTask implements Runnable {
private int id;
private RestTemplate restTemplate = new RestTemplate();
private String result;
private static ConcurrentHashMap<Long, Long> mapData;
public ThreadTask(int id, ConcurrentHashMap<Long, Long> histogram) {
this.id = id;
this.mapData = histogram;
}
@Override
public void run() {
long start_time = System.currentTimeMillis();
result = restTemplate.getForObject("", String.class);
long difference = (System.currentTimeMillis() - start_time);
Long count = getMethod(mapData, difference);
if (count != null) {
count++;
putMethod(mapData, difference, count);
} else {
putMethod(mapData, difference, Long.valueOf(1L));
}
}
private synchronized void putMethod(ConcurrentHashMap<Long, Long> hg2, long difference, Long count) {
hg2.put(Long.valueOf(difference), count);
}
private synchronized Long getMethod(ConcurrentHashMap<Long, Long> hg2, long difference) {
return hg2.get(difference);
}
public static void report() {
System.out.println(mapData);
}
}
以下の提案に基づいてコードベースを更新-
private static RestTemplate restTemplate = new RestTemplate();
private static String result = null;
private static ConcurrentHashMap<Long, AtomicLong> histogram = new ConcurrentHashMap<Long, AtomicLong>();
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1 * 1000; i++) {
service.submit(new ThreadTask(i, histogram));
}
service.shutdown();
while (!service.isTerminated()) {
}
ThreadTask.report();
}
class ThreadTask implements Runnable {
private int id;
private static RestTemplate restTemplate = new RestTemplate();
private String result;
private static ConcurrentHashMap<Long, AtomicLong> hg;
public ThreadTask(int id, ConcurrentHashMap<Long, AtomicLong> histogram) {
this.id = id;
this.hg = histogram;
}
@Override
public void run() {
long start_time = System.currentTimeMillis();
result = restTemplate.getForObject("", String.class);
long difference = (System.currentTimeMillis() - start_time);
final AtomicLong before = hg.putIfAbsent(difference, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
}
public static void report() {
System.out.println(mapData);
}
}
誰かが見て、今回私がそれを正しくしたかどうか私に知らせてもらえますか?