java method execution time out

Posted on 2012-09-21
Last Modified: 2012-09-25
Calling a method abc  in xyz class. If this method execution is not completed in 1 min then I need to throw exception and do other stuff in that class.
In abc I am calling  athird party API
Please provide a good solution where I can implement it

Many Thanks.
Question by:vjysakshi
    LVL 6

    Accepted Solution

    You can use java.util.concurrent.ExecutorService and java.util.concurrent.Callable interfaces.
    try the below code(timeout in 5 seconds):
    public static void main(String[] args) throws InterruptedException {  
              ExecutorService executor = Executors.newCachedThreadPool();
              Callable<Object> task = new Callable<Object>() {
                 public Object call(){
                    //call method here
              Future<Object> future = executor.submit(task);
              try {
                 Object result = future.get(5, TimeUnit.SECONDS);
              } catch (TimeoutException ex) {
              } catch (InterruptedException e) {
              } catch (ExecutionException e) {
              } finally {
                    System.out.println("In finally Block");
    LVL 6

    Expert Comment

    Is the solution helpful? Waiting for your acknowledgement.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Suggested Solutions

    For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
    Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
    Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
    Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now