aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/jogamp/opengl/util/av/SyncedRingbuffer.java
blob: 5f5d69cf8d5fe5daba5112a2e0a6e9387769845d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
 * Copyright 2013 JogAmp Community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of JogAmp Community.
 */

package jogamp.opengl.util.av;

/** 
 * Simple synchronized ring buffer implementation.
 * <p>
 * Caller can chose whether to block until get / put is able to proceed or not.
 * </p>
 * <p>
 * Caller can chose whether to pass an empty array and clear references at get,
 * or using a preset array for circular access of same objects.
 * </p>
 * <p>
 * Circular write position is equal to the read position if buffer is full or if buffer is empty. 
 * </p>
 */
public class SyncedRingbuffer<T> {

    protected final Object sync = new Object();
    protected final T[] array;
    protected final int capacity;
    protected int readPos;
    protected int writePos;
    protected int size;
    
    public final String toString() {
        return "SyncedRingbuffer<?>[filled "+size+" / "+capacity+", writePos "+writePos+", readPos "+readPos+"]";
    }
    
    /** 
     * Create instance w/ the given array and it's capacity, e.g.:
     * <pre>
     *      SyncedRingbuffer r = new SyncedRingbuffer<Integer>(new Integer[10]);
     * </pre>
     * <p>
     * The array may either be clear, or preset w/ elements!
     * </p>
     * @param full if true, given array is assumed to be full, i.e. {@link #isFull()} will return true.
     * @param array
     */
    public SyncedRingbuffer(T[] array, boolean full) {
        this.array = array;
        this.capacity = array.length;
        clearImpl(false);
        if(full) {
            size = capacity;
        }
    }
    
    public final int capacity() {
        return capacity;
    }
    
    /**
     * Resets all ring buffer pointer to zero.
     * <p>
     * {@link #isEmpty()} will return <code>true</code> after calling this method.
     * </p>
     * <p>
     * If <code>clearRefs</code> is true, all ring buffer slots will be set to <code>null</code>.
     * </p>
     * @param clearRefs if true, all ring buffer slots will be flushed, otherwise they remain intact.
     */
    public final void clear(boolean clearRefs) {
        synchronized ( sync ) {
            clearImpl(clearRefs);
        }
    }
    
    private final void clearImpl(boolean clearRefs) {
        readPos = 0;
        writePos = 0;
        size = 0;
        if( clearRefs ) {
            for(int i=0; i<capacity; i++) {
                this.array[i] = null;
            }
        }
    }
    
    /** Returns the number of elements in this ring buffer. */
    public final int size() {
        synchronized ( sync ) {
            return size;
        }
    }
    
    /** Returns the number of free slots available to put.  */
    public final int getFreeSlots() {
        synchronized ( sync ) {
            return capacity - size;
        }
    }

    /** Returns true if this ring buffer is empty, otherwise false. */
    public final boolean isEmpty() {
        synchronized ( sync ) {
            return 0 == size;
        }
    }
    
    /** Returns true if this ring buffer is full, otherwise false. */
    public final boolean isFull() {
        synchronized ( sync ) {
            return capacity == size;
        }
    }
    
    /**
     * Returns the oldest put element if available, otherwise null.
     * <p>
     * Impl. returns the element at the current read position
     * and advances the read position - if available.
     * </p>
     * <p>
     * If <code>clearRef</code> is true, the returned ring buffer slot will be set to <code>null</code>.
     * </p>
     * <p>
     * Method is non blocking and returns immediately;.
     * </p>
     * @param clearRef if true, the returned ring buffer slot will be flushed, otherwise it remains intact.
     * @return the oldest put element if available, otherwise null.  
     */
    public final T get(boolean clearRef) {
        try {
            return getImpl(clearRef, false, false);
        } catch (InterruptedException ie) { throw new RuntimeException(ie); }
    }

    /**
     * Returns the oldest put element.
     * <p>
     * Impl. returns the element at the current read position
     * and advances the read position.
     * </p>
     * <p>
     * If <code>clearRef</code> is true, the returned ring buffer slot will be set to <code>null</code>.
     * </p>
     * <p>
     * Methods blocks until an element becomes available via put.
     * </p>
     * @param clearRef if true, the returned ring buffer slot will be flushed, otherwise it remains intact.
     * @return the oldest put element  
     * @throws InterruptedException 
     */
    public final T getBlocking(boolean clearRef) throws InterruptedException {
        return getImpl(clearRef, true, false);
    }
    
    public final T peek() throws InterruptedException {
        return getImpl(false, false, true);
    }
    public final T peekBlocking() throws InterruptedException {
        return getImpl(false, true, true);
    }
    
    private final T getImpl(boolean clearRef, boolean blocking, boolean peek) throws InterruptedException {
        synchronized ( sync ) {
            if( 0 == size ) {
                if( blocking ) {
                    while( 0 == size ) {
                        sync.wait();
                    }
                } else {
                    return null;
                }
            }
            final T r = array[readPos];
            if( !peek ) {
                if( clearRef ) {
                    array[readPos] = null;
                }
                readPos = (readPos + 1) % capacity;
                size--;
                sync.notifyAll(); // notify waiting putter
            }
            return r;
        }
    }
    
    /** 
     * Puts the element <code>e</code> at the current write position
     * and advances the write position.
     * <p>
     * Returns true if successful, otherwise false in case buffer is full.
     * </p>
     * <p>
     * Method is non blocking and returns immediately;.
     * </p>
     */
    public final boolean put(T e) {
        try {
            return putImpl(e, false, false);
        } catch (InterruptedException ie) { throw new RuntimeException(ie); }
    }
    
    /** 
     * Puts the element <code>e</code> at the current write position
     * and advances the write position.
     * <p>
     * Method blocks until a free slot becomes available via get.
     * </p>
     * @throws InterruptedException 
     */
    public final void putBlocking(T e) throws InterruptedException {
        if( !putImpl(e, false, true) ) {
            throw new InternalError("Blocking put failed: "+this);
        }
    }
    
    /** 
     * Keeps the element at the current write position intact
     * and advances the write position. 
     * <p>
     * Returns true if successful, otherwise false in case buffer is full.
     * </p>
     * <p>
     * If <code>blocking</code> is true, method blocks until a free slot becomes available via get.
     * </p>
     * @param blocking if true, wait until a free slot becomes available via get.
     * @throws InterruptedException 
     */
    public final boolean putSame(boolean blocking) throws InterruptedException {
        return putImpl(null, true, blocking);
    }
    
    private final boolean putImpl(T e, boolean sameRef, boolean blocking) throws InterruptedException {
        synchronized ( sync ) {
            if( capacity <= size ) {
                if( blocking ) {
                    while( capacity <= size ) {
                        sync.wait();
                    }
                } else { 
                    return false;
                }
            }
            if( !sameRef ) {
                array[ writePos ] = e;
            }
            writePos = (writePos + 1) % capacity;
            size++;
            sync.notifyAll(); // notify waiting getter
            return true;
        }
    }
    
    public final void waitForFreeSlots(int count) throws InterruptedException {
        synchronized ( sync ) {
            if( capacity - size < count ) {
                while( capacity - size < count ) {
                    System.err.println("XXXX AAA XXX");
                    sync.wait();
                }
            }
        }
    }
    
}