Stream safe code when using request area

I have a class " RequestContext " that has a request scope. This class has a listOfItem attribute.

I now have a MyMapper class where I need to use this list. Now when I want listOfItems , I always call context.getListOfItem() , but the problem is that I have a lot of private method where I need to repeat this many times. Is this normal when I define this attribute in the constructor? Is it thread safe ?:

 public abstract class MyMapper{ @Autowired protected RequestContext context; private final List<String> listOfItem; public MyMapper() { this.listOfItem = context.getListOfItem(); // is this thread safe and ok ? } public Object map(Object entity){ } } 
+5
source share
1 answer

Yes, it's thread safe as long as it is declared as a bean prototype scope, and you need to create an init() method that Spring calls:

 @PostConstruct public void init() { listOfItem = context.getListOfItem(); } 

RequestContext is accessible only from one thread (one allocated for processing the request), the constructor is not repeated by the nature of the creation of the object immediately before its call.

Be careful not to confuse this with the fact that listOfItem is somehow safe from reconnection problems, but just because it is locked in the MyMapper object MyMapper not stop it from being shared by the getter if it was available (in your case, no ) I also see that this is an abstract class, but since listOfItem is private, subclasses will not have access to it. Any missing link in this list can be controlled by parallel threads if there were any copies made from the link (since List changes in Java).

Since this security is your goal, create a unit test that checks the visibility of the field and fails if accessing the field through reflection does not raise a corresponding exception. You can also comment on the field with your internal marker annotation to indicate that the field is thread safe. This helps with documentation and in the form of annotations of potential future automation (for example, a test base that can search for all such annotations and automatically run a reflection test).

It looks very clean! Keep up the good work.

+1
source

All Articles