thread synchronization problem (with updating a variable sum)
Clash Royale CLAN TAG#URR8PPP
thread synchronization problem (with updating a variable sum)
When I want to update with either synchronized keyword or lock, it works when the sum variable is int but not when it is an Integer object.
code looks like this -
public class TestSynchronized
private Integer sum = new Integer(0);
public static void main(String args)
TestSynchronized test = new TestSynchronized();
System.out.println("The sum is :" + test.sum);
public TestSynchronized()
ExecutorService executor = Executors.newFixedThreadPool(1000);
for (int i = 0; i <=2000; i++)
executor.execute(new SumTask());
executor.shutdown();
while(!executor.isTerminated())
class SumTask implements Runnable
Lock lock = new ReentrantLock();
public void run()
lock.lock();
int value = sum.intValue() + 1;
sum = new Integer(value);
lock.unlock(); // Release the lock
Lock lock = new ReentrantLock();
1 Answer
1
The problem is that you've separate locks
for each of the SumTask
objects. These objects should share the locks
instead.
locks
SumTask
locks
Create a lock
object once in TestSynchronized()
method. This should be shared by all the new SumTask(lock)
objects.
lock
TestSynchronized()
new SumTask(lock)
So your SumTask
class would look like:
SumTask
class SumTask implements Runnable
Lock lock;
public SumTask(Lock commonLock)
this.lock = commonLock;
public void run()
lock.lock();
int value = sum.intValue() + 1;
sum = new Integer(value);
lock.unlock(); // Release the lock
And don't forget to create a commonLock
object in TestSynchronized()
method:
commonLock
TestSynchronized()
Lock lock = new ReentrantLock();
executor.execute(new SumTask(commonLock));
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Lock lock = new ReentrantLock();
you are creating a new Object for every thread– Scary Wombat
14 mins ago