Skip to content

Instantly share code, notes, and snippets.

@seanf
Created August 27, 2018 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanf/f67cb42c6945c12a195547ee64d5a298 to your computer and use it in GitHub Desktop.
Save seanf/f67cb42c6945c12a195547ee64d5a298 to your computer and use it in GitHub Desktop.
Clean up CDI Instances (Dependent only)
/*
* Copyright 2018, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import javax.enterprise.context.Dependent;
import org.jboss.weld.inject.WeldInstance;
import org.zanata.magpie.service.TranslatorBackend;
/**
* @author Sean Flanigan <a href="mailto:sflaniga@redhat.com">sflaniga@redhat.com</a>
*/
public class Instances {
private Instances() {}
/**
* Destroys any Dependent scoped beans represented by these handlers.
* Note that WeldInstance.handlers().iterator() returns new Handlers each
* time it is called, so you may need to copy the handlers to a collection
* before using them, then pass that same collection to this method for
* cleanup.
* <p>
* Sample usage:
*
* <pre>{@code
* @Inject WeldInstance<MyBean> instances;
* List<WeldInstance.Handler<MyBean>> handlers = new ArrayList<>();
*
* @PostConstruct public void postConstruct() {
* instances.handlers().forEach(handlers::add);
* }
*
* public void someOtherMethod() {
* handlers.forEach(h -> h.get().myBeanMethod());
* }
*
* @PreDestroy public void preDestroy() {
* Instances.destroyDependentBeans(handlers);
* }
* }</pre>
*
* * @param instanceHandlers
*/
public static void destroyDependentBeans(
Iterable<WeldInstance.Handler<TranslatorBackend>> instanceHandlers) {
instanceHandlers.forEach(h -> {
if (h.getBean().getScope().equals(Dependent.class)) {
// Destroy only Dependent beans
h.destroy();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment