I am wondering what are the alternative ways to avoid deadlock in the following example. The following example is a typical bank account transferring deadlock problem. What are some of the better approaches to solve it in practice ?
class Account {
double balance;
int id;
public Account(int id, double balance){
this.balance = balance;
this.id = id;
}
void withdraw(double amount){
balance -= amount;
}
void deposit(double amount){
balance += amount;
}
}
class Main{
public static void main(String [] args){
final Account a = new Account(1,1000);
final Account b = new Account(2,300);
Thread a = new Thread(){
public void run(){
transfer(a,b,200);
}
};
Thread b = new Thread(){
public void run(){
transfer(b,a,300);
}
};
a.start();
b.start();
}
public static void transfer(Account from, Account to, double amount){
synchronized(from){
synchronized(to){
from.withdraw(amount);
to.deposit(amount);
}
}
}
}
I am wondering if the deadlock issue will be solved if I separate the nested lock out in my transfer method like the following
synchronized(from){
from.withdraw(amount);
}
synchronized(to){
to.deposit(amount);
}
Sort the accounts. The dead lock is from the ordering of the accounts (a,b vs b,a).
So try:
public static void transfer(Account from, Account to, double amount){
Account first = from;
Account second = to;
if (first.compareTo(second) < 0) {
// Swap them
first = to;
second = from;
}
synchronized(first){
synchronized(second){
from.withdraw(amount);
to.deposit(amount);
}
}
}
In addition to the solution of lock ordered you can also avoid the deadlock by synchronizing on a private static final lock object before performing any account transfers.
class Account{
double balance;
int id;
private static final Object lock = new Object();
....
public static void transfer(Account from, Account to, double amount){
synchronized(lock)
{
from.withdraw(amount);
to.deposit(amount);
}
}
This solution has the problem that a private static lock restricts the system to performing transfers "sequentially".
Another one can be if each Account has a ReentrantLock:
private final Lock lock = new ReentrantLock();
public static void transfer(Account from, Account to, double amount)
{
while(true)
{
if(from.lock.tryLock()){
try {
if (to.lock.tryLock()){
try{
from.withdraw(amount);
to.deposit(amount);
break;
}
finally {
to.lock.unlock();
}
}
}
finally {
from.lock.unlock();
}
int n = number.nextInt(1000);
int TIME = 1000 + n; // 1 second + random delay to prevent livelock
Thread.sleep(TIME);
}
}
Deadlock does not occur in this approach because those locks will never be held indefinitely. If the current object's lock is acquired but the second lock is unavailable, the first lock is released and the thread sleeps for some specified amount of time before attempting to reacquire the lock.
This is a classic question. I see two possible solutions:
To sort accounts and synchronize at account which has an id lower than another one.
This method mentioned in the bible of concurrency Java Concurrency in Practice in chapter 10. In this book authors use system hash code to distinguish the accounts. See java.lang.System#identityHashCode.
The second solution is mentioned by you - yes you can avoid nested synchronized blocks and your code will not lead to deadlock. But in that case the processing might have some problems because if you withdraw money from the first account the second account may be locked for any significant time and probably you will need to put money back to the first account. That's not good and because that nested synchronization and the lock of two accounts is better and more commonly used solution.
You can also create separate lock for each Account (in Account class) and then before doing transaction acquire both locks. Take a look:
private boolean acquireLocks(Account anotherAccount) {
boolean fromAccountLock = false;
boolean toAccountLock = false;
try {
fromAccountLock = getLock().tryLock();
toAccountLock = anotherAccount.getLock().tryLock();
} finally {
if (!(fromAccountLock && toAccountLock)) {
if (fromAccountLock) {
getLock().unlock();
}
if (toAccountLock) {
anotherAccount.getLock().unlock();
}
}
}
return fromAccountLock && toAccountLock;
}
After get two locks you can do transfer without worrying about safe.
public static void transfer(Acc from, Acc to, double amount) {
if (from.acquireLocks(to)) {
try {
from.withdraw(amount);
to.deposit(amount);
} finally {
from.getLock().unlock();
to.getLock().unlock();
}
} else {
System.out.println(threadName + " cant get Lock, try again!");
// sleep here for random amount of time and try do it again
transfer(from, to, amount);
}
}
Here is the solution for the problem stated.
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class FixDeadLock1 {
private class Account {
private final Lock lock = new ReentrantLock();
#SuppressWarnings("unused")
double balance;
#SuppressWarnings("unused")
int id;
public Account(int id, double balance) {
this.balance = balance;
this.id = id;
}
void withdraw(double amount) {
this.balance -= amount;
}
void deposit(double amount) {
balance += amount;
}
}
private class Transfer {
void transfer(Account fromAccount, Account toAccount, double amount) {
/*
* synchronized (fromAccount) { synchronized (toAccount) {
* fromAccount.withdraw(amount); toAccount.deposit(amount); } }
*/
if (impendingTransaction(fromAccount, toAccount)) {
try {
System.out.format("Transaction Begins from:%d to:%d\n",
fromAccount.id, toAccount.id);
fromAccount.withdraw(amount);
toAccount.deposit(amount);
} finally {
fromAccount.lock.unlock();
toAccount.lock.unlock();
}
} else {
System.out.println("Unable to begin transaction");
}
}
boolean impendingTransaction(Account fromAccount, Account toAccount) {
Boolean fromAccountLock = false;
Boolean toAccountLock = false;
try {
fromAccountLock = fromAccount.lock.tryLock();
toAccountLock = toAccount.lock.tryLock();
} finally {
if (!(fromAccountLock && toAccountLock)) {
if (fromAccountLock) {
fromAccount.lock.unlock();
}
if (toAccountLock) {
toAccount.lock.unlock();
}
}
}
return fromAccountLock && toAccountLock;
}
}
private class WrapperTransfer implements Runnable {
private Account fromAccount;
private Account toAccount;
private double amount;
public WrapperTransfer(Account fromAccount,Account toAccount,double amount){
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.amount = amount;
}
public void run(){
Random random = new Random();
try {
int n = random.nextInt(1000);
int TIME = 1000 + n; // 1 second + random delay to prevent livelock
Thread.sleep(TIME);
} catch (InterruptedException e) {}
new Transfer().transfer(fromAccount, toAccount, amount);
}
}
public void initiateDeadLockTransfer() {
Account from = new Account(1, 1000);
Account to = new Account(2, 300);
new Thread(new WrapperTransfer(from,to,200)).start();
new Thread(new WrapperTransfer(to,from,300)).start();
}
public static void main(String[] args) {
new FixDeadLock1().initiateDeadLockTransfer();
}
}
There are three requirements you must satisfy:
Consistently reduce the contents of one account by the specified amount.
Consistently increase the contents of the other account by the specified amount.
If one of the above is successful, the other must also be successful.
You can achieve 1. and 2. by using Atomics, but you will have to use something other that double as there is no AtomicDouble. AtomicLong would probably be your best bet.
So you're left with your third requirement - if one succeeds the other must succeed. There is a simple technique that works superbly with atomics and that is using the getAndAdd methods.
class Account {
AtomicLong balance = new AtomicLong ();
}
...
Long oldDebtor = null;
Long oldCreditor = null;
try {
// Increase one.
oldDebtor = debtor.balance.getAndAdd(value);
// Decrease the other.
oldCreditor = creditor.balance.gtAndAdd(-value);
} catch (Exception e) {
// Most likely (but still incredibly unlikely) InterruptedException but theoretically anything.
// Roll back
if ( oldDebtor != null ) {
debtor.getAndAdd(-value);
}
if ( oldCreditor != null ) {
creditor.getAndAdd(value);
}
// Re-throw after cleanup.
throw (e);
}
Related
I am sorry for this basic question but I am so curious why I am not getting the correct result for the below code. I have a basic Account class which has 3 non-synchronized and 3 synchronized methods that do the same jobs. My expectation is to calculate the correct result when I use the synchronized keyword but when i run the application unfortunately I am getting a wrong error. What I am missing here? Thanks in advance guys!
Here's the Account class
public class Account {
private double balance;
public Account(int balance) {
this.balance = balance;
}
public boolean rawWithDraw(int amount) {
if (balance >= balance) {
balance = balance - amount;
return true;
}
return false;
}
public void rawDeposit(int amount) {
balance = balance + amount;
}
public double getRawBalance() {
return balance;
}
public boolean safeWithDraw(final int amount) {
synchronized (this){
if (balance >= amount) {
balance = balance - amount;
return true;
}
}
return false;
}
public void safeDeposit(final int amount) {
synchronized (this) {
balance = balance + amount;
}
}
public double getSafeBalance() {
synchronized (this) {
return balance;
}
}
}
and here's the main application
public class Main {
public static void main(String[] args) {
Account account1 = new Account(0);
Thread tA = new Thread(() -> account1.safeDeposit(70));
Thread tB = new Thread(() -> account1.safeDeposit(50));
tA.setName("thread-A");
tB.setName("thread-B");
tA.start();
tB.start();
System.out.println("The balance is : " + account1.getRawBalance());
}
}
And when I run the code, sometimes it prints 70, sometimes 0 and sometimes 120. What causing this?
You have not included getRawBalance() as a synchronized method, so it is allowed to run concurrently with either of the two synchronized methods. You can therefore see the result before either method executes, after both methods execute, or in between one and the other, giving four different possible outcomes.
Im having problems with my Printer-Counter School Problem. Its supposed to be a multithreading application and runs fine so far. But when I running it the second or third time it wont work anymore.. No error message. Looks like Threads sleep forver or so. Also when I test it with a JUnit test it wont work. But sometimes it does... wich is already strange itself.
public class CounterPrinter {
public static void main(String[] args) throws InterruptedException {
if (args.length != 2) {
System.out.println("Usage: CounterPrinter <min> <max>");
System.exit(1);
}
Storage s = new Storage();
Printer d = new Printer(s, Integer.parseInt(args[1]));
Counter z = new Counter(s, Integer.parseInt(args[0]), Integer.parseInt(args[1]));
z.start();
d.start();
z.join();
d.join();
Thread.sleep(5000);
}
}
public class Printerextends Thread {
private Storage storage;
private Integer ende;
Printer(Storage s, Integer ende) {
this.storage = s;
this.ende = ende;
}
#Override
public void run() {
while (storage.hasValue()) {
try {
System.out.print(speicher.getValue(ende) + " ");
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Counter extends Thread {
private Storage speicher;
private int max, min;
Counter(Storages, int min, int max) {
this.storage = s;
this.max = max;
this.min = min;
}
#Override
public void run() {
for (int i = min; i <= max; i++) {
try {
storage.setValue(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Storage implements StorageIf {
private Integer wert;
private boolean hasValue = false;
#Override
public synchronized Integer getValue(Integer ende) throws InterruptedException {
if(wert.equals(ende)){
hasValue = false;
return wert;
}else {
while (!hasValue()) {
wait();
}
hasValue = false;
notifyAll();
return wert;
}
}
#Override
public synchronized void setValue(Integer wert) throws InterruptedException {
while (hasValue()){
wait();
}
hasValue = true;
this.wert = wert;
notifyAll();
}
#Override
public boolean hasValue() {
return hasValue;
}
}
Hope someone can spot a mistake I made :(
Thanks a lot!!!
The problem is that you conflate 2 states :
there is currently a value available
there will be no more values
Add an hasEnded() method to your Storage class, checking if the end value has been reached. Make sure to synchronize this method, as well as the hasValue() method. Synchronization needs to be done on both read and write access!
Then make Printer's while loop check hasEnded, rather than hasValue.
Finally : get rid of all the sleep() calls.
Your own answer, solving the problem with sleep, is not a real solution. A thread safe program does not depend on a computer's performance to function correctly.
z.start();
z.sleep(100);
d.start();
Putting a delay between starting the tow Threads solved the problem for me. My Computer was probably too fast down the road in Thread z before it even started Thread d. Thats why it hung itself up in 50% of the time.
Thanks to everyone tho :)
I was looking for deadlock example and stumbled across this code:
package com.example.thread.deadlock._synchronized;
public class BankAccount {
double balance;
int id;
BankAccount(int id, double balance) {
this.id = id;
this.balance = balance;
}
void withdraw(double amount) {
// Wait to simulate io like database access ...
try {Thread.sleep(10l);} catch (InterruptedException e) {}
balance -= amount;
}
void deposit(double amount) {
// Wait to simulate io like database access ...
try {Thread.sleep(10l);} catch (InterruptedException e) {}
balance += amount;
}
static void transfer(BankAccount from, BankAccount to, double amount) {
synchronized(from) {
from.withdraw(amount);
synchronized(to) {
to.deposit(amount);
}
}
}
public static void main(String[] args) {
final BankAccount fooAccount = new BankAccount(1, 100d);
final BankAccount barAccount = new BankAccount(2, 100d);
new Thread() {
public void run() {
BankAccount.transfer(fooAccount, barAccount, 10d);
}
}.start();
new Thread() {
public void run() {
BankAccount.transfer(barAccount, fooAccount, 10d);
}
}.start();
}
}
How would you change transfer method so that it doesn't cause deadlock? First thought is to create a shared lock for all accounts, but that of course would just kill all concurrency. So is there a good way to lock just two accounts involved into a transaction and not affect other accounts?
One way to avoid deadlocks in multi-lock situations is to always lock the objects in the same order.
In this case it would mean that you'd create a total ordering for all BankAccount objects. Luckily we've got an id that we can use, so you could always lock the lower id first and then (inside the other synchronized block) the higher id one.
This assumes that there's no BankAccount objects with identical ids, but that seems like a reasonable assumption.
Use two synchronized blocks separately instead of nested.
synchronized(from){
from.withdraw(amount);
}
synchronized(to){
to.deposit(amount);
}
So after from.withdraw(amount) is called, the lock on from is released before it tries to lock on to
The lock on an object by one thread, no other thread can enter any of the synchronized methods in that class ,but i want to know about non-synchronized method can access by other thread,,,,,,,
class Account {
private int balance = 50;
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
balance = balance - amount;
}
}
public class AccountDanger implements Runnable {
private Account acct = new Account();
public void run() {
for (int x = 0; x < 5; x++) {
this. d();
makeWithdrawal(10);
if (acct.getBalance() < 0) {
System.out.println("account is overdrawn!");
}
}
}
private synchronized void makeWithdrawal(int amt) {
if (acct.getBalance() >= amt) {
System.out.println(Thread.currentThread().getName()
+ " is going to withdraw"+amt);
try {
Thread.sleep(500);
// Thread.sleep(500);
} catch (InterruptedException ex) {
}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName()
+ " completes the withdrawal"+acct.getBalance());
} else {
System.out.println("Not enough in account for " + Thread.currentThread().getName()
+ " to withdraw " + acct.getBalance());
}
}
public static void main(String[] args) {
AccountDanger r = new AccountDanger();
Thread one = new Thread(r);
Thread two = new Thread(r);
one.setName("Fred");
two.setName("Lucy");
one.start();
two.start();
}
private void d() {
System.out.println("hhhhhhhhhhhhhhhhhhhhh"+Thread.currentThread().getName());
}
}
You have answer in your question itself :). If you are just looking for confirmation : YES.
No lock is required to access non-synchronized methods of an object.
If you want to know more about these concepts, visit Object Locks
Yes, the unsynchronized methods can be accessed/called by any Thread, that has/gets the reference to the same instance. Since you created a private Account instance and you didn't give this instance to any other class, in your example no other thread is able to access this special instance.
Good Day!
I need to solve synchronization problem using semaphores. I've read many tutorials and I now know that I should use a release method and am acquire method, however, i don't know where to use them in the code. could you please help me or link me to a useful tutorial.
I have class Account:
public class Account {
protected double balance;
public synchronized void withdraw(double amount) {
this.balance = this.balance - amount;
}
public synchronized void deposit(double amount) {
this.balance = this.balance + amount;
}
}
I have two threads: Depositer:
public class Depositer extends Thread {
// deposits $10 a 10 million times
protected Account account;
public Depositer(Account a) {
account = a;
}
#Override
public void run() {
for(int i = 0; i < 10000000; i++) {
account.deposit(10);
}
}
}
And Withdrawer:
public class Withdrawer extends Thread {
// withdraws $10 a 10 million times
protected Account account;
public Withdrawer(Account a) {
account = a;
}
#Override
public void run() {
for(int i = 0; i < 1000; i++) {
account.withdraw(10);
}
}
}
here is the main:
public class AccountManager {
public static void main(String[] args) {
// TODO Auto-generated method stub
Account [] account = new Account[2];
Depositor [] deposit = new Depositor[2];
Withdrawer [] withdraw = new Withdrawer[2];
// The birth of 10 accounts
account[0] = new Account(1234,"Mike",1000);
account[1] = new Account(2345,"Adam",2000);
// The birth of 10 depositors
deposit[0] = new Depositor(account[0]);
deposit[1] = new Depositor(account[1]);
// The birth of 10 withdraws
withdraw[0] = new Withdrawer(account[0]);
withdraw[1] = new Withdrawer(account[1]);
for(int i=0; i<2; i++)
{
deposit[i].start();
withdraw[i].start();
}
for(int i=0; i<2; i++){
try {
deposit[i].join();
withdraw[i].join();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Using a semapahore for your example could look like this:
import java.util.concurrent.Semaphore;
public class Account {
private Semaphore semaphore = new Semaphore(1);
private double balance = 0;
public void withdraw(double amount){
deposit(amount * -1);
}
public void deposit(double amount){
semaphore.acquireUninterruptibly();
balance += amount;
semaphore.release();
}
}
This example is very similar semantically to the synchronized locking one as it sets up a single Semaphore per Account instance (similar to the single mutex available for locking on an object instance). It also waits uninterruptibly (i.e. forever) to acquire a permit, similar to the under the hood code that tries to acquire a lock on an object. If you didn't want to wait forever, you could change your impl to something like this:
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class Account {
private Semaphore semaphore = new Semaphore(1);
private double balance = 0;
public void withdraw(double amount){
deposit(amount * -1);
}
public void deposit(double amount){
try {
semaphore.tryAcquire(1, TimeUnit.SECONDS);
balance += amount;
semaphore.release();
}
catch (InterruptedException e) {
//Probably want to throw a more specific exception type here...
throw new RuntimeException("Timed out waiting for an account balance...");
}
}
}
In this example, you will only want up to 1 second to acquire a permit, and throw an exception if that does not happen.
I'm not sure if caught your problem properly, but I'll give it a shot.
Your Account class is already thread safe as you are using the 'synchronized' keyword for the withdraw and deposit methods. When a 'synchronized' method is called it locks on 'this', so any two 'synchronized' methods will never run at the same time for one instance of 'Account'.
But if you want to be able to read the balance of one account you should add an accessor that also is synchronized. In that case the balance could only be read by one thread at a time, this could be changed by using a 'ReentrantReadWriteLock'. Here is a code on how you would use it:
class Account {
private double balance;
private ReentrantReadWriteLock balanceLock = new ReentrantReadWriteLock();
public void withdraw(double amount) {
try {
balanceLock.writeLock().lock();
this.balance = this.balance - amount;
}
finally {
balanceLock.writeLock().unlock();
}
}
public void deposit(double amount) {
try {
balanceLock.writeLock().lock();
this.balance = this.balance + amount;
}
finally {
balanceLock.writeLock().unlock();
}
}
public double getBalance() {
try {
balanceLock.readLock().lock();
return this.balance;
}
finally {
balanceLock.readLock().unlock();
}
}
}
In this case several threads can be reading the balance at a time, but only one thread at a time could change the balance.