How to create one instance of WebDriver per thread for parallel execution - multithreading

I am taking input for test from Data Provider where Data Provider is used in parallel.
Method will run in parallel so i want to create separate instance of WebDriver per method
Tried till now:
public class Demo {
private static final ThreadLocal<WebDriver> webDriverThreadLocal= new InheritableThreadLocal<>();
public static Logger log = Logger.getLogger(Demo.class.getName());
#BeforeMethod
public void beforeMethod() {
WebDriver driver=null;
DOMConfigurator.configure("log4j.xml");
Random random = new Random();
int cnt=random.nextInt(2);
if(cnt == 0) {
driver = new FirefoxDriver();
System.out.println(" New Firefox Driver Instantiated");
log.info("New Firefox Driver Instantiated");
}
else if(cnt == 1) {
System.setProperty("webdriver.chrome.driver","path");
driver = new ChromeDriver();
System.out.println(" New Chrome Driver Instantiated");
log.info("New Chrome Driver Instantiated");
}
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
webDriverThreadLocal.set(driver);
}
#Test(dataProvider = "dp1")
public void testPrelogin(TestCase testCase) {
WebDriver driver = webDriverThreadLocal.get();
//here call static methods of different classes for each screen
}
#DataProvider(name ="dp1",parallel=true)
public Object[][] dp() {
return new Object[][] {
new Object[] { 1, "a" },
new Object[] { 2, "b" },
};
}
#AfterMethod
public void afterClass() {
WebDriver driver = webDriverThreadLocal.get();
System.out.println("In after method for id:"+Thread.currentThread().getId()+" "+driver);
driver.quit();
}
Testng.xml
<suite name="Suite" parallel="methods" data-provider-thread-count="2">
<test name="prelogin" >
<classes>
<class name="com.package.Demo" />
</classes>
</test>
</suite>
With the above code multiple browsers are launched but out of 2 test atleast one of my test fails as browser screen becomes blank.
Is it because in some way thread resources are shared like webDriver or any other issue?

Related

How to perform parallel execution in selenium using ThreadLocal and PageFactory concepts

I am using Thread Local driver but still not able to achieve thread-safety while parallel execution.
2 chrome browser launched
both click registration link
then only one browser click on login and same browser again try to
click on login link and get error
other browser window did not click on login at all
My Driver factory class is
public class DriverFactory {
//Singleton design Pattern
//private constructor so that no one else can create object of this class
private DriverFactory() {
}
private static DriverFactory instance = new DriverFactory();
public static DriverFactory getInstance() {
return instance;
}
//factory design pattern --> define separate factory methods for creating objects and create objects by calling that methods
ThreadLocal<WebDriver> driver = new ThreadLocal<WebDriver>();
public WebDriver getDriver() {
return driver.get();
}
public void
setDriver(WebDriver driverParm) {
driver.set(driverParm);
System.out.println("Before Test Thread ID: "+Thread.currentThread().getId());
}
public void closeBrowser() {
driver.get().quit();
System.out.println("After Test Thread ID: "+Thread.currentThread().getId());
driver.remove();
}
}
My Browser Factory class is
public class BrowserFactory {
//create webdriver object for given browser
public WebDriver createBrowserInstance(String browser) throws MalformedURLException {
WebDriver driver = null;
//RemoteWebDriver driver = null;
if(browser.equalsIgnoreCase("Chrome")) {
WebDriverManager.chromedriver().setup();
System.setProperty("webdriver.chrome.silentOutput", "true");
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
DriverFactory.getInstance().setDriver(driver);
driver = new ChromeDriver(options);
}else if (browser.equalsIgnoreCase("firefox")) {
WebDriverManager.firefoxdriver().setup();
FirefoxOptions foptions = new FirefoxOptions();
foptions.addArguments("-private");
//driver = new RemoteWebDriver(new URL("http:192.168.225.219:4444/wd/hub"), DesiredCapabilities.firefox());
driver = new FirefoxDriver(foptions);
} if (browser.equalsIgnoreCase("ie")) {
WebDriverManager.iedriver().setup();
InternetExplorerOptions iOptions = new InternetExplorerOptions();
iOptions.addCommandSwitches("-private");
driver = new InternetExplorerDriver(iOptions);
}
return driver;
}
}
My TestBase class is
public class TestBase extends ActionEngine {
public WebDriver driver;
public BrowserFactory browserFactory;
String browserName = null;
//static ExtentReports extent = ExtentManager.getInstance();
/*public WebDriver getDriver() {
driver=DriverFactory.getInstance().getDriver();
return driver;
}*/
#BeforeMethod
public void LaunchApplication() throws Exception {
browserName = PropertiesOperations.getPropertyValueByKey("browser");
browserFactory = new BrowserFactory();
DriverFactory.getInstance().setDriver(browserFactory.createBrowserInstance(browserName));
//driver = browserFactory.initBrowser(browserName);
//driver = DriverFactory.getInstance().getDriver();
String url = PropertiesOperations.getPropertyValueByKey("url");
DriverFactory.getInstance().getDriver().get(url);
Thread.sleep(5000);
DriverFactory.getInstance().getDriver().manage().window().maximize();
System.out.println("Browser maximized");
DriverFactory.getInstance().getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#AfterMethod
public void tearDown() {
DriverFactory.getInstance().closeBrowser();
}
//#AfterMethod
public void assignDevice() {
ExtentFactory.getInstance().getExtent().assignDevice(browserName);
}
//#AfterMethod
public void assignAuthor() {
ExtentFactory.getInstance().getExtent().assignAuthor("Mayank Mishra");
}
}
TestNG.xml
<suite name="Demo Web App test suite" parallel="methods" thread-count="2" >
<listeners>
<listener
class-name="reusableComponents.ListenersImplementation" />
<listener
class-name="reusableComponents.TestRetryAnalyzerListener" />
</listeners>
<test name="LoginTests">
<classes>
<class name="Tests.LoginTest" />
</classes>
</test> <!-- Test -->
<!--<test name="DataDriven Tests">
<classes>
<class name="Tests.TestCase" />
</classes>
</test>--> <!-- Test -->
</suite> <!-- Suite -->
Page class is
public class RegistrationPage {
private WebDriver driver;
//Asserssion asserssion;
public RegistrationPage(WebDriver driver) {
//driver=DriverFactory.getInstance().getDriver();
this.driver = driver;
PageFactory.initElements(driver, this);
}
#FindBy(linkText = "ACCOUNT")
private WebElement accountLink;
#FindBy(linkText = "Register")
private WebElement registerLink;
#FindBy(linkText = "Log In")
private WebElement loginLink;
#FindBy(xpath = "//h3[contains(text(),'Contact Information')]/following-sibling::a")
private WebElement editAccountInfo;
#FindBy(xpath = "//a[contains(text(),'Forgot Your Password?')]")
private WebElement forgotPasswordLink;
//public static Logger logger = Logger.getLogger(RegistrationPage.class.getName());
//public static Logger log = Logger.getLogger("");
public void clickAccount() throws InterruptedException {
Thread.sleep(5000);
accountLink.click();
//loginLink.click();
//forgotPasswordLink.click();
//loginLink.click();
//driver=DriverFactory.getInstance().getDriver();
//driver.findElement(By.linkText("ACCOUNT")).click();
ExtentFactory.getInstance().getExtent().log(INFO,"Click on account link");
//Log.info("clicked on account link");
}
public void clickLoginLink() throws InterruptedException {
//Log.info("Click on login link");
Thread.sleep(5000);
loginLink.click();
ExtentFactory.getInstance().getExtent().log(INFO,"Click on login link");
}
public void clickForgotPasswordLink() throws InterruptedException {
//Log.info("Click on login link");
Thread.sleep(5000);
forgotPasswordLink.click();
ExtentFactory.getInstance().getExtent().log(INFO,"Click on forgot password link");
}
}
and my testclass is
public class LoginTest extends TestBase {
LoginPage loginPage;
RegistrationPage registrationPage;
ExcelOperations excel = new ExcelOperations("validLogin");
ExcelOperations excel2 = new ExcelOperations("invalidLogin");
//Dataprovider method --> return object array
#DataProvider(name = "validLogin")
public Object[][] testDataSupplier1() throws Exception {
Object[][] obj = new Object[excel.getRowCount()][1];
for (int i = 1; i <= excel.getRowCount(); i++) {
HashMap<String, String> testData = excel.getTestDataInMap(i);
obj[i - 1][0] = testData;
}
return obj;
}
#DataProvider(name = "invalidLogin")
public Object[][] testDataSupplier2() throws Exception {
Object[][] obj = new Object[excel2.getRowCount()][1];
for (int i = 1; i <= excel2.getRowCount(); i++) {
HashMap<String, String> testData = excel2.getTestDataInMap(i);
obj[i - 1][0] = testData;
}
return obj;
}
#BeforeMethod
public void loadClass() {
//loginPage = PageFactory.initElements(DriverFactory.getInstance().getDriver(), LoginPage.class);
registrationPage = PageFactory.initElements(DriverFactory.getInstance().getDriver(), RegistrationPage.class);
}
#Test(dataProvider = "invalidLogin", description = "login with invalid password")
public void loginTest_01(Object obj1) {
try {
System.out.println("in method1
registrationPage.clickAccount();
System.out.println("clicking on login link");
registrationPage.clickLoginLink();
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail("Cant do login");
}
}
#Test(dataProvider = "validLogin", description = "login with valid password")
public void loginTest_02(Object obj2) {
try {
System.out.println("in method2");
registrationPage.clickAccount();
System.out.println("clicking on login link");
Thread.sleep(5000);
registrationPage.clickLoginLink();
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail("Cant do login");
}
}
}
The below cleaned up version of your classes should basically solve your problem
import io.github.bonigarcia.wdm.WebDriverManager;
import java.util.Optional;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public final class DriverFactory {
private DriverFactory() {
//defeat instantiation
}
private static final ThreadLocal<WebDriver> driver = new ThreadLocal<>();
private static final String ERROR_MSG = "WebDriver instance NOT setup for current thread";
public static WebDriver getDriver() {
return Optional.ofNullable(driver.get())
.orElseThrow(() -> new IllegalStateException(ERROR_MSG));
}
public static void setupWebDriver(String browserFlavor) {
driver.set(createBrowserInstance(browserFlavor));
}
public static void closeBrowser() {
Optional.ofNullable(driver.get())
.orElseThrow(() -> new IllegalStateException(ERROR_MSG))
.quit();
driver.remove();
}
private static WebDriver createBrowserInstance(String browser) {
browser = Optional.ofNullable(browser).orElse("chrome").toLowerCase();
switch (browser) {
case "chrome":
WebDriverManager.chromedriver().setup();
System.setProperty("webdriver.chrome.silentOutput", "true");
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
return new ChromeDriver(options);
case "firefox":
WebDriverManager.firefoxdriver().setup();
FirefoxOptions foptions = new FirefoxOptions();
foptions.addArguments("-private");
return new FirefoxDriver(foptions);
case "ie":
WebDriverManager.iedriver().setup();
InternetExplorerOptions iOptions = new InternetExplorerOptions();
iOptions.addCommandSwitches("-private");
return new InternetExplorerDriver(iOptions);
default:
throw new IllegalArgumentException("Browser flavor [" + browser + "] is NOT supported");
}
}
}
Here's how your base class would now look like:
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class TestBase {
#BeforeMethod
public void LaunchApplication() {
String browserName = "chrome";
DriverFactory.setupWebDriver(browserName);
String url = "https://www.somedomain.com";
WebDriver driver = DriverFactory.getDriver();
driver.get(url);
driver.manage().window().maximize();
System.out.println("Browser maximized");
driver.manage().timeouts().implicitlyWait(Duration.of(30, ChronoUnit.SECONDS));
}
#AfterMethod
public void tearDown() {
DriverFactory.closeBrowser();
}
}
With the above two cleaned up classes, you now don't need an extraneous BrowserFactory.
Whenever you would need to access a WebDriver object for the current #Test annotated test method, you just need to invoke DriverFactory.getDriver()
Note: I am using the selenium apis from v4.4.0

Getting null pointer exception in generic runner class in cucmber+testng framework for aws device farm

I am working on cucmber + testng framework to open the browser in mobile in device farm but unable to open through cucmber framework.I am getting null pointer exception in generic runner class at tear down last line.
public class LoginTest extends TestBase{
AndroidDriver<MobileElement> driver;
private final String URL_STRING = "http://127.0.0.1:4723/wd/hub";
#Given("I navigate to the login page")
public void i_navigate_to_the_login_page() throws MalformedURLException {
URL url = new URL(URL_STRING);
driver = new AndroidDriver<MobileElement>(url, new DesiredCapabilities());
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.flipkart.com");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
#When("click on x button")
public void click_on_x_button() {
}
#CucumberOptions(
features = {"src/test/resources/feature"},
glue={"stepDef"},
tags = {"~#Ignore"}
)
public class GenericRunner extends AbstractTestNGCucumberTests {
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
#DataProvider
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
}
#AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
TestNGCucumberRunner testNGCucumberRunner=new TestNGCucumberRunner(this.getClass());
testNGCucumberRunner.finish();
}
}

Parallel execution in testNG using Maven

My scenario is to launch multiple chrome browsers(minimum 2) in Parallel.
I have created a separate class for WebDriver initialization, also I have 2 xml files and in that file it has 2 tests each.
WebDriver Initialization
public class LaunchBrowser
{
public WebDriver driver;
public WebDriver initDriver() {
if (driver == null) {
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
return driver;
}
}
XML file 1 : test method 1
public class Stackoverflow extends LaunchBrowser
{
#Test
public void 1test() throws InterruptedException
{
initDriver();
driver.get("https://stackoverflow.com");
Thread.sleep(3000);
System.out.println("Stack");
}
#Test
public void 2test() throws InterruptedException
{
Thread.sleep(3000);
}
}
XML file 1 : Test method 2
public class StackLogin extends LaunchBrowser
{
#Test
public void 1test() throws InterruptedException
{
driver.findElement(By.xpath("//a[#href='https://stackoverflow.com/users/login?
ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f']")).click();
Thread.sleep(3000);
}
#Test
public void 2test() throws InterruptedException
{
Thread.sleep(3000);
}
}
XML file 2 : Test method 1
public class Google extends LaunchBrowser
{
#Test
public void 1test() throws InterruptedException
{
initDriver();
driver.get("https://www.google.co.in");
Thread.sleep(3000);
System.out.println("Google");
}
#Test
public void 2test() throws InterruptedException
{
Thread.sleep(3000);
}
}
XML file 2 : Test Method 2
public class Gmail extends LaunchBrowser
{
#Test
public void 1test() throws InterruptedException
{
driver.findElement(By.xpath("//a[#href='https://mail.google.com/mail/?tab=wm'][text()='Gmail']")).click();
Thread.sleep(3000);
}
#Test
public void 2test() throws InterruptedException
{
Thread.sleep(3000);
}
}
testng1.xml
<suite name="Suite1">
<test name="01Stackoverflow">
<classes>
<class name="com.ci.selenium.Stackoverflow" />
</classes>
</test>
<test name="02StackLogin">
<classes>
<class name="com.ci.selenium.StackLogin" />
</classes>
</test>
</suite>
testng2.xml
<suite name="Suite2">
<test name="1Google">
<classes>
<class name="com.ci.selenium.Google"/>
</classes>
</test>
<test name="2Gmail">
<classes>
<class name="com.ci.selenium.Gmail"/>
</classes>
</test>
</suite>
Also I have made the below configurations in my pom.xml file
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<suiteXmlFiles>${file}</suiteXmlFiles>
<skipTests>false</skipTests>
<properties>
<property>
<name>suitethreadpoolsize</name>
<value>2</value>
</property>
</properties>
</configuration>
</plugin>
Finally I have triggered the XML file using the below maven command.
mvn clean test -Dfile=MyWork/testng1.xml,MyWork/testng2.xml
Result:
Two Chrome browsers were launched at a time, but only first test method in each xml file got passed and the second test in both xml files gets failed.
Kindly help me to fix this issue.
Logs
java.lang.NullPointerException
at com.ci.selenium.StackLogin.1test(StackLogin.java:12)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
... Removed 18 stack frames
I have launched multiple(minimum 2) chrome browsers in Parallel by using the below site.
Thread Local for Parallel Test Execution
To achieve this scenario, I have created 3 classes. One for WebDriver initialization and other classes for Threads.
Class 1
public class SetTestNG implements Runnable
{
public String xmlString;
public SetTestNG(String suitXMLUrl){
xmlString = suitXMLUrl;
}
#Override
public void run(){
List<String> testSuites = Lists.newArrayList();
testSuites.add(xmlString);
TestNG testng = new TestNG();
testng.setTestSuites(testSuites);
testng.run();
}
}
Class 2 : Main Class
public class MultiThread
{
private static String inputFiles;
private static String[] xmlFile;
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, InterruptedException
{
inputFiles = args[0];
xmlFile = inputFiles.split(",");
for(String file : xmlFile)
{
Thread object1 = new Thread(new SetTestNG(System.getProperty("user.dir")+"/"+file));
object1.start();
Thread.sleep(5000);
}
}
}
Note: The main use case of this code to launch Chrome browser for every single testNG Suite files.
You again need to initilize driver in your second Test method of both class
public class LaunchBrowser
{
public WebDriver driver =null;
public WebDriver initDriver() {
if (driver == null) {
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
return driver;
}
}
XML file 1 : Test method 2
public class StackLogin extends LaunchBrowser
{
#Test
public void 1test() throws InterruptedException
{
initDriver();
driver.findElement(By.xpath("//a[#href='https://stackoverflow.com/users/login?
ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f']")).click();
Thread.sleep(3000);
}
#Test
public void 2test() throws InterruptedException
{
Thread.sleep(3000);
}
}
XML file 2 : Test Method 2
public class Gmail extends LaunchBrowser
{
#Test
public void 1test() throws InterruptedException
{
initDriver();
driver.findElement(By.xpath("//a[#href='https://mail.google.com/mail/?tab=wm'][text()='Gmail']")).click();
Thread.sleep(3000);
}
#Test
public void 2test() throws InterruptedException
{
Thread.sleep(3000);
}
}
It looks like you want your webdriver instance to be created only once per <suite> tag and then shared across #Test annotated test methods that reside amongst multiple <test> tags.
For achieving this, you would need to change your LaunchBrowser class to something like below :
public class LaunchBrowser {
protected WebDriver driver;
#org.testng.annotations.BeforeSuite
public void initDriver() {
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}
You also need to refactor all your tests, so that they don't explicitly call LaunchBrowser.initDriver() else, it would cause the webdriver instantiation to be happened twice - explicitly by your call and implicitly once by TestNG due to the method being annotated using a #BeforeSuite annotation.
That should solve your use case. But please remember that this is the most in-efficient way of managing your webdriver instance, because you are now strictly confined to sequential execution. You cannot run tests in parallel.

Selenium / Appium Parallel Execution using JUnit 4

Trying to execute appium tests parallely on multiple devices. Idea goes like initiating JUnitRunner class as parameterized (e.g. deviceList) that creates parallel thread per device. From runner, invoking TestSuite via JUnitCore.run. Problem is that instantiating driver in test cases need device name (probably from Runner class), but JUnitCore doesnt provide such option (to invoke Suite / Test class by instantiating it). Any help?
Code goes like: JUnitRunner.java
#RunWith(Parallelized.class) // extension of the Parameterized runner
public class JUTRunner {
private String device;
/**
* #param device
*/
public JUTRunner(String device) {
this.device = device;
}
/**
* #return
*/
#Parameters
public static Collection<Object[]> getParameters() {
List<String> deviceList = findAllDevices();
List<Object[]> parameters = new ArrayList<Object[]>(deviceList.size());
for (String device : deviceList) {
parameters.add(new Object[] { device });
}
return parameters;
}
/**
* #return
*/
private static List<String> findAllDevices() {
return DeviceList.getInstance().getDeviceList();
}
/**
* #throws InterruptedException
*/
#Test
public void testOnDevice() throws InterruptedException {
Result result = JUnitCore.runClasses(JUTSuite.class);
Result result = new JUnitCore().run(suite);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
if (result.wasSuccessful()) {
System.out.println("All tests finished successfully...");
}
}
}
And TestCase.java
public class MyTest extends TestCase {
protected String device;
protected AppiumDriver<MobileElement> driver;
private int deviceNum;
#Rule
public TestName testName = new TestName();
#Before
protected void setUp() throws Exception {
this.driver = new AndroidDriver(device).getDriver();
}
#Test
public void testLogin() {
System.out.println(testName.getMethodName() + device);
}
}

How to stop an infinite thread in an application server

i have a JSF web application deployed under glassfish in which i have two buttons.The first start a infinite thread and the second stop it.My problem is that i can not stop a running thread.I have searched for a solution on the net but in vain.it works in case i have a J2SE application but not with a J2EE application here is my code
package com.example.beans;
import org.apache.commons.lang.RandomStringUtils;
public class MyBusinessClass {
public static void myBusinessMethod() {
/* this method takes a lot of time */
int i = 1;
while (i == 1) {
String random = RandomStringUtils.random(3);
System.out.println(random);
}
}
}
package com.example.beans;
import java.util.Random;
import java.util.TimerTask;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import com.example.core.RandomUtils;
public class MySimpleRunnableTask implements Runnable {
private Logger logger = Logger.getLogger(MySimpleRunnableTask.class);
#Override
public void run() {
MyBusinessClass.myBusinessMethod();
}
}
#ManagedBean(name = "MainView")
#SessionScoped
public class MainView {
private static Thread myThread;
#SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public String startSimpleThread() throws SecurityException,
NoSuchMethodException,
InterruptedException {
MySimpleRunnableTask mySimpleRunnableTask = new MySimpleRunnableTask();
myThread = new Thread(mySimpleRunnableTask);
myThread.start();
return null;
}
#SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public String stopSimpleThread() throws SecurityException,
NoSuchMethodException,
InterruptedException {
myThread.interrupt();
return null;
}
}
I have changed my code so you can understand really what's my problem
interrupt only sets the interrupt status in the thread to true. The thread needs to regularly pool the interrupt status flag to stop running:
public void run() {
/* you will have to touch the code here */
int i = 1;
while (i == 1) {
String random = RandomStringUtils.random(3);
logger.info(random);
if (Thread.currentThread().isInterrupted()) {
// the thread has been interrupted. Stop running.
return;
}
}
}
This is the only way to properly stop a thread : ask him to stop. Without cooperation from the running thread, there is no clean way.

Resources