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 77465
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T20:50:04+00:00 2026-05-10T20:50:04+00:00

Here are two chunks of code that accomplish (what I think is) the same

  • 0

Here are two chunks of code that accomplish (what I think is) the same thing.

I basically am trying to learn how to use Java 1.5’s concurrency to get away from Thread.sleep(long). The first example uses ReentrantLock, and the second example uses CountDownLatch. The jist of what I am trying to do is put one thread to sleep until a condition is resolved in another thread.

The ReentrantLock provides a lock on the boolean I’m using to decide whether to wake the other thread or not, and then I use the Condition with await/signal to sleep the other thread. As far as I can tell, the only reason I would need to use locks is if more than one thread required write access to the boolean.

The CountDownLatch seems to provide the same functionality as the ReentrantLock but without the (unnecessary?) locks. However, it feels like I am kind of hijacking its intended use by initializing it with only one countdown necessary. I think it’s supposed to be used when multiple threads are going to be working on the same task, not when multiple threads are waiting on one task.

So, questions:

  1. Am I using locks for ‘the right thing’ in the ReentrantLock code? If I am only writing to the boolean in one thread, are the locks necessary? As long as I reset the boolean before waking up any other threads I can’t cause a problem, can I?

  2. Is there a class similar to CountDownLatch I can use to avoid locks (assuming I should be avoiding them in this instance) that is more naturally suited to this task?

  3. Are there any other ways to improve this code I should be aware of?

EXAMPLE ONE:

import java.util.concurrent.locks.*;  public class ReentrantLockExample extends Thread {  //boolean - Is the service down? boolean serviceDown;  // I am using this lock to synchronize access to sDown Lock serviceLock;  // and this condition to sleep any threads waiting on the service. Condition serviceCondition;  public static void main(String[] args) {     Lock l = new ReentrantLock();     Condition c = l.newCondition();      ReentrantLockExample rle = new ReentrantLockExample(l, c);      //Imagine this thread figures out the service is down     l.lock();     try {         rle.serviceDown = true;     } finally {         l.unlock();     }      int waitTime = (int) (Math.random() * 5000);     System.out.println('From main: wait time is ' + waitTime);     rle.start();     try {         //Symbolizes some random time that the service takes to come back up.         Thread.sleep(waitTime);     } catch (InterruptedException e) {         e.printStackTrace();     }      //Imagine this thread figures out that the service is back up.     l.lock();     try {         rle.serviceDown = false;         c.signal();     } finally {         l.unlock();     }  }  //Constructor public ReentrantLockExample(Lock l, Condition c) {       this.serviceLock = l;     this.serviceCondition = c;  }  /*  * Should wait for this imaginary service to come back online.  */ public void run() {     System.out.println('Thread: start awaiting');     serviceLock.lock();     try {         while (isServiceDown())         {                        serviceCondition.await();         }     } catch (InterruptedException e) {         // TODO Auto-generated catch block         e.printStackTrace();     } finally {         serviceLock.unlock();     }     System.out.println('Thread: done awaiting'); }   private boolean isServiceDown() {            return serviceDown; } } 

EXAMPLE TWO:

import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.*;  public class CountDownLatchExample extends Thread {      //boolean - Is the service down?     boolean serviceDown;      // I am using this latch to wait on the service.     CountDownLatch serviceLatch;        public static void main(String[] args) {         CountDownLatch cdl = new CountDownLatch(1);              CountDownLatchExample cdle = new CountDownLatchExample(cdl);          //Service goes down.         cdle.serviceDown = true;                  int waitTime = (int) (Math.random() * 5000);         System.out.println('From main: wait time is ' + waitTime);         cdle.start();         try {             //Symbolizes some random time that the service takes to come back up.             Thread.sleep(waitTime);         } catch (InterruptedException e) {             e.printStackTrace();         }          //Service comes back up.         cdle.serviceDown = false;         cdl.countDown();         }      //Constructor      public CountDownLatchExample(CountDownLatch cdl) {           this.serviceLatch = cdl;              }      /*      * Should wait for this imaginary service to come back online.      */     public void run() {         System.out.println('Thread: start awaiting');         try {             while (isServiceDown()) {                            serviceLatch.await();             }         } catch (InterruptedException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }         System.out.println('Thread: done awaiting');     }      private boolean isServiceDown() {                return serviceDown;     } } 
  • 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. 2026-05-10T20:50:05+00:00Added an answer on May 10, 2026 at 8:50 pm

    Either approach is roughly equivalent, except that a CountDownLatch can only be released once. After that all await() calls return instantly. So a CyclicBarrier may actually be more appropriate if you are working with a service that may go down and up.

    If your condition really is a one-shot deal, then a FutureTask would be more appropriate. You could call get() which would wait for the service to become available, and then you could use the service as soon as get() returns.

    You mention that CountDownLatch allows waiting without using Locks. However, both CountDownLatch and ReentrantLock are implemented using AbstractQueuedSynchronizer. Under the hood, they provide identical synchronization and visibility semantics.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 167k
  • Answers 167k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Try validates_associated. That should, I believe, allow the join model… May 12, 2026 at 1:34 pm
  • Editorial Team
    Editorial Team added an answer Try the PyWin stuff. It provides (among other things, like… May 12, 2026 at 1:34 pm
  • Editorial Team
    Editorial Team added an answer There are three problems I can see with your code:… May 12, 2026 at 1:34 pm

Related Questions

I'm actually struggling with some piece of code. I do know that it can
First of all, I'm fairly sure snapping to grid is fairly easy, however I've
I'm looking for the appropriate algorithm to use to compare two files. I think
What best practice or strategy would you use to enable bulk insert/update in an

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.