简体   繁体   中英

Java shared references between threads

We're looking for a library/functionality in Java (in a spring framework context) for passing references between threads:

//ParentThread:
XXX.putSharedObject("lock", childLock);
XXX.putSharedObject("someKey", someObjectInstance);
for(i=0;i<X;i++) { taskExecutor.execute(context.getBean("childClass")); }
childLock.wait(xxx);

//ChildThread:
YY = XXX.getSharedObject("someKey");
YY.someFunction();
...some work...
XXX.getSharedObject("lock").notify();

Such that any reference set in XXX by a thread (ParentThread) will be accessible only to 'ParentThread' and any child of it, but not other 'ParentThreads' or their children.

Is that possible? (I believe its kind of how Mapped Diagnostic Context work in logging frameworks)

Thanks

Worked it out like this (Compliments of M. le Rutte ):

//ParentRunnable:
public static final InheritableThreadLocal<SomeObjectType> YY = new InheritableThreadLocal<SomeObjectType>();

@Override
public void run() {
  ...
  YY.set(someObjectInstance);
  logger.debug("InParent: {}", YY.get());
  for(i=0;i<X;i++) { taskExecutor.execute(context.getBean("childClass")); }
}


//ChildRunnable:
@Override
public void run() {
  logger.debug("InChild: {}", ParentRunnable.YY.get());
}

The nice part is also that:

@Override
protected SomeObjectType initialValue()

can throw an exception to hint calling "get()" prematurely before a "set()", or use the application context to get a prototype bean which is used as a singleton between the children.

Hope this is helpful to anyone needing it (and hopefully also correctly written)

Java shared references can be achieved with thread safety using a synchronized class or even a block or a method. This way, you can share a given object between threads(Parent,child ...) and guarantee thread safety.

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