i got that question on todays interview.
class BankAccount {
private int money;
public synchronized void deposite(int sum) {
money += sum;
}
public synchronized void withdraw(int sum) {
money -= sum;
}
public synchronized int getMoney() {
return money;
}
}
class accountManager {
public void transfer(BankAccount a, BankAccount b, int money) {
}
}
So i need to write transfer() method, so it will be threadsafe and account balance should be >= 0.
public void transfer(BankAccount a, BankAccount b, int money) {
synchronized ( a ) {
synchronized ( b ) {
int temp = a.getMoney() - money;
if (temp >= 0) {
a.withdraw(temp);
b.add(temp);
}
}
}
}
I wrote this, but it produces deadlock when we transfer from a to b and from b to a simultaneously. So the 2nd question is, how to fix deadlock?
You have to lock the objects in the same order or you will get a deadlock.
BTW: given the lock is much more expensive than the operation performed you are better off using a global lock or just one thread.
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.
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
This question already has answers here:
Synchronizing on an Integer value [duplicate]
(9 answers)
Closed 7 years ago.
takeAmount and addAmount is simply to add/sub value from balanceAccount(eg. add 11,12...,20 or add 101,102...,110). balanceAccount have two version one is using synchronized function and other is using synchronized block.
Is that any different between BalanceAccount_synchronizedBlock and BalanceAccount_synchronizedFunction?
Indeed BalanceAccount_synchronizedFunction always return 0, while BalanceAccount_synchronizedBlock doesn't.
And...why it will show different behavior?
public class mainStart {
public static void main(String args[])
{
for (int i=1;i<3000;i=i+10)
{
new Thread(new addAmount(i)).start();
new Thread(new takeAmount(i)).start();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//BalanceAccount_synchronizedBlock.printAmount();
BalanceAccount_synchronizedFunction.printAmount();
}
}
class takeAmount implements Runnable {
private int startFrom;
public takeAmount(int start)
{
this.startFrom=start;
}
public void run()
{
for (int i=startFrom;i<startFrom+10;i++)
//BalanceAccount_synchronizedBlock.sub(i);
BalanceAccount_synchronizedFunction.sub(i);
}
}
class addAmount implements Runnable {
private int startFrom;
public addAmount(int start)
{
this.startFrom=start;
}
public void run()
{
for (int i=startFrom;i<startFrom+10;i++)
//BalanceAccount_synchronizedBlock.add(i);
BalanceAccount_synchronizedFunction.add(i);
}
}
public class BalanceAccount_synchronizedBlock {
public static Integer amount=0;
public static void add(int a)
{
synchronized (amount)
{
amount = amount + a;
}
}
public static void sub(int a)
{
synchronized (amount)
{
amount = amount - a;
}
}
public synchronized static void printAmount()
{
System.out.println("Amount " + amount);
}
}
public class BalanceAccount_synchronizedFunction {
public static Integer amount=0;
public synchronized static void add(int a)
{
amount = amount + a;
}
public synchronized static void sub(int a)
{
amount = amount - a;
}
public synchronized static void printAmount()
{
System.out.println("Amount " + amount);
}
}
Synchronizing a method uses the enclosing class as a synchronization token. When you write synchronized(amount) you are using an Integer instance as a synchronization token. As you are not using the same token in both cases, the lock will not occur as expected.
Also note that Integer is immutable, and every time you reassign a value into amount, you are creating a new instance an lose whatever lock you may have had on the previous value.
Your print method is defined as
public synchronized static void printAmount()
which is synchronized on the class itself. In the case of your "block" attempt, the blocks are synchronizing on amount, while the print method is synchronizing on the class. Change that method to use a block also synchronized on amount.
As Kayaman pointed out, you also have the problem that you're synchronizing on a variable (amount) whose referent is constantly changing. Instead, declare a private static final Object LOCK = new Object() that is used only for synchronization--or better yet, just use AtomicInteger.
You can either lock using object which is calling this method by using
synchronized (this) { // this is similar to method level synchronization
Or using another class level Object other then amount integer(as #Kayaman pointed out, it is immutable so every time new integer object is created when you update it)
public class BalanceAccount_synchronizedBlock {
public static Integer amount=0;
public static Object Lock = new Object();
public static void add(int a) {
synchronized (Lock) {
amount = amount + a;
}
}
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.
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);
}