A: 

It sounds like you want to cache the data representing an object (for example, the results of a database query) rather than an object itself (for example, session data for a user that you may want to retrieve elsewhere).

If this is the case, your custom cacheing layer (around ehcache) needs to create an object from the cache data when a user makes a request - this will give you a unique object every time and you won't get object interference.

Robert Christie
Yes, thats's what Im trying to do
Tommy
A: 

When you retrieve from the cache by id (getOrderItemById) I'd assume that to mean "get the object uniquely identified by id=?". In your second excerpt you have (or are trying to have?) 2 different objects so it looks a bit like you're trying to do 2 contradictory things in the code.

You could enforce uniqueness-Id="ID" is always the same object. If you set the status and then reset it, it means the same object has new status. You'd probably want to extend the .equals method to return true if the id matches as well.

You could also use a "dirty" flag to mark objects that have been changed from the (transactional?) data store.

Making a copy is not a bad way to deal with this either, though it's not clear what it means to have 2 objects running around with the same id. Maybe the copy should be created with a null id to indicate that it doesn't exist in the cache yet?

What's the right behavior for your application?

Steve B.
+3  A: 

This is a problem with mutable state. It isn't only caching, it's any time you could have multiple references to the same object and that object is mutable. For example:

HashMap map = new HashMap();
map.put("one", new OrderItem());
OrderItem one = map.get("one");
OrderItem two = map.get("one");
one.setStatus(1);
two.setStatus(2);

Will have exactly the same problem. This becomes even more complicated when you have a concurrent environment. One way to solve this is to only have immutable objects. That way, if you want an object with different state, you're going to have to make a new one. It also makes concurrent programming easier.

You're right to consider copying the object. Your options are:

Each has their strengths and weaknesses and which one works best will depend on your environment.

jamie mccrindle