Reputation: 53786
The ResourceMapping "filter" is accessed from .jsp page using Ajax request.
My understanding is that Spring will create a new thread of execution each time the resource "filter" is accessed. Since FilterItems is a Spring @Component bean and is therfore a singleton then multiple threads (crated by calls to resource "filter)will access this same instance. A new instance of FilterItems is instantiated with each each call to "filter" resource, as each instance is not shared between threads then this is thread safe ?
Is invocation of FilterItems.filter1 & FilterItems.filter2 threadSafe ?
@Controller
@RequestMapping("VIEW")
public class MyController {
@ResourceMapping(value = "filter")
public void filter(){
FilterItems t = new FilterItems();
LinkedList<MyObj> l = new LinkedList<MyObj>();
l.add(new MyObj("1"));
l.add(new MyObj("2"));
System.out.println("size is : " + l.size());
t.filterItem1(l);
System.out.println("size is : " + l.size());
t.filterItem2(l);
System.out.println("size is : " + l.size());
}
}
*****************************************************************************
import java.util.Iterator;
import java.util.LinkedList;
@Component
public class FilterItems {
public void filterItem1(LinkedList<MyObj> l) {
Iterator<MyObj> iter = l.iterator();
while (iter.hasNext()) {
MyObj myObj = iter.next();
if (myObj.param.equalsIgnoreCase("1")) {
iter.remove();
}
}
}
public void filterItem2(LinkedList<MyObj> l) {
Iterator<MyObj> iter = l.iterator();
while (iter.hasNext()) {
MyObj myObj = iter.next();
if (myObj.param.equalsIgnoreCase("2")) {
iter.remove();
}
}
}
private static class MyObj {
public final String param;
public MyObj(String param) {
this.param = param;
}
}
}
Upvotes: 0
Views: 237
Reputation: 49714
It is almost thread-safe as almost all your data is stored in local variables and passed as parameters.
The only possible exception is the param
field of MyObj
, which should be final
to guarantee that the same value is seen by everyone after object creation.
From the JLS:
An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.
But so long as MyObj
class is kept private
and no-one else can possibly instantiate them, that won't be a problem.
Upvotes: 0
Reputation: 200138
Your controller code has no dependencies on shared mutable data, it only handles data local to a single method invocation. That means that the code is thread-safe.
It isn't clear, though, how MyController
manages to invoke private methods on FilterItems
, or how it instantiates a foreign private static class MyObj
.
Upvotes: 2