Basic Code
The constructor of the ReentrantLock and ReentrantReadWriteLock classes admits a boolean parameter named fair that allows you to control the behavior of both classes.
The false value is the default value and it's called the non-fair mode. In this mode, when there are some threads waiting for a lock (ReentrantLock or ReentrantReadWriteLock) and the lock has to select one of them to get the access to the critical section, it selects one without any criteria.
The true value is called the fair mode. In this mode, when there are some threads waiting for a lock (ReentrantLock or ReentrantReadWriteLock) and the lock has to select one to get access to a critical section, it selects the thread that has been waiting for the most time.
public class AccountInfo { private double account1; private double account2; private ReadWriteLock lock; public AccountInfo(){ account1=1.0; account2=2.0; lock=new ReentrantReadWriteLock(); } public double getaccount1() { lock.readLock().lock(); double value=account1; lock.readLock().unlock(); return value; } public double getaccount2() { lock.readLock().lock(); double value=account2; lock.readLock().unlock(); return value; } public void setPrices(double account1, double account2) { lock.writeLock().lock(); this.account1=account1; this.account2=account2; lock.writeLock().unlock(); } }
The constructor of the ReentrantLock and ReentrantReadWriteLock classes admits a boolean parameter named fair that allows you to control the behavior of both classes.
The false value is the default value and it's called the non-fair mode. In this mode, when there are some threads waiting for a lock (ReentrantLock or ReentrantReadWriteLock) and the lock has to select one of them to get the access to the critical section, it selects one without any criteria.
The true value is called the fair mode. In this mode, when there are some threads waiting for a lock (ReentrantLock or ReentrantReadWriteLock) and the lock has to select one to get access to a critical section, it selects the thread that has been waiting for the most time.
No comments:
Post a Comment