如何防止此Java代码挂起

时间:2012-07-20 19:53:58

标签: java proxy

我有一个代理列表来测试它们是HTTP还是Socks代理,但下面的Java代码在调用connection.getContent()或connection.getInputStream()时会挂起。我观察到当代理服务器无法响应并且代码块等待服务器响应时会发生此问题。当服务器无法响应时,如何防止此代码永久挂起/阻塞,以便可以检查下一个代理。

import java.io.*;
import java.net.*;
import java.util.*;

public class ProxyTest {

    public static void main(String[] args) throws IOException {

        InetSocketAddress proxyAddress = new InetSocketAddress("myproxyaddress", 1234);

        Proxy.Type proxyType = detectProxyType(proxyAddress);
    }

    public static Proxy.Type detectProxyType(InetSocketAddress proxyAddress) throws IOException {

    URL url = new URL("http://www.google.com/");

    List<Proxy.Type> proxyTypesToTry = Arrays.asList(Proxy.Type.SOCKS, Proxy.Type.HTTP);

    for(Proxy.Type proxyType : proxyTypesToTry) {

        Proxy proxy = new Proxy(proxyType, proxyAddress);

        URLConnection connection = null;

        try {

            connection = url.openConnection(proxy);

            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            connection.getContent();
            //connection.getInputStream();

            return(proxyType);
        }

        catch (SocketException e) {

    e.printStackTrace();
        }
    }

    return(null);
}
}

2 个答案:

答案 0 :(得分:1)

要并行处理,请使用线程。

for(Foo f : foos){
    Thread t = new Thread(new Runnable(){
        @Override
        public void run(){
            // blocking call
        }        
    });
    t.start();
}

更好的是,使用java.util.concurrent包中的一个数据结构。

答案 1 :(得分:0)

我认为没有简单直接的解决方案。答案取决于JDK版本,实现和运行时环境。有关详细信息,请参阅Java URLConnection Timeout