Home > Software engineering >  How to set name to instance of ThreadLocal
How to set name to instance of ThreadLocal

Time:12-21

I want to set name to each instance of the ThreadLocal variable of type WebDriver. And then get the ThreadLocal instance by name. Is there a way to set and get ThreadLocal instance by name?

Here is my class where I want to add the set and get functions.

public class DFactory {
    private DFactory() {

    }

    private static DFactory dInstance= new DFactory();

    public static DFactory getInstance() {
        return dInstance;
    }

    ThreadLocal<WebDriver> driver = new ThreadLocal<WebDriver>();

    public WebDriver getDriver() {
        return driver.get();
    }

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

CodePudding user response:

Is there a way to set and get ThreadLocal instance by name?

No, there isn't a way.

ThreadLocal variables don't have names, and cannot be accessed by name. That is not part of the ThreadLocal API.

It is not clear what you are trying to achieve here, but one possibility is to create a ThreadLocal whose type is Map<String, Object> and store your "named" variables in the maps.

  • Related