Sometimes it is useful to execute some code with a time limit for completion.

public static boolean runTimeLimitedThread(Thread thread, long msecsTimeLimit)
{
    long endTimeMsecs = System.currentTimeMillis() + msecsTimeLimit;

    if (msecsTimeLimit == 0L || thread == null) return false;  // nothing to do
     
    thread.start();
     
    boolean currentThreadNeedsInterrupt = false;
    while (System.currentTimeMillis() < endTimeMsecs)
    {
        if (thread.isAlive())
        {
            try
            {
                Thread.sleep(250);
            }
            catch (InterruptedException e)
            {
                currentThreadNeedsInterrupt = true;
                break;
            }
        }
        else
        {
            break;
        }
    }
    boolean interrupted = false;
    if (thread.isAlive())
    {
        thread.interrupt();
        interrupted = true;
    }
    if (currentThreadNeedsInterrupt)
    {
        Thread.currentThread().interrupt();
    }
    return interrupted;
}
blog comments powered by Disqus