Search code examples
javaandroidconcurrencytask-queue

reader-writer task-queue in Android


I am making an android app with reading tasks and writing tasks . I want to get the following behavior:

  • tasks are executed in a queue
  • reading tasks can be run concurrently.
  • writing tasks are very important and can not run concurrently, if it is running a writing task can not run any other task of any kind

Iam searching a library that solves this problem. I could solve this problem semaphores, but I have fear of making a solution to these problems in android. In my limited experience with android I know it is very difficult to manage the life cycle of these things. And it is very important that writing tasks are executed correctly.

Sorry for my English. Thanks


Solution

  • Use a fixed thread pool executor for your tasks, let all your tasks use the same ReadWriteLock, and let it work itself out. General example:

    public class ReadTask implements Runnable {        
        private final ReadWriteLock lock;
        public ReadTask (ReadWriteLock lock) {
            this.lock = lock;
        }
        @Override public void run () {
            lock.readLock().lock();
            // do stuff
            lock.readLock().unlock();
        }
    }
    
    public class WriteTask implements Runnable {
        private final ReadWriteLock lock;
        public WriteTask (ReadWriteLock lock) {
            this.lock = lock;
        }
        @Override public void run () {
            lock.writeLock().lock();
            // do stuff
            lock.writeLock().unlock();
        }
    }
    

    And then, set up your initial executor and lock:

    ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
    ReadWriteLock lock = new ReentrantReadWriteLock();
    

    And when you want to queue tasks:

    // a write task:    
    executor.execute(new WriteTask(lock));
    
    // a read task:
    executor.execute(new ReadTask(lock));
    

    Just make sure you always unlock the locks; you can use a try ... finally block if necessary but really since run() shouldn't throw any exceptions, you shouldn't be running into issues if you handle everything properly within run() as you should.