Vikash Mishra
Vikash Mishra

Reputation: 97

Facing Issues in Multithreading

I have written a code where it will launch the fixed number of threads from the main class. Below function is just a part of it . All threads will come to this method. I have given thread names like USER1, USER2 etc.

My requirement is that in this method after driver=WebDriver....... statement all of my threads should wait until they all get the driver. I know we can join . But unable to implement here . Can someone please guide

private  void testSuitLogin(String driverType){

        try{
            System.out.println(Thread.currentThread().getName()+" Start Time "+System.currentTimeMillis());
            driver = WebDriverFactory.getDriver(driverType);
            System.out.println(Thread.currentThread().getName()+" End Time "+System.currentTimeMillis());
            homePage();
            googleSignIn();
            driver.quit();
        }
        catch(Exception e){
            if(driver==null)
            {
                totalNumberOfUsers--;
                return ;
            }
        }
    }

Upvotes: 1

Views: 65

Answers (2)

YoungHobbit
YoungHobbit

Reputation: 13402

You can use the CountDownLatch. Create a CountDownLatch with a fixed number of thread value and call countdown() after you get the instance of the WebDriver and then call await() to wait until all the threads arrive there.

CountDownLatch countDownLatch = new CountDownLatch(fixedNumber);

private  void testSuitLogin(String driverType){

  try{
    System.out.println(Thread.currentThread().getName()+" Start Time "+System.currentTimeMillis());
    driver = WebDriverFactory.getDriver(driverType);
    countDownLatch.countDown();  // decreases the value of latch by 1 in each call.
    countDownLatch.await();      //It will wait until value of the latch reaches zero.
    System.out.println(Thread.currentThread().getName()+" End Time "+System.currentTimeMillis());
    homePage();
    googleSignIn();
    driver.quit();
  }
  catch(Exception e){
    if(driver==null)
    {
      countDownLatch.countDown();
      totalNumberOfUsers--;
      return ;
    }
  }
}

Upvotes: 4

Koebmand STO
Koebmand STO

Reputation: 171

First: If all wait for all to get the driver, then you have a problem when one fails to get the driver.

In order to have all wait for each other (I don't think I have actually ever done that, but here is a suggestion). Since you know the number of threads, you can make something like:

  • Thread gets driver
  • Thread calls a synchronized method (only 1 thread can run it at a time) that decrements a counter by 1 (initialized to the number of threads).
  • Thread yields.
  • Thread runs again, calls a method that checks if the counter has reached 0.
  • A: Counter is not 0 yet, thread yields.
  • B: Counter is 0, thread continues its work.

Upvotes: 0

Related Questions