Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locks between two methods starving one method

In my program i have two methods:

public void methodA() { //gets called very often
   //write something to file
}

public void methodB() {
  //write something to file
}

methodA gets called by the client very often, whereas methodB gets only called from time to time. However, I need to make sure that whenever a client wants to call methodB it can do so (after possible current execution of methodA has finished). I tried to introduce a synchronized block with an locking object within each method however methodB seems to starve, since methodA gets called more often. How can I solve this issue?

like image 509
Moonlit Avatar asked Jan 08 '15 09:01

Moonlit


People also ask

What is lock starvation?

Lock starvation occurs when a particular thread attempts to acquire a lock and never succeeds because another thread is already holding the lock.

What are the differences between deadlock livelock and starvation?

Livelock is a deadlock-like situation in which processes block each other with a repeated state change yet make no progress. Starvation is the outcome of a deadlock, livelock, or as a result of continuous resource denial to a process.

How do you resolve thread starvation?

Thread Starvation Fix: Move the Lock Each iteration of the loop, a thread will acquire the lock, perform the task, then release the lock.

What is starvation in multithreading?

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads.


1 Answers

Sounds like you are in need of a fair Lock. To make one of these you should pass true as a parameter to the constructor.

Lock lock = new ReentrantLock(true);

public void methodA() {
    lock.lock();
    try {
        // Write something to a file.
    } finally {
        lock.unlock();
    }
}

public void methodB() {
    lock.lock();
    try {
        // Write something to a file.
    } finally {
        lock.unlock();
    }
}
like image 121
OldCurmudgeon Avatar answered Oct 21 '22 00:10

OldCurmudgeon