Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

92
LINES

< > BotCompany Repo | #1036407 // SynchronizedCircularFifoBuffer

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (10091L/55K).

sclass SynchronizedCircularFifoBuffer<E> is Iterable<E>, IntSize {
  int capacity;
  long base;
  ArrayDeque<E> coreStorage; // Unsynched core list
  Cl<E> storage; // synched coreStorage
  
  *(int capacity) {
    this.capacity = capacity;
    coreStorage = new ArrayDeque<E>(capacity);
    storage = synchronizedCollection(coreStorage);
  }
  
  /**
   * Adds the given element to the buffer. If the buffer is full, the least recently added element is discarded so
   * that a new element can be inserted.
   */
  public void add(E e) {
    synchronized(storage) {
      if (isFull()) remove();
      coreStorage.addLast(e);
    }
  }
  
  /**
   * Removes and returns the least recently inserted element from this buffer.
   */
  public E remove() {
    synchronized(storage) {
      ++base;
      return coreStorage.removeFirst();
    }
  }
  
  /**
   * Returns true iff the buffers remaining capacity is 0.
   */
  public boolean isFull() {
    return storage.size() == capacity;
  }
  
  /**
   * Returns true iff the buffers size is 0.
   */
  public boolean isEmpty() {
    return storage.isEmpty();
  }
  
  /**
   * Returns the number of elements in the buffer.
   */
  public int size() {
    return storage.size();
  }
  
  public Object[] toArray() {
    return storage.toArray();
  }
  
  public<T> T[] toArray(T[] a) {
    return storage.toArray(a);
  }
  
  public List<E> asList() {
    return new ArrayList<E>(storage);
  }
  
  public Cl<E> getBackingStore() {
    ret storage;
  }
  
  public Iterator<E> iterator() {
    return storage.iterator();
  }
  
  public E last() {
    synchronized(storage) {
      ret coreStorage.peekLast();
    }
  }
  
  public void clear {
    synchronized(storage) {
      coreStorage.clear();
      base = 0;
    }
  }
  
  // how many elements were discarded
  synchronized long getBase() { ret base; }
  
  synchronized int getCapacity() { ret capacity; }
}

Author comment

Began life as a copy of #1000774

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1036407
Snippet name: SynchronizedCircularFifoBuffer
Eternal ID of this version: #1036407/11
Text MD5: f45e5ca17e3cce4d20837252608d2023
Transpilation MD5: ddb3c294c5badb6a8ba0da44af35bbac
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-12-11 15:09:44
Source code size: 2006 bytes / 92 lines
Pitched / IR pitched: No / No
Views / Downloads: 77 / 149
Version history: 10 change(s)
Referenced in: [show references]