Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6372077
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T01:11:08+00:00 2026-05-25T01:11:08+00:00

Using the java.util.concurrent.locks.ReentrantLock library as follows: Two threads generate a random number and use

  • 0

Using the java.util.concurrent.locks.ReentrantLock library as follows:

Two threads generate a random number and use it to update the shared variables account1 and account2 stored in class Accounts – a lock is used to protect the writing to the shared vars

package osproj221;
import java.util.concurrent.locks.ReentrantLock;

public class Accounts {
    private int account1,account2;
    private final ReentrantLock mutex;

    public Accounts(){
        account1=account2=0;
        mutex = new ReentrantLock();
    }

    public void updateAccounts(int amt){
        try{
            mutex.lock();
            account1 += amt;
            account2 -= amt;
        }catch(Exception ex){
            System.out.println(ex);
        }finally{mutex.unlock();}
    }

    public int getAccount1(){
        return this.account1;
    }

    public int getAccount2(){
        return this.account2;
    }
}

My threads implement the Runnable interface as follows:

package osproj221;
import java.util.Random;

public class RaceThread implements Runnable {

    private Random myRand = new Random();
    private int counter = 0;
    private Accounts accounts;

    public RaceThread(Accounts accounts){
        this.accounts = accounts;
    }

    public void run(){

        do{
            int r = myRand.nextInt(300);
            r = Math.abs(r);
            accounts.updateAccounts(r);
            counter++;
        }while((accounts.getAccount1() + accounts.getAccount2() == 0));

        System.out.println(counter + " " + accounts.getAccount1() + " " + accounts.getAccount2());
    }

}

and finally my Main class

package osproj221;

public class Main {

    public static void main(String[] args) {
        Accounts myAccounts = new Accounts();

        Thread t1 = new Thread(new RaceThread(myAccounts));
        Thread t2 = new Thread(new RaceThread(myAccounts));

        t1.start();
        t2.start();

        try{
            t1.join();
            t2.join();
        }catch(Exception ex){
            System.out.println(ex);
        }

        System.out.println(myAccounts.getAccount1() + " " + myAccounts.getAccount2());

    }

}

that looks a little longer than i thought it would – apologies. I would expect that neither of the threads would terminate, because account1+account2 should always = 0 as the mutex handles protecting the updating of account1 and account2. What seems to happen is that one of the threads exits because it fails the account1+account2==0 condition, and the other one continues indefinitely. im confused!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T01:11:10+00:00Added an answer on May 25, 2026 at 1:11 am

    It’s because you’re not locking the reads on your getters. This means thread 2 can read the data in an inconsistent state, while thread 1 is updating the data (between += and -=).
    The problem can happen as follows:

    Thread 1:

    1. updateAccounts(5);
    2. OBTAIN LOCK
    3. account1 += 5; -> account1 = 0 + 5; -> account1 = 5;

    Thread 2:

    1. getAccount1() <- returns 5
    2. getAccount2() <- returns 0
    3. 5+0 != 0 –> EXIT

    Thread 1:

    1. account2 -= 5 -> account2 = 0-5 -> account2 = -5;
    2. RELEASE LOCK.

    The solution:
    Unfortunately you can’t simply synchonize your getters individually I would instead recommend a new get method:

    public int getAccountsSum() {
        try {
            mutex.lock();
            return this.account1 + this.account2;
        } finally { mutex.unlock(); }
    

    and in RaceThread.run() change the while condition to:

        }while((accounts.getAccountsSum() == 0));
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been ask to build a multi-threaded java application using the java.util.concurrent library. I'm
I have realized some logic using integers import java.util.concurrent.locks.*; public class MassageSalon implements Salon{
Is there any advantage of using java.util.concurrent.CountdownLatch instead of java.util.concurrent.Semaphore ? As far as
I'm using a java.util.concurrent.ExecutorService that I obtained by calling Executors.newSingleThreadExecutor() . This ExecutorService can
I have a thread pool created using java.util.concurrent.ThreadPoolExecutor Is there anyway I can wait
Is there a way to convert milliseconds to minutes using java.util.concurrent.TimeUnit? This answer seems
When using any of the java.util.concurrent classes, do I still need to synchronize access
I'm trying to test java.util.concurrent.ConcurrentLinkedQueue when accessed via multiple threads. Mentioned below is my
I have code where I schedule a task using java.util.Timer . I was looking
I'm using Java, and need to generate a simple, standards-compliant RSS feed. How can

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.