What is the process for recreating a thread with different parameters?

I am working on a multithreading program that sends emails to my clients. However, I am facing some issues with the threads in my code - they only close the window of Firefox and do not continue the desired actions. I am looking to create an algorithm where if a thread encounters issues and closes the Firefox window (using Selenium), it should then retrieve new parameters from my database and restart the thread with these new parameters. Additionally, I would like to have 5-10 threads running continuously at all times.

Main method:

static String path = "C:\\Users\\Admin\\Desktop\\clients.txt";
static String path_ok = "C:\\Users\\Admin\\Desktop\\clients2.txt";
static Integer numberMail = 1;
static List<User> users = new ArrayList<User>();

YandexConfig config1 = new YandexConfig("login1", "password1", "cookies", port1);
YandexConfig config2 = new YandexConfig("login2", "password2", "cookies", port2);
ExecutorService executor = Executors.newFixedThreadPool(50);
CompletableFuture.runAsync(new DoThread("thread 1", path, path_ok, numberMail, users, config1), executor);
CompletableFuture.runAsync(new DoThread("thread 2", path, path_ok, numberMail, users, config2), executor);

doThread:

class DoThread implements Runnable {
    private String threadName;
    private Integer numberMail;
    private String themeMessage = "Your order";
    private String messageDefault = "blabla";
    private final List<User> users;
    private final String fileWait;
    private final String fileOk;
    private final YandexConfig config;

    DoThread(String threadName, String fileWait, String fileOk, Integer numberMail, List<User> users, YandexConfig config) {
        this.threadName = threadName;
        this.fileWait = fileWait;
        this.fileOk = fileOk;
        this.numberMail = numberMail;
        this.users = users;
        this.config = config;
    }

    public void run() {
        System.out.println("Thread #" + threadName + " started");

        while (true) {
            try {
                auth(threadName, config.login, config.password);
                break;
            } catch (InterruptedException e) {

                System.out.println("Something goes wrong");

                e.printStackTrace();
            }
        }
            //more code here
    }
}

Question: How can I effectively restart a thread with new parameters as per the requirements outlined above?

Answer №1

If you are looking to adjust the parameters for the next thread, you will need to provide setters for the data and then initiate another thread.

class DoThread implements Runnable {
    ...
    void setThreadName(String name) { ... }
    void setFileOK(String fileOK) { ... }
}

