logo
Tags down

shadow

Is it possible to timeout java method?


By : Seno Putra Panulisan
Date : October 17 2020, 06:10 PM
it fixes the issue You could use something like the TimeLimiter from the Google Guava library. This allows you to wrap a callable in an operation that you can call with Timeout. If the callable does not complete the operation in time, it will throw a TimeoutException which you can catch and return false after one second.
As an example:
code :
TimeLimiter timeLimiter = new SimpleTimeLimiter();
try {
  String result = timeLimiter.callWithTimeout(
                () -> callToPing(), 1, TimeUnit.SECONDS);
  return true // Or something based on result
} catch (TimeoutException e) {
  return false
}


Share : facebook icon twitter icon

what is the best way to create a timeout to a method in java?


By : user3003589
Date : March 29 2020, 07:55 AM
I wish this help you That heavily depends on what your method is doing. The simplest approach would be to periodically check how long the method has been executing and return when the limit is exceeded.
code :
long t0 = System.currentTimeMillis();
// do something
long t1 = System.currentTimeMillis();
if (t1-t0 > x*1000) {
    return;
}
public <T> T myMethod() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        try {
            T value = executor.invokeAny(Collections.singleton(new Callable<T>() {
                @Override
                public T call() throws Exception {
                    //your actual method code here
                    return null;
                }
            }), 3, TimeUnit.SECONDS);
            System.out.println("All went fine");
            return value;
        } catch (TimeoutException e) {
            System.out.println("Exceeded time limit, interrupted");
        } catch (Exception e) {
            System.out.println("Some error happened, handle it properly");
        }
        return null; /*some default value*/
    } finally {
        executor.shutdownNow();
    }
}

Timeout Method in Java


By : Berta Dénes
Date : March 29 2020, 07:55 AM
hope this fix your issue You can try using Thread.sleep(long millis), which
code :
System.out.println("Program has Ended");
try {
   Thread.sleep(5000); //5000 milliseconds = 5 seconds.
} catch (InterruptedException e) {
   e.printStackTrace();
}
System.exit(0);

Java, Spring : Setting timeout for a method so the code returns to method end.


By : arpmisc
Date : March 29 2020, 07:55 AM
Any of those help One of the ways to implement your requirement is to call your method asynchronously. The method will need to return Future or CompletableFuture (if you are using Java 8).
So you will have a method annotated with @Async (you need to enable async with @EnableAsync in your config):
code :
@Async
   CompletableFuture<Void> createDocxToPdfAndThenToImage(String targetLocation)
CompletableFuture<Void> future= createDocxToPdfAndThenToImage(targetLocation);
   future.get( 10, SECONDS)
        @Async
       CompletableFuture<String> createDocxToPdfAndThenToImage(String targetLocation)  ....

       CompletableFuture<String> future=createDocxToPdfAndThenToImage(targetLocation);
       return future.get( 10, SECONDS);

java.lang.AbstractMethodError: abstract method "okio.Timeout okhttp3.Call.timeout()"


By : Todd S
Date : March 29 2020, 07:55 AM
it should still fix some issue After some research on investigating this issue here is what I found out:
Apparently, this crash is caused due to a timeout error when the React Native package uses okhttp3 by the time a React Native application instance is created.

How to set timeout in a method in Java and retry method for a periodic amount of time


