Question

Just wondering if having a static dozer mapper like this can leads to concurrency errors :

public static Mapper mapper = new DozerBeanMapper();
public static MyDTO toDTO(MyEntity e) {
    MyDTO dto = mapper.map(e, MyDTO.class);
    return dto;
}

Or should I always use this code :

public static MyDTO toDTO(MyEntity e) {
    Mapper mapper = new DozerBeanMapper();
    MyDTO dto = mapper.map(e, MyDTO.class);
    return dto;
}

The method is used in an @Stateless session bean of a JBoss Server, it can be accessed concurrently. The fact is I dont really know if Dozer makes use of static variables or instance variables in the library to decide if I can/should use a static Mapper or create a new instance at every call.

Was it helpful?

Solution

Dozer instance could be static. If you would create new instance for each request the performance will be much worse, since lots of the caches will be initialised every time. ConcurrencyErrors may be encountered either due to bugs in Custom Converters or internal Dozer problems.

OTHER TIPS

From the documentation, DozerMapper instance should be built as singleton. The DozerBeanMapper is thread safe so you can use at any risks with multiple threads.

To be sure you can also use DozerBeanMapperSingletonWrapper.getInstance(); This will handle the singleton part for you.

I don't thinks it is a really good idea to use the mapper as public static field.

You could also use Selma, to handle youre mapping. This is a new library based on an Annotation processor that generates the mapping code at compile time. With it youre code will look like that:

// Configure the mapping
@Mapper
public interface DtoMapper {

    MyDTO toDTO(MyEntity e);
}

// Retrieve the mapper 
public static DtoMapper mapper = Selma.getMapper(DtoMapper.class);

// and some where in the code use
mapper.toDto(entity);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top