Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe code when using request scope

Tags:

java

spring

I have class "RequestContext" which has scope request. This class has atribute listOfItem.

now I have class MyMapper where I need to use this list. Now when I want to listOfItems I always call context.getListOfItem() but problem is that I have a lot of private method where I need to repeat this a lot of times. It is ok when I define this atribute in constructor ? It is 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){

}

}
like image 834
hudi Avatar asked Nov 10 '22 15:11

hudi


1 Answers

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

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

The RequestContext is only accessible from single thread (the one allocated to handle the request), the constructor is not re-entrant by nature of the creation of the object just before it's call.

Be careful not to confuse this with the listOfItem somehow being safe from reentrancy problems though, just because it is locked down in the MyMapper object does not stop it from being shared by a getter, if one were available (there isn't in your case). I also see that it's an abstract class, but because the listOfItem is private, subclasses will not have access to it. Any leaked reference of that List could be manipulated by concurrent threads were there to be any copies made of the reference (since Lists are mutable in Java).

As this safety is your intent, create a unit test that checks the visibility of the field and fails if accessing the field via reflection does not throw the appropriate exception. You may also want to comment the field with your own internal marker annotation to indicate the field is thread safe. This helps with documentation, and as an annotation, potential future automation (such as a test base that could look for all such annotations and automatically run the reflection test).

It looks very clean! Keep up the good work.

like image 113
Brian Topping Avatar answered Nov 14 '22 23:11

Brian Topping