Home > Blockchain >  Concurrent-safe queue in Java
Concurrent-safe queue in Java

Time:10-13

I'm trying to create thread safe queue with unique elements. I see no vulnerabilities but not sure still is this realisation thread safe or not? get(), add(), toArray() methods do everything under lock, toString() and equals() use toArray() in order to get main array copy and work independently with copy without locks.

public class SafeQueue<T> {
        private final Object[] queue;
        private final HashSet<T> content;
        private final Lock lock;
        private int size;
        
        public SafeQueue() {
            queue = new Object[100];
            content = new HashSet<>(100);
            lock = new ReentrantLock();
        }

        public boolean add(T el) {
            Objects.requireNonNull(el);
            final Lock lock = this.lock;
            lock.lock();
            try {
               //some logic
            } finally {
                lock.unlock();
            }
            return true;
        }

        public T get() {
            final Lock lock = this.lock;
            lock.lock();
            try {
                T el = (T) queue[0];
                if (el != null) {
                    //some shift logic
                    content.remove(el);
                }
                return el;
            } finally {
                lock.unlock();
            }
        }

        public Object[] toArray() {
            final Lock lock = this.lock;
            lock.lock();
            try {
                return Arrays.copyOf(this.queue, size);
            } finally {
                lock.unlock();
            }
        }

        @Override
        public boolean equals(Object o) {
            Object[] eqQueue = ((SafeQueue<?>) o).toArray();
            Object[] curQueue = toArray();

            //some comparison logic with eqQueue and curQueue
            return equal;
        }

        @Override
        public String toString() {
            Object[] curQueue = toArray();
            StringBuilder sb = new StringBuilder();
            sb.append('[');
            //some logic with curQueue
            return sb.toString();
        }
    }

CodePudding user response:

Yes, your implementation is thread safe.

  • Related