-1

I want to run a task for 8 hours. I am using ExecutorService executor = Executors.newFixedThreadPool(30). and after submitting the task I am waiting for 8 hours . This is the code I have used.

task1.get(8,TimeUnit.HOURS);

Problem is the code after above statement will be executed after 8 hours . I wanted the task to be executed for 8 hour but the statement after that should be printed immediately. Can somebody suggest some way.

matt freake
  • 4,877
  • 4
  • 27
  • 56
Rashmi
  • 271
  • 1
  • 2
  • 11

4 Answers4

2

It sounds like you are using ExecutorService and Future slightly incorrectly.

When you submit your task, that is when it may (depending on your thread pool) begin executing. If you want to print something after it has started, that is where you should do it.

Future.get is used to wait retrieve the result (up to 8 hours in your case) so is going to block until it is complete.

Something like (not tested):

Callable task = new Callable<String>() {
    // 8 hour task
}

Future<String> future
       = executor.submit(task); // Task may begin here
System.out.println("Task has been submitted, let's wait");
String result;
try {
     result = future.get(8,TimeUnit.HOURS); //
} catch (ExecutionException ex) { 
     // ....
matt freake
  • 4,877
  • 4
  • 27
  • 56
0

You can use CompletableFuture and use thenApply on it. Then the code won't wait on get because get is blocking method which (in your case) waits maximum 8 hours

k0ner
  • 1,086
  • 7
  • 20
0

I think this thread about task completion might help you.

I do agree with @k0ner, use CompletableFuture available on Java8. There is an example at this answer about using CompletableFuture. The get(long timeout, TimeUnit unit) method has a blocking behavior and that's not what you want to.

Community
  • 1
  • 1
Rafael Naufal
  • 411
  • 3
  • 6
0

I am using Java 6. So I cannot use CompletableFuture.

I am solving problem with this logic. I have removed the get functionality. Inside run() method I am getting the startTime of the thread being started using Date Utility. Then I am checking if 8 hour is over (right now I have tested for 1 min). The task is stored in data structure.

After the time is over I am retrieving the task and cancelling it.

António Almeida
  • 9,620
  • 8
  • 59
  • 66
Rashmi
  • 271
  • 1
  • 2
  • 11
  • So just avoid calling `get` in your main thread. You can do this in different thread which waits for the completition. Or you can even print the result in you `task1`. It all depends whether you need (or not) to pass the result somewhere else. – k0ner Dec 03 '15 at 10:27