I'm currently developing an app that in some test cases, goes on a infinite loop, but if I redo the same tests, it goes on well. To prevent it, I'm using a secondary thread to monitor the time passed since the start of a task, but I'm currently not using synchronized blocks, because I don't know how to.
Here is an example:
public class ThreadHarvest {
private static final ReentrantLock lock = new ReentrantLock();
private static boolean safe;
public static void main(String[] args) throws InterruptedException
{
Thread task = new Thread(() ->{
lock.lock();
safe = false;
for (long i = 10000000L; i > 0L; --i)
System.out.println(i);
safe = true;
lock.unlock();
System.out.println("Safe ended!");
});
task.start();
while (lock.isLocked() == false);
lock.tryLock(5, TimeUnit.SECONDS);
if (!safe)
{
task.stop();
System.out.println("Force ended!");
}
}
}
Also, there is a specific area that is guaranteed to be safe, which is just after the lock is released. And I know too that the stop method is deprecated, so if you happen to have some good ideas to make it less error prone, I'd be very thankful :D