com.github.joira.guice.impl.ManagedScope Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of managed Show documentation
Show all versions of managed Show documentation
A @ManageSingleton that works much like @Singleton, but can be reset to force recreation of instances. By implementing the ManagedService interface and registering it using a MultiBinder, the startup process can be manged using different run levels (much like services on the OS).
The newest version!
/**
* Copyright (c) 2011 jolira. All rights reserved. This program and the accompanying materials are made available under
* the terms of the GNU Public License 2.0 which is available at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
package com.github.joira.guice.impl;
import java.util.HashMap;
import java.util.Map;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Scope;
/**
* @author jfk
* @date Aug 19, 2011 9:54:33 PM
* @since 1.0
*
*/
class ManagedScope implements Scope, SingletonManager {
private final Map, Object> scopedByKey = new HashMap, Object>();
@Override
public void reset() {
synchronized (scopedByKey) {
scopedByKey.clear();
}
}
T getScoped(final Key key, final Provider unscoped) {
synchronized (scopedByKey) {
@SuppressWarnings("unchecked")
final T cached = (T) scopedByKey.get(key);
if (cached != null) {
return cached;
}
final T i = unscoped.get();
scopedByKey.put(key, i);
return i;
}
}
@Override
public Provider scope(final Key key, final Provider unscoped) {
return new Provider() {
@Override
public T get() {
return getScoped(key, unscoped);
}
};
}
}