reader-writer task-queue in Android

时间:2016-08-30 04:47:37

标签: java android concurrency task-queue

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

1 个答案:

答案 0 :(得分:1)

使用fixed thread pool executor执行任务,让所有任务使用相同的ReadWriteLock,让它自行运行。一般例子:

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();
    }
}

然后,设置你的初始执行者并锁定:

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

当你想要排队任务时:

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

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

确保你始终解锁;如有必要,您可以使用try ... finally阻止,但由于run()不应该抛出任何异常,如果您在run()内正确处理所有问题,则不应该遇到问题你应该这样做。