-
March 1st, 2013, 02:40 AM
#1
Interesting Synchronization problem
Hi,
Aim of the below program is to access "balance" variable by only 1 synchronized block code. But, it is seen that synchronization is not working properly here. Pl, let me know how this program can work perfectly i.e. should not produce any output but run in infinite loop.
<code>
// BalanceUpdateSynchronized.java
public class BalanceUpdateSynchronized {
// Start with balance as 100
private static int balance = 100;
public static void main(String[] args) {
// Start two threads to update the balance
startBalanceUpdateThread();
// Start one thread to monitor the balance
startBalanceMonitorThread();
}
public static void startBalanceUpdateThread() {
// Start a new thread that calls updateBalance() method
Thread t = new Thread()
{
public void run() {
while (true) {
synchronized(this)
{
balance=balance+10;
balance=balance-10;
}
}
}
};
t.start();
}
public static void startBalanceMonitorThread() {
// Start a thread that monitors the balance value
Thread t = new Thread() {
public void run() {
while (true) {
synchronized(this)
{
int b = balance;
//Ideally, balance should not change and this program run in
// infinite loop
if (b != 100) {
System.out.println("Balance changed: " + b);
System.exit(1); // Exit the program
}
}
}
}
};
t.start();
}
}
</code>
-
March 1st, 2013, 06:00 AM
#2
Re: Interesting Synchronization problem
You are synchronizing to two separate objects - the "this" in each case is the anonymous inner class.
If you add another object to synchronize to and change both synchronized(this) to synchronized(my object) ...
Code:
private static Object lockObject = new Object();
public static void startBalanceUpdateThread() {
// Start a new thread that calls updateBalance() method
Thread t = new Thread() {
public void run() {
while (true) {
synchronized(lockObject) {
balance=balance+10;
balance=balance-10;
}
}
}
};
t.start();
}
you will get the behavior you desire.
I'm not sure that this is the *best* way - I'm sure other contributors to this forum will have other suggestions.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|