All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hibernate.jpa.event.internal.jpa.ListenerFactoryStandardImpl Maven / Gradle / Ivy

There is a newer version: 7.0.0.Alpha1
Show newest version
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or .
 */
package org.hibernate.jpa.event.internal.jpa;

import java.util.concurrent.ConcurrentHashMap;
import javax.persistence.PersistenceException;

import org.hibernate.jpa.event.spi.jpa.Listener;
import org.hibernate.jpa.event.spi.jpa.ListenerFactory;

/**
 * Standard implementation of the ListenerFactory contract using simple instantiation.
 *
 * @author Steve Ebersole
 */
public class ListenerFactoryStandardImpl implements ListenerFactory {
	private final ConcurrentHashMap listenerInstances = new ConcurrentHashMap();

	@Override
	@SuppressWarnings("unchecked")
	public  Listener buildListener(Class listenerClass) {
		ListenerImpl listenerImpl = listenerInstances.get( listenerClass );
		if ( listenerImpl == null ) {
			try {
				T listenerInstance = listenerClass.newInstance();
				listenerImpl = new ListenerImpl( listenerInstance );
			}
			catch (Exception e) {
				throw new PersistenceException(
						"Unable to create instance of " + listenerClass.getName() + " as a JPA callback listener",
						e
				);
			}
			ListenerImpl existing = listenerInstances.putIfAbsent(
					listenerClass,
					listenerImpl
			);
			if ( existing != null ) {
				listenerImpl = existing;
			}
		}
		return (Listener) listenerImpl;
	}

	@Override
	public void release() {
		listenerInstances.clear();
	}

	private static class ListenerImpl implements Listener {
		private final T listenerInstance;

		public ListenerImpl(T listenerInstance) {
			this.listenerInstance = listenerInstance;
		}

		@Override
		public T getListener() {
			return listenerInstance;
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy