如何使用多线程定期获取服务器状态

huangapple go评论92阅读模式
英文:

How to get server status using multi-threads periodically

问题

以下是代码的翻译部分:

  1. 下面的代码运行良好它连接到给定的服务器主机端口并获取连接状态
  2. 它的功能是
  3. 1. PollService 实现了 Callable 接口连接到服务器主机端口),然后返回状态
  4. 2. 由于这应该定期发生它在一个 while(true) 循环中迭代 Hashmap 条目
  5. 问题在服务器端我发现它需要23秒才能到达线程如果我使用带有定期实现的 Runnable它将在1秒内连接看起来无限迭代 Hashmap 是一种缓慢的方法
  6. 然而我不能使用 Runnable因为它不会返回我后面需要使用的连接状态
  7. 下面是连接到服务器的 ServiceMonitor 客户端)。
  8. package org.example;
  9. import java.time.LocalDateTime;
  10. import java.util.ArrayList;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.concurrent.ExecutionException;
  15. import java.util.concurrent.ExecutorService;
  16. import java.util.concurrent.Executors;
  17. import java.util.concurrent.Future;
  18. import java.util.logging.Level;
  19. import java.util.logging.Logger;
  20. import java.util.stream.Collectors;
  21. public class ServicesMonitor {
  22. private ExecutorService scheduledExecutorService = null;
  23. private static Logger logger = Logger.getLogger(ServicesMonitor.class.getName());
  24. private final Map<ServiceType, List<ClientMonitorService>> clientMonitorServicesMap = new HashMap<>();
  25. public void registerInterest(ClientMonitorService clientMonitorService) {
  26. clientMonitorServicesMap.computeIfAbsent(clientMonitorService.getServiceToMonitor().getServiceType(), v -> new ArrayList<>()).add(clientMonitorService);
  27. }
  28. public Map<ServiceType, List<ClientMonitorService>> getClientMonitorService() {
  29. return clientMonitorServicesMap;
  30. }
  31. public void poll(){
  32. //Observable.interval(1, TimeUnit.SECONDS).st
  33. }
  34. public void pollServices() {
  35. scheduledExecutorService = Executors.newFixedThreadPool(clientMonitorServicesMap.size());
  36. try {
  37. while (true) {
  38. clientMonitorServicesMap.forEach((k, v) -> {
  39. Future<Boolean> val = scheduledExecutorService.submit(new PollService(k));
  40. try {
  41. boolean result = val.get();
  42. System.out.println("service " + k.getHost() + ":" + k.getPort() + " status is " + result);
  43. if (result) {
  44. List<ClientMonitorService> list = v.stream().filter(a -> LocalDateTime.now().getSecond() % a.getServiceToMonitor().getFreqSec() == 0)
  45. .collect(Collectors.toList());
  46. list.stream().forEach(a -> System.out.println(a.getClientId()));
  47. }
  48. } catch (InterruptedException e) {
  49. e.printStackTrace();
  50. } catch (ExecutionException e) {
  51. e.printStackTrace();
  52. }
  53. });
  54. }
  55. } catch (Exception e) {
  56. logger.log(Level.SEVERE, e.getMessage());
  57. } finally {
  58. scheduledExecutorService.shutdown();
  59. }
  60. }
  61. }
  • 如何通过减少连接到服务器所需的时间来改善此代码的性能?
  • 如何改进此代码?
英文:

The below code works fine and it connects to a given server (host, port) and gets the connection status.

What it does is:

  1. PollService implements the Callable interface and connects to a server(host, port) then it returns the status.
  2. Since this should happen periodically, it iterates the Hashmap entries in a while(true) loop infinitely.

The problem: On the server-side, I see it takes 2 or 3 seconds to reach the thread and if I use Runnable with periodic implementation it connects within 1 sec. Looks like iterating the Hashmap infinitely is a slow approach.

However, I can not use Runnable as it doesn't return the status of the connection which I need later to use.

Below is the ServiceMonitor class (client) which connects to the server.

  1. package org.example;
  2. import java.time.LocalDateTime;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.concurrent.ExecutionException;
  8. import java.util.concurrent.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.Future;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13. import java.util.stream.Collectors;
  14. public class ServicesMonitor {
  15. private ExecutorService scheduledExecutorService = null;
  16. private static Logger logger = Logger.getLogger(ServicesMonitor.class.getName());
  17. private final Map&lt;ServiceType, List&lt;ClientMonitorService&gt;&gt; clientMonitorServicesMap = new HashMap&lt;&gt;();
  18. public void registerInterest(ClientMonitorService clientMonitorService) {
  19. clientMonitorServicesMap.computeIfAbsent(clientMonitorService.getServiceToMonitor().getServiceType(), v -&gt; new ArrayList&lt;&gt;()).add(clientMonitorService);
  20. }
  21. public Map&lt;ServiceType, List&lt;ClientMonitorService&gt;&gt; getClineMonitorService() {
  22. return clientMonitorServicesMap;
  23. }
  24. public void poll(){
  25. //Observable.interval(1, TimeUnit.SECONDS).st
  26. }
  27. public void pollServices() {
  28. scheduledExecutorService = Executors.newFixedThreadPool(clientMonitorServicesMap.size());
  29. try {
  30. while (true) {
  31. clientMonitorServicesMap.forEach((k, v) -&gt; {
  32. Future&lt;Boolean&gt; val = scheduledExecutorService.submit(new PollService(k));
  33. try {
  34. boolean result = val.get();
  35. System.out.println(&quot;service &quot; + k.getHost() + &quot;:&quot; + k.getPort() + &quot;status is &quot; + result);
  36. if (result) {
  37. List&lt;ClientMonitorService&gt; list = v.stream().filter(a -&gt; LocalDateTime.now().getSecond() % a.getServiceToMonitor().getFreqSec() == 0)
  38. .collect(Collectors.toList());
  39. list.stream().forEach(a -&gt; System.out.println(a.getClientId()));
  40. }
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. } catch (ExecutionException e) {
  44. e.printStackTrace();
  45. }
  46. });
  47. }
  48. } catch (Exception e) {
  49. logger.log(Level.SEVERE, e.getMessage());
  50. } finally {
  51. scheduledExecutorService.shutdown();
  52. }
  53. }
  54. }
  • How to improve the performance of this code by reducing the time it takes to connect to the server?
  • How to improve this code?

答案1

得分: 0

使用get(1, TimeUnit.SECONDS)后,我也开始在服务器端看到了改进(线程达到不到1秒)因为在客户端我们不再等待超过1秒。

  1. while (true) {
  2. clientMonitorServicesMap.forEach((k, v) -> {
  3. Future<Boolean> val = scheduledExecutorService.submit(new PollService(k));
  4. try {
  5. boolean result = val.get(1, TimeUnit.SECONDS);
  6. System.out.println("service " + k.getHost() + ":" + k.getPort() + " status is " + result);
  7. if (result) {
  8. List<ClientMonitorService> list = v.stream()
  9. //.filter(a -> LocalDateTime.now().getSecond() % a.getServiceToMonitor().getFreqSec() == 0)
  10. .collect(Collectors.toList());
  11. list.stream().forEach(a -> System.out.println(a.getClientId()));
  12. }
  13. } catch (InterruptedException e) {
  14. logger.log(Level.WARNING, "Interrupted -> " + k.getHost() + ":" + k.getPort());
  15. } catch (ExecutionException e) {
  16. logger.log(Level.INFO, "ExecutionException exception -> " + k.getHost() + ":" + k.getPort());
  17. } catch (TimeoutException e) {
  18. logger.log(Level.INFO, "TimeoutException exception -> " + k.getHost() + ":" + k.getPort());
  19. }
  20. });
  21. }
英文:

after using the get(1, TimeUnit.SECONDS); I started to see improvement on the server side as well (Reaching the threads less than 1 second) since we are not waiting more than 1 second on the client side.

  1. while (true) {
  2. clientMonitorServicesMap.forEach((k, v) -&gt; {
  3. Future&lt;Boolean&gt; val = scheduledExecutorService.submit(new PollService(k));
  4. try {
  5. boolean result = val.get(1, TimeUnit.SECONDS);
  6. System.out.println(&quot;service &quot; + k.getHost() + &quot;:&quot; + k.getPort() + &quot;status is &quot; + result);
  7. if (result) {
  8. List&lt;ClientMonitorService&gt; list = v.stream()
  9. //.filter(a -&gt; LocalDateTime.now().getSecond() % a.getServiceToMonitor().getFreqSec() == 0)
  10. .collect(Collectors.toList());
  11. list.stream().forEach(a -&gt; System.out.println(a.getClientId()));
  12. }
  13. } catch (InterruptedException e) {
  14. logger.log(Level.WARNING,&quot;Interrupted -&gt; &quot; + k.getHost()+&quot;:&quot;+k.getPort());
  15. } catch (ExecutionException e) {
  16. logger.log(Level.INFO,&quot;ExecutionException exception -&gt; &quot;+ k.getHost()+&quot;:&quot;+k.getPort());
  17. } catch (TimeoutException e) {
  18. logger.log(Level.INFO,&quot;TimeoutException exception -&gt; &quot;+ k.getHost()+&quot;:&quot;+k.getPort());
  19. }
  20. });
  21. }

huangapple
  • 本文由 发表于 2020年9月29日 11:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64112611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定