I just can't kill a java thread

I have a stream that downloads some images from the Internet using different proxies. Sometimes it freezes and cannot be killed by any means.

public HttpURLConnection uc; public InputStream in; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("server", 8080)); URL url = new URL("http://images.com/image.jpg"); uc = (HttpURLConnection)url.openConnection(proxy); uc.setConnectTimeout(30000); uc.setAllowUserInteraction(false); uc.setDoOutput(true); uc.addRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); uc.connect(); in = uc.getInputStream(); 

When it freezes, it freezes with the uc.getInputStream() method. I made a timer that tries to kill a thread if its start time exceeds 3 minutes. I tried the .terminate() stream. There is no effect. I tried uc.disconnect() from the main thread. The method also hangs with it, the main thread. I tried in.close() . There is no effect. I tried uc=null , in=null in the hope of an exception that will end the stream. He continues to work. It never misses the uc.getInputStream() method.

In my last test, the flow lasted more than 14 hours after receiving all of the above commands (or various combinations). I had to kill the Java process to stop the thread.

If I simply ignore the stream and set it to null, the stream does not die and is not cleared by the garbage collector. I know, because if I let the application run for several days, the Java process takes up more system memory. After 3 days, it took 10% of my RAM to 8 GB.

Impossible to kill a thread?

+4
source share
4 answers

Try setting uc.setReadTimeout(30000);

+3
source

Impossible to kill a thread?

In many cases, yes - especially when the thread is blocking on an intermittent IO. You may be able to unlock it by calling uc.getInputStream().close() from another thread. Although this may not be thread safe. HttpUrlConnection also has setReadTimeout (), which you should probably set in your case.

+4
source

Along with setting a read timeout (mentioned in other answers), did you try to interrupt the stream?

+4
source

No, you can’t. Killing a thread outside is inherently an unsafe operation.

What you can do is make Thread voluntarily close. Record the download stream so that it ends when the timeout is exceeded.

0
source

Source: https://habr.com/ru/post/1306912/


All Articles