Amol
Amol

Reputation: 303

can i make this class thread safe via immutable object?

i have a class in which i have 2 people which check balance and withdraw money from a common account .. i have made the the transaction thread safe via synchronized keyword but it has a lot of overhead , i have read about immutable objects and thread safety they provide . but i am unable to make this class thread safe via immutable object

code :

final class bank implements Runnable
{
private final int balance,min_balance;

bank(int bal,int mbal)
{
  this.balance=bal;
  this.min_balance=mbal;
}
@Override
public void run()
{
   transaction();

}
public void transaction()
{
   if(checkBalance()> min_balance)
    {
     System.out.println("checkin is done by : "+Thread.currentThread().getName()
             +" and Balance left in the account is : "+checkBalance()); 
     System.out.println(Thread.currentThread().getName()+" is going to sleep ...");
    try{

       Thread.currentThread().sleep(2000); }
       catch(Exception e){
       }
    System.out.println(Thread.currentThread().getName()+" Woke up ..");
    withdraw();  
    System.out.println(Thread.currentThread().getName()+" has made the withdrawl ..");
   }
   else{
      lowBalance();   
   }
}

int checkBalance()
{
   return balance;
 }
 void lowBalance()
 {
     System.out.println("balance is not adequate");
 }

void withdraw()
{
   balance=balance-20;  //this wont work as balance is private
}

}

public class ryanmonica {

  public static void main(String args[])
  {
   bank obj=new bank(100,20);
   Thread t1=new Thread(obj);
   Thread t2=new Thread(obj);
   t1.setName("Ryan");
   t2.setName("Monica");
   t1.start();
   t2.start(); 

 }
}

Upvotes: 0

Views: 50

Answers (1)

TheLostMind
TheLostMind

Reputation: 36304

An immutable object's state never changes. Since you need state change in your instance (balance and minBalance are changing), you need to use synchronization mechanism.

Immutable objects are thread-safe because they don't allow state change in their instances.

Upvotes: 1

Related Questions