001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2017-2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero 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, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.io.util;
020
021import java.lang.ref.WeakReference;
022import java.util.ArrayList;
023import java.util.Iterator;
024import java.util.LinkedList;
025import java.util.List;
026import java.util.concurrent.Semaphore;
027
028/**
029 * A class that manages a set of permits and notifies listeners
030 * about changes of availability.
031 * 
032 * Listeners are added using {@link WeakReference}, so removing
033 * them isn't strictly necessary.
034 */
035@SuppressWarnings("PMD.AvoidSynchronizedStatement")
036public class PermitsPool {
037
038    private final MySemaphore delegee;
039    private final List<WeakReference<AvailabilityListener>> listeners
040        = new LinkedList<>();
041    private boolean lastNotification = true;
042
043    /**
044     * A variant of {@link Semaphore}.
045     */
046    @SuppressWarnings("PMD.PublicMemberInNonPublicType")
047    private static class MySemaphore extends Semaphore {
048        private static final long serialVersionUID = 8758302721594300704L;
049
050        /**
051         * Instantiates a new semaphore.
052         *
053         * @param permits the number of permits
054         */
055        public MySemaphore(int permits) {
056            super(permits);
057        }
058
059        @Override
060        public void reducePermits(int reduction) {
061            super.reducePermits(reduction);
062        }
063    }
064
065    /**
066     * Instantiates a new permits pool.
067     *
068     * @param permits the permits
069     */
070    public PermitsPool(int permits) {
071        delegee = new MySemaphore(permits);
072    }
073
074    /**
075     * Returns the number of currently available permits.
076     *
077     * @return the result
078     */
079    public int availablePermits() {
080        return delegee.availablePermits();
081    }
082
083    /**
084     * Adds the given number of permits to the pool.
085     *
086     * @param permits the number of permits to add
087     * @return the permits pool
088     */
089    public PermitsPool augmentPermits(int permits) {
090        delegee.release(permits);
091        return this;
092    }
093
094    /**
095     * Remove the given number of permits from the pool.
096     *
097     * @param permits the number of permits to remove
098     * @return the permits pool
099     */
100    public PermitsPool reducePermits(int permits) {
101        delegee.reducePermits(permits);
102        return this;
103    }
104
105    /**
106     * Adds an AvailabilityListener.
107     *
108     * @param listener the AvailabilityListener
109     * @return the permits pool
110     */
111    public PermitsPool addListener(AvailabilityListener listener) {
112        synchronized (listeners) {
113            listeners.add(new WeakReference<>(listener));
114        }
115        return this;
116    }
117
118    /**
119     * Removes the listener.
120     *
121     * @param listener the AvailabilityListener
122     * @return the permits pool
123     */
124    @SuppressWarnings("PMD.CompareObjectsWithEquals")
125    public PermitsPool removeListener(AvailabilityListener listener) {
126        synchronized (listeners) {
127            for (Iterator<WeakReference<AvailabilityListener>> iter
128                = listeners.iterator(); iter.hasNext();) {
129                WeakReference<AvailabilityListener> item = iter.next();
130                if (item.get() == null || item.get() == listener) {
131                    iter.remove();
132                }
133            }
134        }
135        return this;
136    }
137
138    private void notifyAvailabilityListeners() {
139        boolean available = availablePermits() > 0;
140        if (available == lastNotification) {
141            return;
142        }
143        lastNotification = available;
144        List<AvailabilityListener> copy = new ArrayList<>();
145        synchronized (listeners) {
146            for (Iterator<WeakReference<AvailabilityListener>> iter
147                = listeners.iterator(); iter.hasNext();) {
148                WeakReference<AvailabilityListener> item = iter.next();
149                AvailabilityListener listener = item.get();
150                if (listener == null) {
151                    iter.remove();
152                    continue;
153                }
154                copy.add(listener);
155            }
156        }
157        for (AvailabilityListener l : copy) {
158            l.availabilityChanged(this, available);
159        }
160    }
161
162    /**
163     * Release a previously obtained permit.
164     */
165    public PermitsPool release() {
166        synchronized (this) {
167            delegee.release();
168            notifyAvailabilityListeners();
169            return this;
170        }
171    }
172
173    /**
174     * Acquire a permit, waiting until one becomes available.
175     *
176     * @return the permits pool
177     * @throws InterruptedException the interrupted exception
178     */
179    public PermitsPool acquire() throws InterruptedException {
180        delegee.acquire();
181        notifyAvailabilityListeners();
182        return this;
183    }
184
185    /**
186     * Try to acquire a permit.
187     *
188     * @return `true` if successful
189     */
190    public boolean tryAcquire() {
191        synchronized (this) {
192            boolean gotOne = delegee.tryAcquire();
193            if (gotOne) {
194                notifyAvailabilityListeners();
195                return true;
196            }
197            return false;
198        }
199    }
200
201}