java - how future get() method works with timeout -
i bit confused how future.get(timeout) works per definition through exception after specified timeout time, not happening in test cases.
import java.util.linkedhashset; import java.util.set; import java.util.concurrent.callable; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.future; import java.util.concurrent.timeunit; public class callableexample { public static class wordlengthcallable implements callable<string> { private string word; private long waiting; public wordlengthcallable(string word, long waiting) { this.word = word; this.waiting = waiting; } public string call() throws interruptedexception { thread.sleep(waiting); return word; } } public static void main(string args[]) throws exception { args = new string[] { "i", "am", "in", "love" }; long[] waitarr = new long[] { 3000, 3440, 2500, 3000 }; executorservice pool = executors.newfixedthreadpool(3); set<future<string>> set = new linkedhashset<future<string>>(); int = 0; (string word : args) { callable<string> callable = new wordlengthcallable(word, waitarr[i++]); future<string> future = pool.submit(callable); set.add(future); } string sum = ""; (future<string> future : set) { try { sum += future.get(2000, timeunit.milliseconds) + ", "; } catch (exception e) { } } system.out.print("result : " + sum); } }
output "am, in,"
it behaves differently on changing waiting time in array( timearr values). when use timeout?
in for-loop wait first future complete. may take 2000 millis. @ time other threads sleep. hence, values of other threads 2000 millis less. wait 2000 millis , perhaps future wait returns. hence, 2 or more threads succeed.
in each iteration of loop donate 2000 millis other thread. if 1 future returns successfully, donate less remaining futures. if observe futures fail, due 2000 millis timeout, have process them in parallel well.
if change of code way:
set<callable<string>> tasks = new hashset<>(); (string word : args) { tasks.add(new wordlengthcallable(word, waitarr[i++])); } list<future<string>> futures = executors.newfixedthreadpool(3) .invokeall(tasks, 2000, timeunit.milliseconds);
you should observe none of tasks succeed, due wait times of:
3000, 3440, 2500, 3000
for each callable
created, greater 2000.
Comments
Post a Comment