GenuineSounds

SimpleNonBlockingLockList

Dec 3rd, 2014
324
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.77 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4. import java.util.function.Function;
  5.  
  6. public class SimpleNonBlockingLockList<T> {
  7.  
  8.     private final List<T> elements = new ArrayList<T>();
  9.  
  10.     private final List<T> addQueue = Collections.synchronizedList(new ArrayList<T>());
  11.  
  12.     private final List<T> removeQueue = Collections.synchronizedList(new ArrayList<T>());
  13.  
  14.     public void add(T t) {
  15.         synchronized (addQueue) {
  16.             addQueue.add(t);
  17.         }
  18.     }
  19.  
  20.     public void remove(T t) {
  21.         synchronized (removeQueue) {
  22.             removeQueue.add(t);
  23.         }
  24.     }
  25.  
  26.     public synchronized void updateWith(Function<T, Void> function) {
  27.         elements.addAll(addQueue);
  28.         elements.removeAll(removeQueue);
  29.         for (T element : elements) {
  30.             function.apply(element);
  31.         }
  32.     }
  33. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment