class DelegatingContext implements Context {

    public void close() throws NamingException {
        final Context context = this.getInnermostDelegateContext();
        if (context == null) {
            return;
        }

        //Get a local reference so the member can be nulled earlier
        this.delegateContext = null;

        //Return the object to the Pool and then null the pool reference
        try {
            boolean valid = true;

            if (context instanceof FailureAwareContext) {
                FailureAwareContext failureAwareContext = (FailureAwareContext) context;
                if(failureAwareContext.hasFailed()) {
                    valid = false;
                }
            }

            if (valid) {
                this.keyedObjectPool.returnObject(this.dirContextType, context);
            } else {
                this.keyedObjectPool.invalidateObject(this.dirContextType, context);
            }
        }
        catch (Exception e) {
            final NamingException namingException = new NamingException("Failed to return delegate Context to pool.");
            namingException.setRootCause(e);
            throw namingException;
        }
        finally {
            this.keyedObjectPool = null;
        }
    }

    public  DelegatingContext(KeyedObjectPool<Object,Object> keyedObjectPool, Context delegateContext, DirContextType dirContextType);

}