class UseDoThread {
    void f() {
        DoThread r = new DoThread(...);
        new Thread(r).start();
        ...
        r.setThreadName("?");
        r.setFileOK("I think so");
        new Thread(r).start();
}

However, caution: It is crucial to wait for the thread to finish before modifying the values and restarting. Failing to do so may lead to corrupt data being used in the initial run. You can ensure that the thread finishes by utilizing the join method.

If simply using join defeats the purpose of implementing multithreading, consider creating a new instance of DoThread for each thread.

void f() {
    new Thread(new DoThread("thread1", ...)).start();
    new Thread(new DoThread("thread2", ...)).start();
}

This is why disposable classes with final values are preferred in concurrent programming. Each thread should have its own unique version, eliminating the need to recycle such a class. If you anticipate creating a new instance of DoThread each time, it might be beneficial to declare all fields in DoThread as final.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python offers a straightforward way to execute Selenium WebDriver tests that are stored in a subdirectory. This

Being new to Python, I am seeking assistance and patience with my lack of knowledge. The current file structure is as follows: parentDir\ runTests.py commonpageelements.py testcases\ __init__.py test1.py test ...

Jenkins encountered an issue with a tooltip appearing over a dot on a Highchart graph

Having an issue with retrieving information from dots on a graphic like this: When attempting to get the info inside each dot, the tooltip is present but Selenium fails to recognize the dot, resulting in an error: "org.openqa.selenium.WebDriverException: ...

Selenium encountered an error: Element not found - Could not locate element: {"method":"CSS selector","selector":"*[data-test="email-input"]}

Recently, my application has been encountering an error when trying to log in through a web form. The issue seems to be with locating the email input field: "no such element: Unable to locate element: {"method": "css selector", "s ...

Selenium javascript troubleshooting: encountering problems with splitting strings

Hello, I am new to using selenium and encountering an issue with splitting a string. <tr> <td>storeEval</td> <td>dList = '${StaffAdminEmail}'.split('@'); </td> <td>dsplit1 </td> < ...

Enabling Unverified SSL Certificates in Opera Browser for Selenium Testing using Java

Is there a way to configure Selenium WebDriver to accept untrusted certificates on the Opera browser? I attempted to implement this code, but it did not produce the desired outcome. DesiredCapabilities capabilities = new DesiredCapabilities(); capabiliti ...

Array of Arrays Jolt Transformation Specification

I have a JSON input with specific fields and values. I need help creating the expected output in JSON format. Input JSON: { "Features": [ "fields": [ { "name": "featureName" ...

Find the parent element that houses a particular child element

I am searching for a way to identify all the parent elements that have a certain child element within them. <tr> <i class="myClass"> </i> </tr> For example, I want to find all tr elements that contain an i element with the specif ...

Troubleshooting the malfunction of Jackson Mixin in converting Pojo to JSON

I have successfully converted XML to Pojo using JAXB, and now I am attempting to convert Pojo to JSON using Jackson Jaxb. However, the resulting JSON includes fields from the JAXBElement class that I want to remove. { "name" : "{http://xxx.xx.xx.xx.xx.x ...

Selenium encountering difficulty locating element within collapsible container

Recently, I attempted to automate the Make My Trip website using Selenium. Here is a rundown of the steps I followed: Started by searching for MakeMyTrip on Google -> Completed Navigated to Makemytrip and switched the country to US -> Completed Clicked o ...

Automatic scrolling feature in JavaFX

I am currently working on developing a chat box using JavaFX. My goal is to implement an auto-scroll feature that will scroll down the page when it gets filled up. However, I am facing some issues with this functionality. import javafx.application.Applica ...

Is there a way to access a URL using the IJavaScriptExecutor in Selenium with C#?

When using selenium in C#, it is common practice to use the driver.Navigate method to navigate to a link. For example: driver.Navigate(driver.FindElement(linkLocator).GetAttribute("href")); However, I am curious if there is a way to accomplish this usin ...

Guide on how to send a file to DHC-REST/HTTP API using Selenium

In an attempt to send a POST request using the Chrome extension DHC, I encountered an issue where the uploaded file's size appeared as 0 bytes. The code snippet I used is as follows: from selenium.webdriver.chrome.options import Options from selenium ...

Tips on patiently waiting for a progress bar to complete its process before verifying the final outcome

When I initiate a process, such as creating a Distribution group, it triggers a progress bar that indicates three possible statuses: Failed, In Progress, and Completed. How can I set up a wait for the progress bar to finish its task, and then verify the ou ...

Latest JSON toolkit for fetching information from URLs

Currently, I am on the hunt for a reliable and updated JSON file that can successfully extract information from a link like this one: https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=CAD By clicking on the above link, you will be able to view the ...

Selenium GUI tests are not showing up when running in Jenkins on a Windows 7 machine

I am encountering an issue where when I run my Selenium test (mvn test) from Jenkins on a Windows system, I can only see the console output and not the actual browsers being opened. Is there a way to configure Jenkins so that I can view the browsers runn ...

Turning ResultSet into a json object in Restlet framework: A step-by-step guide

After executing a query on a table, I now have a ResultSet object: ResultSet result = stat.executeQuery("SELECT * FROM Greetings"); I am looking to convert this ResultSet object into JSON format and send it back to the web client. Can a Restlet tool be u ...

Delaying until the specified text is found in the element is not the same as the given string

I need to find a method for making the selenium webdriver pause until the text in the specified element location is NOT the same as the string provided in the code below. wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//*[@id=&bso ...

Encountering org.openqa.selenium.firefox.NotConnectedException while using Selenium Java 3.0.1 with Firefox version 51.0.1

Encountering org.openqa.selenium.firefox.NotConnectedException while using selenium java 3.0.1 with firefox version 51.0.1. Attempting to utilize the Gecko driver. This is my code public class Gecko { String driverPath = "/home/hema/Downloads/Softwa ...

Determining dynamic captcha changes using Selenium after submission: A step-by-step guide

Despite my efforts, I have been unable to find a solution to my issue. I need confirmation that the captcha (two numbers) changes after invalid submissions. The two numbers can be found in a span tag on this URL: . Here are the steps: Open Fill out the ...

Issue with Docker's depends_on flag not successfully handling dependencies between containers

My goal is to set up a Selenium hub, Chrome node, and Firefox node, and then run the test execution script in that specific order. I have the nodes depending on the hub, and the code depends on both the hubs. However, when I run docker-compose --build, it ...