Apply timeout control around Java operation

前端 未结 7 978
滥情空心
滥情空心 2021-02-07 06:54

I\'m using a third party Java library to interact with a REST API. The REST API can sometimes take a long time to respond, eventually resulting in a java.net.ConnectExcept

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-07 07:26

    There is no general timeout mechanism valid for arbitrary operations.

    While... there is one... by using Thread.stop(Throwable). It works and it's thread safe, but your personal safety is in danger when the angry mob confronts you.

    // realizable 
    try
    {
        setTimeout(1s);  // 1
        ... any code     // 2 
        cancelTimeout(); // 3
    }
    catch(TimeoutException te)
    {
        // if (3) isn't executed within 1s after (1)
        // we'll get this exception
    } 
    

提交回复
热议问题