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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T13:38:08+00:00 2026-06-04T13:38:08+00:00

I use a CountDownLatch for waiting for a certain event from another component (running

  • 0

I use a CountDownLatch for waiting for a certain event from another component (running in a different thread). The following approach would fit the semantics of my software, but I’m not sure whether it works as a I expect:

mCountDownLatch.await(3000, TimeUnit.MILLISECONDS)
otherComponent.aStaticVolatileVariable = true;
mCountDownLatch.await(3500, TimeUnit.MILLISECONDS);
... <proceed with other stuff>

The scenario should be the following: I wait for 3 seconds, and if the latch is not counted down to 0, I notify the other component with that variable, and then I wait at most 3.5 seconds. If there is timeout again, then I don’t care and will proceed with other operations.

Note: I know it doesn’t look like that, but the above scenario is totally reasonable and valid in my software.

I did read the documentation of await(int,TimeUnit) and CountDownLatch, but I’m not a Java/Android expert, so I need confirmation. To me, all scenarios look valid:

  • If the first await is successful, then the other await will return immediately
  • If the first await times out, then the other await is still valid;
    therefore, if the other thread notices the static signal,the second
    await might return successfully
  • Both await calls time out (this is fine according to my software’s semantics)

Am I using await(…) correctly? Can a second await(…) be used in the above way even if a previous await(…) on the same object timed out?

  • 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-06-04T13:38:09+00:00Added an answer on June 4, 2026 at 1:38 pm

    If I understand your question correctly, this test proves that all your assumptions/requirements are true/met. (Run with JUnit and Hamcrest.) Note your code in the runCodeUnderTest() method, though it’s interspersed with time recording and the timeouts are reduced by a factor of 10.

    import org.junit.Before;
    import org.junit.Test;
    
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.TimeUnit;
    
    import static org.hamcrest.Matchers.closeTo;
    import static org.hamcrest.Matchers.lessThan;
    import static org.junit.Assert.assertThat;
    
    public class CountdownLatchTest {
        static volatile boolean signal;
        CountDownLatch latch = new CountDownLatch(1);
        long elapsedTime;
        long[] wakeupTimes = new long[2];
    
        @Before
        public void setUp() throws Exception {
            signal = false;
        }
    
        @Test
        public void successfulCountDownDuringFirstAwait() throws Exception {
            countDownAfter(150);
            runCodeUnderTest();
            assertThat((double) elapsedTime, closeTo(150, 10));
            assertThat(wakeupTimeSeparation(), lessThan(10));
        }
    
        @Test
        public void successfulCountDownDuringSecondAwait() throws Exception {
            countDownAfter(450);
            runCodeUnderTest();
            assertThat((double) elapsedTime, closeTo(450, 10));
            assertThat((double) wakeupTimeSeparation(), closeTo(150, 10));
        }
    
        @Test
        public void neverCountDown() throws Exception {
            runCodeUnderTest();
            assertThat((double) elapsedTime, closeTo(650, 10));
            assertThat((double) wakeupTimeSeparation(), closeTo(350, 10));
        }
    
        @Test
        public void countDownAfterSecondTimeout() throws Exception {
            countDownAfter(1000);
            runCodeUnderTest();
            assertThat((double) elapsedTime, closeTo(650, 10));
            assertThat((double) wakeupTimeSeparation(), closeTo(350, 10));
        }
    
        @Test
        public void successfulCountDownFromSignalField() throws Exception {
            countDownAfterSignal();
            runCodeUnderTest();
            assertThat((double) elapsedTime, closeTo(300, 10));
        }
    
        private int wakeupTimeSeparation() {
            return (int) (wakeupTimes[1] - wakeupTimes[0]);
        }
    
        private void runCodeUnderTest() throws InterruptedException {
            long start = System.currentTimeMillis();
            latch.await(300, TimeUnit.MILLISECONDS);
            wakeupTimes[0] = System.currentTimeMillis();
            signal = true;
            latch.await(350, TimeUnit.MILLISECONDS);
            wakeupTimes[1] = System.currentTimeMillis();
            elapsedTime = wakeupTimes[1] - start;
        }
    
        private void countDownAfter(final long millis) throws InterruptedException {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sleep(millis);
                    latch.countDown();
                }
            }).start();
        }
    
        private void countDownAfterSignal() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean trying = true;
                    while (trying) {
                        if (signal) {
                            latch.countDown();
                            trying = false;
                        }
                        sleep(5);
                    }
                }
            }).start();
        }
    
        private void sleep(long millis) {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException e) {
                throw new IllegalStateException("Unexpected interrupt", e);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

use pthread_create to create limited number of threads running concurrently Successfully compile and run
Use Eclipse Classic with ADT plugin. Tried to make project from existing example of
use Thread; use warnings; use Tk; my $x = 10; my $mw = new
use qcvalues_test go select [finalConc] ,[rowid] from qvalues where rowid in (select rowid from
I frequently need to have a thread wait for the result of another thread.
I have a thread that updates it's state from time to time and I
I have the following code from apache's svn. As you can see this is
USE AdventureWorks2008R2; GO INSERT INTO myTestSkipField SELECT * FROM OPENROWSET(BULK 'C:\myTestSkipField-c.dat', FORMATFILE='C:\myTestSkipField.fmt' ) AS
Use these 2 persistent CFCs for example: // Cat.cfc component persistent=true { property name=id
Use case: user clicks the link on a webpage - boom! load of files

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.