Code only executes once.
Disclaimer: Well aware this is an infinite loop, wrote it this way as part of troubleshooting the problem.
update: There was an exception in my error log that got fixed and the problem is still the same, code only executes once
I tried using the same for loop in the same code for a different task (printing a sentence) and it worked fine, problem must be with my JS code.
for(int i=0; i<i+1;i++) {
((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("https://www.google.com");
}
Code is executing only once because of an exception being thrown, OR maybe one or more of the network calls you are making is taking too long that makes you believe that the code is executing only once.
To confirm that the value i + 1, which you are using in the for-loop isn't getting replaced by 1, I ran the following loop on my machine:
for (int i = 0; i < i + 1; i++) {
System.out.println(i);
}
...and it goes on to print numbers starting from 0.
I'm just going to clarify this point as an answer, as I expect the question will be removed.
The for loop isn't your problem. You are writing code which has an exception or is blocking the running thread. If you're using another thread to run this, a lack of an UncaughtExceptionHandler can allow it to skip being logged. Similarly the use of Callable<T> can result in exceptions being swallowed from personal experience (perhaps for the same reason?).
If you are blocking the thread running it, then that thread won't run anything else until the blocking method returns control to the context of where you called it.
Given you said you had cases where the loop "ran once" but still printed after, I'm going to go with it being an exception, and the way that you are running your test is flawed. This can be from an uncountable number of reasons, such as a folly System#exit/Runtime#halt call, threads, using a service to run the tests, or running them in some production environment like a game server or a phone (or... A browser?). For future cases, your questions should ideally be reproducible with nothing other than a main method and the code you provide. If you cannot make such an example, at minimum you should provide how you are testing it.
If you do all of that and still have the issue, I think it will either be obvious to you, or the people reading your question here will have a much easier time answering it for you.
Related
I am newbie learning selenium and wrote below java code. I am trying to run a for loop that is supposed to load the site 20 times. Right now it does loop in sequential order and I want that to be run in parallel.
public class lenders {
//ExtentReports logger = ExtentReports.get(lenders.class);
public static void main(String[] args) throws InterruptedException {
for (int i=0; i<20; i++) {
FirefoxDriver driver= new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.SECONDS);
try {
driver.get("https://www.google.com");
} catch (TimeoutException e) {
driver.quit();
}
}
Towards the end I want 20 browsers to be open and loading the site and all of them getting killed.
If you are on Java-8 you can run a parallel for loop using aparallelStream
IntStream.range(0,20).parallel().forEach(i->{
... do something here
});
In general and at a high level, trying to run code in parallel within java means that you are trying to run multi-threaded code (more than one thread executing at one time).
As individuals have been saying in comments, one must therefore give a warning with my answer. Multi-threading in itself is a complicated topic and one must enter this territory with caution as there can be many issues/topics regarding "thread safety" and even if this is the way you "should" approach the "business request".
In any case, if you really want to create something multi-threaded then I would direct you to a few technical items to get you STARTED on the topic training (and your own further research): You could create another class that implements the Callable interface. It will then have to have the "call" method by nature of implementing that interface. In this class and in the "call" method you would put the actual logic that you want to happen in parallel. In your case, all of the driver, etc.
Then in your parent class (the one you put code from above), you can use a FixedThreadPool and an associated ExecutorService that accepts this callable class. It will essentially run the "call" method in a separate thread so that your for loop can continue onwards at the same time that the logic in the "call" method is executed. It will go the second time around and create another thread, etc. You can manage how many threads are created using your thread pool. You can use different kind of thread pools and services, etc. Again, this is a really BIG topic and field. I am just trying to get your nose in a direction for you to start researching it further.
People might not like my answer because they think you should use completely different technologies other than using Selenium in this manner, etc. I totally understand that point of view and don't disagree with those alternate answers. However, your question was "how to get this running at the same time" and I have tried to give you the building block answer. I hope that helps! Let me know if you need some links to tutorials or anything, but google "ExecutorService" "Thread Pool" and "Callable" (or combinations of them) with the word java and tutorial should get you a variety of answers on the topic.
I hope that helps!
I have a scenario in which I am running unreliable code in java (the scenario is not unlike this). I am providing the framework classes, and the intent is for the third party to overwrite a base class method called doWork(). However, if the client doWork() enters a funked state (such as an infinite loop), I need to be able to terminate the worker.
Most of the solutions (I've found this example and this example) revolve around a loop check for a volatile boolean:
while (keepRunning) {
//some code
}
or checking the interrupted status:
while (isInterrupted()) {
//some code
}
However, neither of these solutions deal with the the following in the '//some code' section:
for (int i = 0; i < 10; i++) {
i = i - 1;
}
I understand the reasons thread.stop() was depreciated, and obviously, running faulty code isn't desirable, though my situation forces me to run code I can't verify myself. But I find it hard to believe Java doesn't have some mechanism for handling threads which get into an unacceptable state. So, I have two questions:
Is it possible to launch a Thread or Runnable in Java which can be reliably killed? Or does Java require cooperative multithreading to the point where a thread can effectively hose the system?
If not, what steps can be taken to pass live objects such that the code can be run in a Process instead (such as passing active network connections) where I can actually kill it.?
If you really don't want to (or probably cannot due to requirement of passing network connections) spawn new processes, you can try to instrument code of this 'plugin' when you load it's class. I mean change it's bytecode so it will include static calls to some utility method (eg ClientMentalHealthChecker.isInterrupted()). It's actually not that hard to do. Here you can find some tools that might help: https://java-source.net/open-source/bytecode-libraries. It won't be bullet proof because there are other ways of blocking execution. Also keep in mind that clients code can catch InterruptedExceptions.
Sometimes when I examine a code I didn’t write, I launch eclipse in debug mode and use figures to understand a program. For example, if they are n items retrieved from the DB, it can be interesting to know that there’re n processed items in a service, etc.
When loops are used, things get more complicated: if we’re in a “while” loop, the number of execution is not defined and if there are alternatives, the flow of execution can greatly change.
For this purpose, I sometimes set a breakpoint in a portion of code and count how many times we reach it.
Of course, it’s not very convenient and I wonder if there is a way to count the number of breakpoint hits. I know that Eclipse can suspend execution after a fixed number of hits but I just want Eclipse to count them in a normal flow of execution.
I’d be glad to hear your opinions about it.
Thanks!
You can add a condition into your breakpoint. The simplest one could look something like this:
System.err.println("Passing checkpoint");
return false;
You can also extend it by calling your own static class:
org.foo.StaticCounter.COUNTER++;
System.err.println("Passing checkpoint " + org.foo.StaticCounter.COUNTER);
return false;
As an alternative to counting breakpoints, you could use a profiling tool, such as the one here.
So I have this Java piece of code where I need to do some work on a bunch of items. I decided to parallelize this to get some extra boost and I though to use a ThreadPoolExecutor. The problem is that the work I need to do can throw an exception...
Now I would like to shutdown the entire job to stop as soon as an error is encountered and report it back so I can handle it. Looking online, I found that the normal way this should be done is via ExecutorCompletionService and analyzing the Future results. However, this won't let me shut everything down when the first error comes by, as there is no way to loop over based on which task finishes first...
So I did something that I thought was rather hacky and I'm curious if there is a better way to handle this. What I did was:
1) Have each Runnable that I will execute have a field for the Throwable that it might execute.
2) Override the TPE's "afterExecute" method and check if any checked exception got thrown (which gets recorded in the Runnable) or any unchecked one gets thrown (which should be reported in the second parameter of this method). If any did, then I issue a shutdownNow() on the TPE.
Again, this seems a bit hacky and I am wondering if there is something I am missing. Thanks in advance!
Look at ExecutorService.invokeAny:
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.
It looks it does the exact same thing you are trying to do... if I understood your problem correctly.
However for cancel to do anything, you have to make your Callable tasks interrupt aware. But that applies no matter how you try to cancel your tasks.
EDIT:
This is not what you need; I misread the javadoc. Here's another solution: you could put all your Future's in a list and then have a semi-busy while loop where you check periodically on each futureList.get(i).get(100, TimeUnits.MILLISECONDS) and you can catch an exception and act accordingly. However, this no more "elegant" than your solution. It seems that afterExecute was made to do what you want anyway.
I'm working on a multithreaded program in Java that uses a shared array to pass data between threads. It's being developed in Netbeans 6.7.1.
One of the threads only seems to work when a breakpoint is placed in it, it doesnt matter where it is.
Running in debug mode with no breakpoints acts the same as running in release - the expected output never arrives.
I can't tell where the problem occurs, as the moment a breakpoint is added and I press continue, it works as expected.
How can I narrow down where/why this problem occurs?
Example code:
result = utils.isBufferFull(AudioDuplex.voiceArray);
if(result == true) {
System.out.println("Taking copy");
voiceArray = AudioDuplex.voiceArray;//.clone();
utils.clearBuffer(AudioDuplex.voiceArray);
}
If a breakpoint is placed on line 2, it is never hit.
A breakpoint on line 3 will be hit, and the expected output will arrive.
It's impossible to tell exactly what's wrong without a lengthier code sample, but in my experience, this kind of behavior is typical of unrecognized producer-consumer problems (see http://en.wikipedia.org/wiki/Producer-consumer_problem).
Basically, what's probably happening is that your producer thread does not have the data available when the consumer thread is requesting it. The basic solution is to keep a semaphore (there is a Sempahore class in java afaik). The producer would post when it has the data, the consumer would wait until the producer posts.
What you're seeing with the break point is you stopping the consumer thread for a long enough period that the producer can offer something. When you don't break, the consumer runs normally, and exits before the producer has anything.
Write the values of the involved variables to a log file, the console or add them to an array and print them as soon as you get the error.
Your problem is probably a runtime issue (a second thread updates an involved variable). Since breakpoints only stop the active thread, the second thread gets its work done so the code works.