java - Do i need to create new Callable object for each thread? -
here 2 options
1) create 1 callable , submit multiple times
callable<string> callable = new mycallable(); for(int i=0; i< 100; i++){ future<string> future = executor.submit(callable); list.add(future); }
2) create multiple callables each thread
for(int i=0; i< 100; i++){ future<string> future = executor.submit(new mycallable()); list.add(future); }
what best practice?
if mycallable
thread-safe class can reuse same instance of it, otherwise, end race conditions , inconsistent results.
in other words, if mycallable
tries hold state not synchronized properly, can't use same instance.
for example, below mycallable
class, can't reuse same instance across multiple threads (i.e., can't share executor.submit(singleinstance)
):
//non-thread safe callable implementation public class mycallable implements callable<string> { private int i; @override public string call() throws exception { i++; //race condition system.out.println(i); return string.valueof(i); } }
whereas if replace int
atomicinteger
, shown below, can reuse same instance:
//thread safe callable implementation public class mythreadsafecallable implements callable<string> { private atomicinteger = new atomicinteger(0); @override public string call() throws exception { int value = i.incrementandget(); system.out.println(value); return string.valueof(value); } }
so, important point note here that, if wanted reuse same instance of callable
, need ensure threadsafe. otherwise, need multiple callable
instances submitted executorservice
.
Comments
Post a Comment