简体   繁体   中英

Assign Unique Proxy in a Multithreaded Environment in Java

I know Java supports the use of proxies either by setting system property:

System.setProperty("http.proxyHost", "domain.com");     
System.setPropery("http.proxyPort", "8080");

Or by using the ProxySelector class.

The benefit of using ProxySelector class is that it can be enabled just for a specific URL.

My needs are a bit different.

I want to set a specific proxy when making a connection to an external (SOAP) web service but I want to change the proxy for each thread. In other words, I will be connecting to SOAP web service using multiple threads and I want thread a to use proxy a , thread b to use proxy b and so on (instead of using one proxy throughout the entire JVM)

Is this possible?

Clarification: I would like to have access to two+ different proxies at the same time, not sequentially so any solution which requires me to lock/synchronize access will not work.

You already have the pieces for a solution. Implement your own ProxySelector , and in the select method, choose a different proxy depending on the thread that invoked the select method.

You could have a Map<Thread,Proxy> in your ProxySelector implementation to store and pick the proxy for each thread from (be sure to access/update this map in a thread-safe manner)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM