JAVA THREADLOCAL

Posted by MCRSR on April 18, 2023

ThreadLocal

In Java, ThreadLocal is a class that provides a way to create variables that are local to a particular thread. A ThreadLocal variable is a special type of variable that is created and maintained separately for each thread, and its value can be accessed and modified only by the same thread that created it.

The ThreadLocal class provides two methods to interact with its instances:

  • get(): This method returns the value of the ThreadLocal variable for the current thread. If no value has been set for the current thread, it returns null.
  • set(): This method sets the value of the ThreadLocal variable for the current thread.

One of the primary use cases of ThreadLocal is to maintain state that is specific to a particular thread. For example, consider a web application that handles multiple requests concurrently. Each request may require some state information to be stored (such as a user's session information). Using ThreadLocal, you can create a session object that is local to the current thread and store the state information in that object. This way, each thread can maintain its own copy of the session object, and there will be no interference between different threads.

Here is an example of how to use ThreadLocal in Java:

            
public class MyThreadLocalClass {
    private static ThreadLocal myThreadLocal = new ThreadLocal<>();

    public static void setValue(String value) {
        myThreadLocal.set(value);
    }

    public static String getValue() {
        return myThreadLocal.get();
    }
}                
            
        

In this example, we have created a ThreadLocal variable named myThreadLocal. We have also defined two methods setValue() and getValue() to set and get the value of this variable. When a value is set using setValue(), it is set only for the current thread. Similarly, when the value is retrieved using getValue(), it is retrieved only for the current thread.

use of ThreadLocal in java selenium with examples

In Selenium, ThreadLocal can be used to maintain a separate instance of the WebDriver object for each thread. This can be useful when running Selenium tests in parallel, as it ensures that each thread has its own WebDriver instance and avoids interference between different threads.

Here's an example of how to use ThreadLocal in Java Selenium:

            
public class WebDriverFactory {
    private static ThreadLocal webDriverThreadLocal = new ThreadLocal<>();

    public static WebDriver getDriver() {
        return webDriverThreadLocal.get();
    }

    public static void setDriver(WebDriver driver) {
        webDriverThreadLocal.set(driver);
    }

    public static void removeDriver() {
        webDriverThreadLocal.remove();
    }
}
            
        

In this example, we have created a ThreadLocal variable named webDriverThreadLocal to store a separate instance of the WebDriver object for each thread. We have also defined three methods getDriver(), setDriver(), and removeDriver() to get, set, and remove the WebDriver instance for the current thread.

To use this WebDriverFactory class, we can create a new instance of the WebDriver object for each thread and set it using the setDriver() method. Here's an example of how to use this class in a test:

            
public class MySeleniumTest {
    @Test
    public void test() {
        WebDriver driver = new ChromeDriver();
        WebDriverFactory.setDriver(driver);

        // Test code here

        WebDriverFactory.removeDriver();
        driver.quit();
    }
}                
            
        

In this example, we create a new instance of the ChromeDriver object and set it using the setDriver() method. We can then use the getDriver() method to retrieve the WebDriver instance for the current thread and perform our test code. Finally, we remove the WebDriver instance for the current thread using the removeDriver() method and quit the WebDriver. This ensures that each thread has its own WebDriver instance and avoids interference between different threads.

                                
                                    import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.safari.SafariDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class DriverFactory {

	public WebDriver driver;

	public static ThreadLocal tlDriver = new ThreadLocal<>();

	/**
	 * This method is used to initialize the thradlocal driver on the basis of given
	 * browser
	 * 
	 * @param browser
	 * @return this will return tldriver.
	 */
	public WebDriver init_driver(String browser) {

		System.out.println("browser value is: " + browser);

		if (browser.equals("chrome")) {
			WebDriverManager.chromedriver().setup();
			tlDriver.set(new ChromeDriver());
		} else if (browser.equals("firefox")) {
			WebDriverManager.firefoxdriver().setup();
			tlDriver.set(new FirefoxDriver());
		} else if (browser.equals("safari")) {
			tlDriver.set(new SafariDriver());
		} else {
			System.out.println("Please pass the correct browser value: " + browser);
		}

		getDriver().manage().deleteAllCookies();
		getDriver().manage().window().maximize();
		return getDriver();

	}

	/**
	 * this is used to get the driver with ThreadLocal
	 * 
	 * @return
	 */
	public static synchronized WebDriver getDriver() {
		return tlDriver.get();
	}
}