public void exit(Context context) { //System.out.println("exiting scope of : " + context); final Stack<ScopedObjects> stack = getContextStack(); ScopedObjects currentScopedObject = stack.peek(); if (currentScopedObject.getContextWeakReference().get() == context) { currentScopedObject.setEnterCount(currentScopedObject.getEnterCount() - 1); } if (currentScopedObject.getEnterCount() >= 0 && currentScopedObject.getContextWeakReference().get() == context) { //System.out.println("fast exit"); return; } final Context c = stack.pop().getContextWeakReference().get(); if (c != null && c != context) { throw new IllegalArgumentException(String.format("Scope for %s must be opened before it can be closed", context)); } }
public T get() { final Stack<ScopedObjects> stack = getContextStack(); final ScopedObjects scopedObjects = stack.peek(); // The context should never be finalized as long as the provider is still in memory if (scopedObjects == null) { return null; // May want to consider throwing an exception here (if provider is used after onDestroy()) } @SuppressWarnings({"unchecked"}) T current = (T) scopedObjects.getScopedObjects().get(key); if (current == null && !scopedObjects.getScopedObjects().containsKey(key)) { current = unscoped.get(); scopedObjects.getScopedObjects().put(key, current); } return current; } };
/** * You MUST perform any injector operations inside a synchronized(ContextScope.class) block that starts with * scope.enter(context) if working in a multithreaded environment * * @param context the context to enter * @see ContextScope * @see ContextScopedRoboInjector * @see ContextScopedProvider */ public void enter(Context context, Map<Key<?>, Object> scopedObjects) { //System.out.println("entering scope of : " + context); final Stack<ScopedObjects> stack = getContextStack(); if (!stack.isEmpty()) { ScopedObjects currentScopedObject = stack.peek(); if (currentScopedObject.getContextWeakReference().get() == context) { currentScopedObject.setEnterCount(currentScopedObject.getEnterCount() + 1); //System.out.println("fast enter"); return; } } // Mark this thread as for this context stack.push(new ScopedObjects(new WeakReference<Context>(context), scopedObjects)); }