22
33import java .io .IOException ;
44import java .nio .charset .Charset ;
5+ import java .util .HashMap ;
56import java .util .Map ;
6- import java .util .concurrent .ConcurrentHashMap ;
77import java .util .function .Predicate ;
88
99import org .apache .commons .io .IOUtils ;
2424import us .codecraft .webmagic .utils .CharsetUtils ;
2525import us .codecraft .webmagic .utils .HttpClientUtils ;
2626
27-
2827/**
2928 * The http downloader based on HttpClient.
3029 *
3332 */
3433public class HttpClientDownloader extends AbstractDownloader {
3534
36- private final Map <String , CloseableHttpClient > httpClients = new ConcurrentHashMap < >();
35+ private final Map <String , CloseableHttpClient > httpClients = new HashMap < String , CloseableHttpClient >();
3736 private final Logger logger = LoggerFactory .getLogger (getClass ());
3837 private final HttpClientGenerator httpClientGenerator = new HttpClientGenerator ();
3938
@@ -46,13 +45,6 @@ public class HttpClientDownloader extends AbstractDownloader {
4645
4746 private Predicate <Throwable > refreshProxyOnError = t -> false ;
4847
49-
50- private Predicate <Throwable > refreshClientOnError = t -> false ;
51-
52-
53- public void setRefreshClientOnError (Predicate <Throwable > clientOnError ){
54- this .refreshClientOnError = clientOnError ;
55- }
5648 public void setRefreshProxyOnError (Predicate <Throwable > proxyOnError ) {
5749 this .refreshProxyOnError = refreshProxyOnError ;
5850 }
@@ -70,8 +62,17 @@ private CloseableHttpClient getHttpClient(Site site) {
7062 return httpClientGenerator .getClient (null );
7163 }
7264 String domain = site .getDomain ();
73- return httpClients .computeIfAbsent (domain ,k ->httpClientGenerator .getClient (site ));
74-
65+ CloseableHttpClient httpClient = httpClients .get (domain );
66+ if (httpClient == null ) {
67+ synchronized (this ) {
68+ httpClient = httpClients .get (domain );
69+ if (httpClient == null ) {
70+ httpClient = httpClientGenerator .getClient (site );
71+ httpClients .put (domain , httpClient );
72+ }
73+ }
74+ }
75+ return httpClient ;
7576 }
7677
7778 @ Override
0 commit comments