Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. public final class HttpClientPool {
  2. private static HttpClientPool instance = null;
  3. private PoolingHttpClientConnectionManager manager;
  4. private IdleConnectionMonitorThread monitorThread;
  5. private final CloseableHttpClient client;
  6.  
  7. public static HttpClientPool getInstance() {
  8. if (instance == null) {
  9. synchronized(HttpClientPool.class) {
  10. if (instance == null) {
  11. instance = new HttpClientPool();
  12. }
  13. }
  14. }
  15. return instance;
  16. }
  17.  
  18. private HttpClientPool() {
  19. manager = new PoolingHttpClientConnectionManager();
  20. client = HttpClients.custom().setConnectionManager(manager).build();
  21. monitorThread = new IdleConnectionMonitorThread(manager);
  22. monitorThread.setDaemon(true);
  23. monitorThread.start();
  24. }
  25.  
  26. public CloseableHttpClient getClient() {
  27. return client;
  28. }
  29. }
  30.  
  31.  
  32. class IdleConnectionMonitorThread extends Thread {
  33. private final HttpClientConnectionManager connMgr;
  34. private volatile boolean shutdown;
  35.  
  36. IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
  37. super();
  38. this.connMgr = connMgr;
  39. }
  40.  
  41. @Override
  42. public void run() {
  43. try {
  44. while (!shutdown) {
  45. synchronized(this) {
  46. wait(5000);
  47. // Close expired connections
  48. connMgr.closeExpiredConnections();
  49. // Optionally, close connections
  50. // that have been idle longer than 30 sec
  51. connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
  52. }
  53. }
  54. } catch (InterruptedException ex) {
  55. //
  56. }
  57. }
  58.  
  59. void shutdown() {
  60. shutdown = true;
  61. synchronized(this) {
  62. notifyAll();
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement