Is private method in spring service implement class thread safe

Posted by Roger Ray on Stack Overflow See other posts from Stack Overflow or by Roger Ray
Published on 2014-08-22T04:12:23Z Indexed on 2014/08/22 4:20 UTC
Read the original article Hit count: 212

Filed under:
|

I got a service in an project using Spring framework.

public class MyServiceImpl implements IMyService {
    public MyObject foo(SomeObject obj) {
       MyObject myobj = this.mapToMyObject(obj);
       myobj.setLastUpdatedDate(new Date());
       return myobj;
    }

    private MyObject mapToMyObject(SomeObject obj){
       MyObject myojb = new MyObject();
       ConvertUtils.register(new MyNullConvertor(), String.class);
       ConvertUtils.register(new StringConvertorForDateType(), Date.class);
       BeanUtils.copyProperties(myojb , obj);
       ConvertUtils.deregister(Date.class);
       return myojb;
    }
}

Then I got a class to call foo() in multi-thread;

There goes the problem. In some of the threads, I got error when calling

BeanUtils.copyProperties(myojb , obj);

saying Cannot invoke com.my.MyObject.setStartDate - java.lang.ClassCastException@2da93171

obviously, this is caused by ConvertUtils.deregister(Date.class) which is supposed to be called after BeanUtils.copyProperties(myojb , obj);.

It looks like one of the threads deregistered the Date class out while another thread was just about to call BeanUtils.copyProperties(myojb , obj);.

So My question is how do I make the private method mapToMyObject() thread safe?

Or simply make the BeanUtils thread safe when it's used in a private method.

And will the problem still be there if I keep the code this way but instead I call this foo() method in sevlet? If many sevlets call at the same time, would this be a multi-thread case as well?

© Stack Overflow or respective owner

Related posts about multithreading

Related posts about spring