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?
Lock starvation occurs when a particular thread attempts to acquire a lock and never succeeds because another thread is already holding the lock.
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.
Thread Starvation Fix: Move the Lock Each iteration of the loop, a thread will acquire the lock, perform the task, then release the lock.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With