Best way to reorganize this in Spring?

private final ExecutorService executorParsers = Executors.newFixedThreadPool(10); public void parse(List<MyObjInt> objs) { //... bunch of elided stuff .... CompletionService<AsupParseObj> parserService = new ExecutorCompletionService<AsupParseObj>(executorParsers); for (final AsupStoreObj obj : objs) { parserService.submit(new ParseThread(obj)); } } 

I would like the DI "ParseThread", but there certainly should be a better way to do this than to bury the getBean call on the scoped bean prototype, and since I'm new to Spring, I decided I would ask ...

+7
source share
2 answers

Here is the complete configuration using the lookup-method (see 3.4.6.1 Entering the search method ):

 <bean id="executorParsers" class="java.util.concurrent.Executors" factory-method="newFixedThreadPool" destroy-method="shutdownNow"> <constructor-arg value="10"/> </bean> <bean id="parserService" class="java.util.concurrent.CompletionService"> <constructor-arg ref="executorParsers"/> </bean> <bean id="foo" class="Foo"> <lookup-method name="createThread" bean="parseThread"/> </bean> <bean id="parseThread" class="ParseThread" scope="prototype" lazy-init="true"/> 

And Java code:

 abstract class Foo { @Autowired CompletionService parserService; protected abstract ParseThread createThread(); public void parse(List<MyObjInt> objs) { for (final AsupStoreObj obj : objs) { ParseThread t = createThread(); t.setObject(obj); parserService.submit(t); } } } 

Unfortunately, you cannot pass any parameters to the lookup-method (see SPR-7431 and my article Creating a prototype of Spring beans on demand using the search method ), therefore, you need to use artificial setObject() .

If you don't like abstract methods / classes, the search method may not be an abstract no-op method or (better) the default implementation may throw an exception. Spring will override the implementation at run time, effectively calling getBean() for you.

Bonus: I translated Executor / CompletionService into Spring managed beans. Note that Spring supports these ready-made files: Run and schedule tasks .

+7
source

Well, I'm not sure what you think Spring is going to buy you here, but I would introduce a factory that spits out Runnable / Callable .

 private final ExecutorService executorParsers = Executors.newFixedThreadPool(10); @Autowired private CallableFactory myCallableFactory = new MyCallableFactory(); //create this factory public void parse(List<MyObjInt> objs) { //... bunch of elided stuff .... CompletionService<AsupParseObj> parserService = new ExecutorCompletionService<AsupParseObj>(executorParsers); for (final AsupStoreObj obj : objs) { parserService.submit(myCallableFactory.createCallable(obj)); } } 

You can also introduce ExecutorService using Spring.

0
source

All Articles