-
Jun 13th, 2010, 04:16 AM
#1
scope "prototype" and thread safe.
I need my code to be thread-safe.
Does it make sense that my service class (@Service) has to be a scope prototype? What about manager class inside of service class?
Thanks and regards.
-
Jun 13th, 2010, 05:34 AM
#2
I think it would be more appropriate to synchronize the block of code which you want to be thread safe (and scope as the default scope - singleton). With scope as prototype you will end up creating a new bean instance for every usage.
Again it depends on case to case basis. If you can share more about your case it might help to think and discuss.
-
Jun 13th, 2010, 06:22 AM
#3
Ok, I provide more details about the case.
I am developing an typical service layer with service class and manager class to encapsulate some business code:
[Service Class]
@Service("serviceX")
public class ServiceX implements IServiceX {
@Autowired
IManagerX managerX;
@Autowired
IFactoryX
@Transactional
public void method1(List<Item> list) throws XException {
factoryX.refreshBundle();
...
for(Item item: list){
managerX.method2(factoryX, ...);
}
...
}
[Manager Class]
public class ManagerX implements IManagerX {
@Autowired
private IXDao xDao;
@Autowired
private IYDao yDao;
public void method2(IFactoryX, ...) throws XException {
factoryX.getObject(className);
...
}
}
IFactoryX define an factory to instantiate objects dinamically from property file.
Property file must be refreshed in order to change the class dinamically loaded.
This code is suceptible for sinchronization:
public class FactoryX implements IFactoryX {
private ResourceBundle bundle;
public FactoryMapper() {
super();
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
this.bundle = ResourceBundle.getBundle("/.../property-file",
Locale.getDefault(),currentClassLoader);
}
public IXObject getObject(String keyClass){
try{
Class objClass = Class.forName(bundle.getString(keyClass));
IXObject object = (IXObject) objClass.newInstance();
return object;
}catch(...Exception e){
...
}
public void refreshBundle(){
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
this.bundle = ResourceBundle.getBundle("/.../property-file",
Locale.getDefault(),new ResClassLoader(currentClassLoader)) ;
}
/**
* Needs to create our own class loader in order to clear the cache for
* a ResourceBundle. Without using a new class loader each time the values
* would not be reread from the .properties file
*/
private static class ResClassLoader extends ClassLoader {
ResClassLoader(ClassLoader parent) {
super(parent);
}
}
}
Thanks in advance.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules