简体   繁体   中英

Java multi-threaded shared objects and bean autowiring

We have a spring based application which has 2 levels of runnables: parents (dispatchers) and children (loaders) where each parent running in a ThreadPoolExecutor has a set of children (again in ThreadPoolExecutors) which require a set of parent specific values (which they obtain currently by calling parent.getSomeProperty())

My question is: how can i autowire beans used by a single parent and its children? Or is there a way to make those children aware of their "session"/"context" sort of saying (which can be a simple ID obtained by hashing "something"?

Sample use case:

  • Each dispatcher has a set of User attributes (like UserID, 3rdParty tokens/passwords, counters, isAborted..etc) which loaders reference
  • Loaders get data from 3rd party different endpoints and generate common Obejects (which have attributes coming from parent and 3rd party) and put them into a single FastMap (Javolution) which is consumed in batches by another bean doing DB INSERT/UPDATE in another thread

I'm currently passing the dispatcher "parent" into all of its children, which makes it mute to use AppContext.getBean(...) and then set common values/pass the parent.

Since I haven't got any answers, I'll post my own implementation which I have so far:

I implemented a SharedStore static object which has mainly two methods:

void putShared(Object o, String objectKey)
<T> T getShared(String objectKey, int parentCode, Class<T> type)

The parent thread calls put, while the children do the gets:

//Parent:
SomeClass someObject;
putShared(someObject, "someObjectKey");

This uses Thread.CurrentThread().hashCode() to put the object into a concurrent hash map

And the child has a key set in constructor:

//Child constructor in BaseRunnable abstract class
private int parentKey = Thread.currentThread().hashCode();

and calls the getMethod with:

//Child
getShared("someKey", parentKey, SomeClass.class);

And uses it as needed (which is done concurrently by multiple children inside the ThreadPoolExecutor in the child

All Runnable beans are autowired prototypes with lazy init and extend base abstract class which implements the default constructor and sets the parentKey, the rest of the stuff like DAOs and 3rdParty api obejects are autowired normally.

Criticism appreciated!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM