1

I know that the title seems deprecated, but believe me, it is not. In our JAVA application, we are using an SDK to handle a connection with a device. The problem is, the close function sometimes (probable due to a hardware error) freezes and causes the whole app to freeze and no longer be responsive to the user. Note that I don't have access to this function implementation (as it is inside a DLL), therefore I can't put a flag inside it to check. I have tried to put it inside a thread then tried to kill it but I couldn't, I tried all the approaches mentioned here How to Stop Execution After a Certain Time in Java And this is how I implemented one of these approaches:

Runnable runnable =new Runnable() {
    @Override
    public void run() {

        while (!Thread.currentThread().interrupted())
        {
            System.out.println("this is printed");
            theFunctionFromTheDllFile();
            System.out.println("this is not printed");
        }
    }
};
Thread thread = new Thread(runnable);
thread.start();
thread.join(3*1000);
if (thread.isAlive()) {
    thread.interrupt();
}

So is there any solution that I can use to stop this function regardless of its result after about 5 seconds for example?

Wael Abed
  • 101
  • 2
  • 10
  • You can use a [Timer](https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html) to stop the tread (or thread pool, or kill the app) after a certain time. – c0der Dec 30 '21 at 11:10
  • 1
    If it freezes in native code, there's probably not a lot you can do from the Java code. You *could* make sure that `theFunctionFromTheDllFile` is never called in a path that's blocking the UI in any way to mitigate the effects, but short of killing your whole program or fixing the native code there's not much you can do there. – Joachim Sauer Dec 30 '21 at 11:12
  • @c0der I tried this before and it also didn't work. if we assume that the `theFunctionFromTheDllFile` is this code `while (true){System.out.println("hi");}` the `hi` message will keep printing even after the timer timeout. – Wael Abed Dec 30 '21 at 17:46
  • @JoachimSauer I am also convinced that there isn't much to do, however, I am desperately waiting for somebody to come out with a workaround that didn't cross my mind :), thank you – Wael Abed Dec 30 '21 at 17:53

0 Answers0