I’m implementing an object cache:
void cache(String request_type, String request_id, ProcessingStrategy request_strategy)
{
if (no_state(request_strategy) == true)
map.put(request_type, request_strategy);
else
map.put(request_id, request_strategy); //no chance of keyspace collision
}
ProcessingStrategy lookup(String request_type, String request_id)
{
ProcessingStrategy request_strategy = map.get(request_type);
if (request_strategy == null) return map.get(request_id)
else return request_strategy;
}
This scheme of sharing objects implementing interface ProcessingStrategy across all requests of a particular type will only work if there is no state being stored in the concrete class.
How do I write the no_state method?
I am thinking checking if all member fields are final using Reflection will suffice:
for(Field f : request_strategy.getClass().getDeclaredFields())
if(!Modifier.isFinal(f.getModifiers()))
return false;
//even if all fields are final;
//how to check that they are not being initialized with differently in the ProcessingStrategy constructor?
What you’re attempting to do (detect mutability of an arbitrary object), I don’t think can be done. Even if it could, through some reflective acrobatics, it still seems a bad idea.
If you control the
ProcessingStrategyinterface or its implementors, perhaps you can use a method,isStateless(), or a subinterface,StatelessProcessingStrategywhich are, by convention, shareable across requests.