Java Synchronization question

Hi gurus,

I have a question about Synchronization.

for example, I have a class,BankAccount, it has two methods, deposit(doube money), withdraw(double money).

I also have a class, Customer, which extends Thread/implements Runnable. The run() method is

public void run()
{
this.deposit(100);
this.withdraw(200);
}

The constructor of Customer class is
public Customer(BankAcount account)
{
this.account=account;
}

Suppose I have two customer object

Customer dad=new Customer (anAccount);
Customer son=new Customer (anAccount);

I am learing Synchronization but I am a bit confused.

How can I make sure that:

1) Only dad or son, not both, can deposit or withdraw (use sunchronized, right?)
2) Only one of dad or son, can do two transcations in order. that is, the person (the father or son) makes two transactions in pair. in other words, no such cases, the father deposits 100 dollars, and then the son withdraws 200 dollars.

I will appreciate it if you could explain thread/Synchronization  a bit more.

Thanks
LVL 1
tiger0516Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mayank SAssociate Director - Product EngineeringCommented:
BTW, why does Customer extend Thread/ implement Runnable? The customer class should perhaps only hold data and the logic/ processing should be done in a separate class.

When does the thread get started and how long does it run (do you have a loop, etc in your run () method or is it just as much as you have shown?).

You can use a static object like:

private static Object synchronizer = new Object () ; // data member of the class

Then lock it while doing the transactions:

synchronized ( synchronizer )
{
  this.deposit ( 100 ) ;
  this.withdraw ( 200 ) ;

}

This will make sure that only one object of the class runs this block of code at a point of time and the other one will have to wait.
0
tiger0516Author Commented:
>BTW, why does Customer extend Thread/ implement Runnable? The customer class should perhaps only hold data and the logic/ processing should be done in a separate class.

:) It is because I think I need an example, and I thought about this, which is easy to understand.
0
Mayank SAssociate Director - Product EngineeringCommented:
Well, its not actually the best way.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Mayank SAssociate Director - Product EngineeringCommented:
Did you try the code I posted?
0
NelliosCommented:
This is the classic "Racing Conditions" issue. You can google "Racing Conditions" and find lots & lots of examples.

The approach that I usally use is having a lock for each resource that is being accessed by multiple threads.

public static boolean lock=false;
public synchronized void deposit(double amount){
while(lock){
wait();
}
lock=true;
//Deposit code
lock=false;
notifyAll();
}

public synchronized void withdraw(double amount){
while(lock){
wait();
}
lock=true;
//Withdraw code
lock=false;
notifyAll();
}

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Manikandan ThiagarajanSenior consultantCommented:
synchronized is used to avoid data corruption
0
colr__Commented:
If you synchronize the method on an object, this means that the code within the synchronized block can only run if it gets hold of the 'object lock'. So, when the code below is run, the first thing that happens is that the thread obtains the lock for the object 'mutex'. While the thread has the lock, no other thread can obtain the lock, so you effectivvely prevent symultaneous access of the synchronised block.

synchronized(mutex){
// mutually exclusive code
...
}

The advantage of using the object 'mutuex' is that it can be declared elsewhere and can be used to limit access across threads in different classes, so you can effectively limit access to multiple methods at the same time, across multiple classes if you wanted.

The code belowalso does the same thing but works slightly differently:

synchronized{
// mutually exclusive code
...
}

In this instance, the object lock is obtained of the current instance. With this method, you can only synchronise code within the same class. This is usually acceptable for most uses of synchronisation.

colr__
0
Mayank SAssociate Director - Product EngineeringCommented:
BTW, is that the only comment you want to accept?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.