-1

I have a program A which runs with a method execute() and for every iteration it writes on a txt file a String. Sometimes this program blocks and I need to stop it and just recall the method execute() that knows where to restart from. I have a program B which extends Thread, it runs parallel to A, and verifies every X time if the program A is blocked, but I don't know how to block the object A and restart it with its own method. What's the simplest method to do this?

P.s. program A stucks not because I am a bad programmer(I am it for other reasons), but just because it works with online services which does not allow to me to do what I want.

  • 3
    *Sometimes this program blocks and I need to stop it*: well, that shouldn't happen in the first place. Don't try o workaround your bugs. Fix them instead. But we can't help since you haven't post any single line of code. – JB Nizet Oct 22 '17 at 11:38

1 Answers1

0

You can use a Condition and wait for the condition to become satisfied in a specified period in a guard thread. The guard thread will receive an InterruptedException if the condition takes too long.

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    private static class PotentiallyBlockingTask implements Runnable {
        private final Lock lock;
        private final Condition condition;

        public PotentiallyBlockingTask(Lock lock, Condition condition) {
            this.lock = Objects.requireNonNull(lock);
            this.condition = Objects.requireNonNull(condition);
        }

        @Override
        public void run() {         
            // run the task

            // signal the guard thread that it is done.
            lock.lock();            
            try {
                condition.signal();
            }   finally {
                lock.unlock();
            }
        }
    }

private static class GuardTask implements Runnable {
    private final Lock lock;
    private final Condition condition;

    public GuardTask(Lock lock, Condition condition) {
        this.lock = Objects.requireNonNull(lock);
        this.condition = Objects.requireNonNull(condition);
    }

    public void run() {
        lock.lock();
        try {
            condition.await(30, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // handle situation
        } finally {
            lock.unlock();
        }
    }
}

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        PotentiallyBlockingTask pbt = new PotentiallyBlockingTask(lock, condition);
        GuardTask gt = new GuardTask(lock, condition);
    //....
    }
}
M. le Rutte
  • 3,525
  • 3
  • 18
  • 31