By : user2790723
Date : March 29 2020, 07:55 AM
I wish this help you Your method already has a 5 seconds timeout. All you need to do now is to add some kind a loop with 3 repeats. You need a counter of timeouts and a break after successful attempt. Not sure what you want to do when other exceptions happen, added breaks there as well. Following code should do the job:
code :
private ConnectionInterface  connectWithTimeout() throws MalformedURLException, Exception {
        int repeatCount = 0;

        ExecutorService executor = Executors.newCachedThreadPool();
        Callable<Object> task = new Callable<Object>() {
            public Object call() throws InterruptedException, MalformedURLException, Exception {
                return connectWithNoTimeout();  //This is the method that takes to long. If this method takes more than 5 seconds, I want to cancel and retry for 3 more times. Then abort completely.
            }
        };

        while (repeatCount < 3){
          Future<Object> future = executor.submit(task);
          try {
              Object result = future.get(5, TimeUnit.SECONDS);
              break;

          } catch (TimeoutException ex) {
            repeatCount++;
            System.out.println( "Timeout Occured");

          } catch (InterruptedException e) {
            System.out.println( " "InterruptedException Occured");
            break; 

          } catch (ExecutionException e) {
              System.out.println( "ExecutionException Occured");
            break;    

          } finally {

              future.cancel(true); // here the method gets canceled. How do I retry it?
          }
        }
        System.out.println( "Connected !!");
        return connectWithNoTimeout();
    }
Related Posts Related Posts :
  • How do I add arrays to an Arraylist of Arrays (Arraylist<Integer[]>)
  • Trying to remove a tuple using a prepared statement
  • Best/recommended way to convert Java 8 OffsetDateTime to localized string on android
  • Print a String n times using recursion
  • I have a Jtable with a button in one of the columns and I want to access the value in the 1st column when I press the bu
  • Generating source code with a gradle task based on existing classes with annotations on them
  • a subclass for specifying a generic shows bound mismatch
  • Static Variable with null reference
  • painting string in the middle of a given size cell java
  • Displaying column in tableView
  • What does <+ mean in Java?
  • What cplex function I have to use to write this variable?
  • Java ConcurrentHashSet - iterating over it in a multi-threaded environment
  • Can't seem to get my Java to work in VS Code
  • I don't understand the function of "count++"
  • What are the possibilities to design an API that needs overloads depending on a generic type?
  • Can't connect to Apache Ignite Cluster on AWS EC2 - Ignite server rejects clients
  • Trying to understand garbage collection in java
  • Is there a way to associate an ArrayList with another ArrayList with a one to many relationship?
  • Generate List with Combination of Subset of List, Java
  • Getting Illegal State Exception in Regex
  • Shuffling an Array (Java)
  • Tomcat v 9.0 - Public Key Retrieval is not allowed
  • Clarification on why this code is resulting in false and not true
  • Adding a log function to the java calculator program
  • Any elegant way to parse camel-style string to upper case enum in java?
  • how to download a csv file written in local computer using java
  • JCR SQL2 query: binding of ISDESCENDANTNODE param
  • Difference between db.isopen and db != null
  • How to consume the inconsistent json structure for the same key using jackson (com.fasterxml.jackson)?
  • What is the location of file that is read?
  • Need suggestion on coding practices on the concept "Do Not Repeat Yourself"
  • Simple java ticketing system in netbeans
  • System.lineSeparator() does not work in Linux environment
  • Is it sensible to use the hash code of a class as its serialVersionUID?
  • "Heap size" is growing way faster than "Used heap"
  • Android extract array of properties of array of objects
  • How do i link a JAVA 8 backend to an Angular frontend?
  • How to get/set application name in .dxf for Groupcode 1001?
  • Constantly updating and changing text in a JLabel
  • Export csv file in browser
  • Why does hashCode() function generate an error
  • Android Navigation Component keeps reloading WebView
  • How to format a number based on locale, while retaining all decimal points?
  • Camunda deploy Delegate with global visibility
  • Listing files with specific extension inside a directory: how to handle fake duplicates
  • Different look and feel of java application from the look and feel of Operating System
  • Springboot app is up but POST request always return "not found"
  • new array list created everytime function is called recursively
  • Add a header to an outgoing request by a filter in WebFlux
  • Why "FormDataMultiPart" type parameter is treated differently
  • DateTimeFormatter and SimpleDateFormat produce different strings
  • How to use ExecuteService with custom Threads that contain a AutoCloseable resource
  • If a reference variable is set to null does it still consume memory?
  • Generate title cased fields with JPA/Spring Boot on Postgres
  • RestTemplate mapping Page 'Page size must not be less than one'
  • Using RandomAccessFile along with BufferedReader to speed up file read
  • Why does my code result in a compiler error?
  • Duplicate items added in ConcurrentSkipListSet
  • Kafka's JsonDeserializer not working for java.util.Map
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk