001/* 002 * HA-JDBC: High-Availability JDBC 003 * Copyright (C) 2012 Paul Ferraro 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Lesser General Public License as published by 007 * the Free Software Foundation, either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018package net.sf.hajdbc.util.concurrent; 019 020import java.util.concurrent.atomic.AtomicReference; 021 022/** 023 * @author Paul Ferraro 024 */ 025public class ReferenceRegistryStoreFactory implements RegistryStoreFactory<Void> 026{ 027 /** 028 * {@inheritDoc} 029 * @see net.sf.hajdbc.util.concurrent.RegistryStoreFactory#createStore() 030 */ 031 @Override 032 public <V> LifecycleRegistry.Store<Void, V> createStore() 033 { 034 return new ReferenceRegistryStore<V>(); 035 } 036 037 static class ReferenceRegistryStore<V> implements LifecycleRegistry.Store<Void, V> 038 { 039 private final AtomicReference<V> reference = new AtomicReference<V>(); 040 041 /** 042 * {@inheritDoc} 043 * @see net.sf.hajdbc.util.concurrent.RegistryStore#setIfAbsent(java.lang.Object, java.lang.Object) 044 */ 045 @Override 046 public V setIfAbsent(Void key, V value) 047 { 048 return this.reference.compareAndSet(null, value) ? null : this.reference.get(); 049 } 050 051 /** 052 * {@inheritDoc} 053 * @see net.sf.hajdbc.util.concurrent.RegistryStore#get(java.lang.Object) 054 */ 055 @Override 056 public V get(Void key) 057 { 058 return this.reference.get(); 059 } 060 061 /** 062 * {@inheritDoc} 063 * @see net.sf.hajdbc.util.concurrent.RegistryStore#clear(java.lang.Object) 064 */ 065 @Override 066 public V clear(Void key) 067 { 068 return this.reference.getAndSet(null); 069 } 070 } 071}