import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.WeakHashMap;
/**
* An {@link ExtensionFactory} that always returns a specific instance.
private final List<String> extensionClassNames;
- private Map<ClassLoader, Map<String, Object>> cache;
+ private final Map<ClassLoader, Map<String, Object>> cache;
- public SingletonExtensionFactory(String... extensionClassNames) {
+ public SingletonExtensionFactory(PluginManager pluginManager, String... extensionClassNames) {
this.extensionClassNames = Arrays.asList(extensionClassNames);
- cache = new WeakHashMap<>(); // simple cache implementation
+ cache = new HashMap<>();
+
+ pluginManager.addPluginStateListener(event -> {
+ if (event.getPluginState() != PluginState.STARTED) {
+ cache.remove(event.getPlugin().getPluginClassLoader());
+ }
+ });
}
@Override
*/
package org.pf4j;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.pf4j.test.FailTestExtension;
import org.pf4j.test.TestExtension;
*/
public class SingletonExtensionFactoryTest {
+ private PluginManager pluginManager;
+
+ @BeforeEach
+ public void setUp() {
+ pluginManager = new DefaultPluginManager();
+ }
+
+ @AfterEach
+ public void tearDown() {
+ pluginManager = null;
+ }
+
@Test
public void create() {
- ExtensionFactory extensionFactory = new SingletonExtensionFactory();
+ ExtensionFactory extensionFactory = new SingletonExtensionFactory(pluginManager);
Object extensionOne = extensionFactory.create(TestExtension.class);
Object extensionTwo = extensionFactory.create(TestExtension.class);
assertSame(extensionOne, extensionTwo);
@Test
public void createNewEachTime() {
- ExtensionFactory extensionFactory = new SingletonExtensionFactory(FailTestExtension.class.getName());
+ ExtensionFactory extensionFactory = new SingletonExtensionFactory(pluginManager, FailTestExtension.class.getName());
Object extensionOne = extensionFactory.create(TestExtension.class);
Object extensionTwo = extensionFactory.create(TestExtension.class);
assertNotSame(extensionOne, extensionTwo);
@Test
@SuppressWarnings("unchecked")
public void createNewEachTimeFromDifferentClassLoaders() throws Exception {
- ExtensionFactory extensionFactory = new SingletonExtensionFactory();
+ ExtensionFactory extensionFactory = new SingletonExtensionFactory(pluginManager);
// Get classpath locations
URL[] classpathReferences = getClasspathReferences();