satish b
satish b

Reputation: 392

Detect if an object stores state or can be shared

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?

Upvotes: 3

Views: 95

Answers (2)

Stephen C
Stephen C

Reputation: 719229

I am thinking checking if all member fields are final using Reflection will suffice

It won't.

What if the member field is a final reference to an array or collection. How can you tell if the array / collection is part of the object state (by design) or not?

The problem is that the Java language provides no way to say where the conceptual boundaries of the design objects are ... so there's nothing to interogate reflectively.

A better idea might be to rely on the clients of your code to "declare" that classes are stateful or non-stateful using custom annotations.

Upvotes: 2

Michael Brewer-Davis
Michael Brewer-Davis

Reputation: 14276

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 ProcessingStrategy interface or its implementors, perhaps you can use a method, isStateless(), or a subinterface, StatelessProcessingStrategy which are, by convention, shareable across requests.

Upvotes: 2

Related Questions