I'm doing some java programming in Netbeans 7.3 and I have written a program that contains a complex while loop. It reads a file in, does some calculations, then prints an output file with some changes.
Something goes slightly wrong at the point where the while loop goes through the 158th line of the text (158th cycle of the while loop). Nothing appears to be wrong with the file itself at this point.
Am I being stupid when putting a breakpoint on the while loop and continuously clicking "Step Out" 158 times to see what's going on? Is there an easier way to do this with java? Like running the loop until a variable reaches a certain value?
adding debugcode like
if (iterationCount == 158) {
int dummy = 13; // <= put breakpoint here
}
is a practical alternative to "conditional breakpoints".
Related
I've been scratching my head at this for hours now, but I can't seem to figure this one out.
I'm writing a program that has a constant loop going in a Thread, which occasionally sends back data to another part of the program using an Arraylist.
I only want to send this data back after I have gathered 11 items in my arraylist. So I used this code:
//The rest of the loop in which i gather the values for key and velocity.
notenbuffer.add(new Noot(key,velocity));
if (notenbuffer.size() > 10){
System.out.println("Notenbuffer > 10, verstuur data");
if (notenbuffer.isEmpty()){
System.out.println("buffer is empty!");
}
else {
usbRead.writeNotes(notenbuffer);
System.out.println("emptied the buffer!");
notenbuffer.clear();
}
}
Now for some weird reason the program never empties the Arraylist, and just keeps on adding items to it. I've checked and it does in fact reach the usbRead.writeNotes(notenbuffer) part because this function gets called correctly. When I use the debugger it simply skips to the beginning of the loop after this function was called.
Is there a way in which I can empty an Arraylist once it reaches a certain size?
Edit: I made a logic error by writing if (notenbuffer.isEmpty()) this will always be false because I am already in an if statement which requires this to be false.
Did you put your second if inside your first by accident? (The missing indentation seems to suggest so). Having if
(notenbuffer.isEmpty()) inside the if (notenbuffer.size() > 10) block
makes no sense at all logically. After all if your List size is > 10
then the list is obviously not empty. So if (notenbuffer.isEmpty())
can never be true at all. – OH GOD SPIDERS 15 mins ago
This was indeed the problem. Removing this exposed an NoClassDefFoundError that needed resolving.
Hey guys, i have this while loop for variable 'i' and i have created a board[][] which is 2x2 (so sizeX for the board is 2 in this example). The problem is i can't work out why it isn't leaving the while loop if it goes through one of the 'if' statements starting with 'i=1' and then it then sets 'i=i+1' (=2) but doesn't leave the while statement and tries to see what board[2][x] is equal to when obviously that is out of the bounds of the board. Sorry for confusing explanation i hope you understand...
I am assuming that you are new to programming because you are using BlueJ.
When your second loop is running, I'm guessing that your line x=x is keeping x within range and hence the loop never exits.
One good thing to help is to use a debugger or print statements to show what the values of x and i are at each stage. That will quickly let you know what is going wrong.
I have noticed that when I debug with conditional breakpoints, execution is dramatically slowed down. I have known this for a while, and would now like to understand why. What exactly is happening that causes execution to be so slow? I know that a conditional is being added, but if I add the conditional myself, I don't slow down execution.
For example, lets say we have the following code. And lets say we add a conditional breakpoint a=i. Lets just set the conditional to i==10000.
public class Main {
public static void main(String[] args) {
int a = 0;
for (int i = 0; i<100000; i++) {
a = i; //put breakpoint here (if i == 10000)
}
System.out.println("Done! a=" + a);
}
}
Now lets instead, write the conditional ourselves.
public class Main {
public static void main(String[] args) {
int a = 0;
for (int i = 0; i<100000; i++) {
if (i == 10000)
a = i; //put a NON-conditional breakpoint here
else a = i;
}
System.out.println("Done! a=" + a);
}
}
Why is the run time of both of these so dramatically different? Why is the first one so much slower?
In case your wondering, I am using Oracle-JDK-8 on Linux (Ubuntu).
I get the same results with Eclipse and IntelliJ.
Experiment results
I ran the first case on multiple IDE's to see if there is a difference. Here are the results
IntelliJ:
~9 seconds to hit breakpoint
~90 seconds to hit completion (including initial 9 seconds)
Eclipse:
~9 seconds to hit breakpoint
~90 seconds to hit completion (including initial 9 seconds)
Netbeans:
~ 12 seconds to hit breakpoint
~ 190 seconds to hit completion (including initial 12 seconds)
So IntelliJ and Eclipse are about the same, but Netbeans is much much slower.
The second example runs almost instantaneously on all IDE's, so I did not do an experiment. (But I did run it all all three to see if any of them had a delay, none of them did.)
I have not implemented IDE, debugger or JVM, so I can not be sure that the things are going exactly as I will explain here.
But. When code is running with debugger the JVM interprets the code until it meets breakpoint. Then it stops and calls debugger (IDE).
JVM's do not support conditional breakpoints, so IDE's use a "hack" to accomplish this feature. The IDE simply adds a normal breakpoint. Every time a breakpoint is hit, the IDE evaluates the expression itself before alerting the user, if the evaluation is false, it sends the "continue" command.
Now examine your examples. In second example JVM performs such call only once. In first example this is done 100000 times. Each time JVM calls debugger and waits until it interprets the condition and sends to JVM command "continue" (exactly as you can do manually when you are debugging your code). Obviously 100000>1, so this process takes time.
EDIT: the next 2 paragraphs were written as an not proven assumption only. The experiments of OP showed that they are wrong. I however do not want to remove them completely: let's interpret this as a theoretical thinking and improvement proposal for Eclipse team.
Concerning IntelliJ vs Eclipse. Again, this is assumption only. I saw that IntelliJ works much slower with conditional breakpoints. I know also that conditional breakpoints in IntelliJ do not support some elements of java programming language (e.g. anonymous inner classes). I can conclude that IntelliJ probably compiles the code that you write as a condition of your brekepoint using language other than java (for example groovy or something). This probably causes additional performance degradation.
I also know that eclipse does not use standard javac compiler but its own compiler that has a lot of cool features. I can assume that probably conditional breakpoints in eclipase are compiled as a part of your code, i.e. actually compiler automatically creates code like your example number 2. If this is correct such code will run almost as quickly as code that contains manually written if statement.
Conditional breakpoints rely on the interpretative (!) evaluation of the condition, to be done whenever the location of the breakpoint is hit.
Hitting a breakpoint is fast: the sequential flow of execution is interrupted, e.g., by replacing the instruction at that location by some code that triggers an interrupt. But the evaluation of the condition must fetch the values of the variables from memory and compute the result, which isn't done the same way the expression would evaluate in compiled code. A considerable slow-down is to be expected.
While a compiled expression results in machine instructions (in Java, at least after JIT compilation), an interpreted expression is based on an abstract syntax tree (a data structure), such as Equals( Variable( "i" ), Literal( 10000 )) and code that descends on that data structure, fetches values ("i") and computes operations ("==").
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.
Please Note: I am not "looking for teh codez" - just ideas for algorithms to solve this problem.
This IS a homework assignment. I thought I was in the home stretch, about to finish it out, but the last part has absolutely stumped me. Never have I been stuck like this. It has to do with threading in Java.
The Driver class reads a file, the first line indicates the number of threads, second line is a space delimited list of file names for each thread to read from. Each thread is numbered (0 - N), N being the total number of files. Each thread reads the file specified, and outputs to a file named t#_out.txt where # is the threads index.
After all of this is done the Driver thread must:
After all threads finish execution, the program Driver.java opens all
output files t#_out.txt, reads a line from each file, and writes the
line to an output file out.txt.
Example of the out.txt:
MyThread[0]: Line[1]: Something there is that doesn't love a wall,
MyThread[1]: Line[1]: HOG Butcher for the World,
MyThread[2]: Line[1]: I think that I shall never see
MyThread[0]: Line[2]: That sends the frozen-ground-swell under it,
MyThread[1]: Line[2]: Tool Maker, Stacker of Wheat,
MyThread[2]: Line[2]: A poem lovely as a tree.
MyThread[0]: Line[3]: And spills the upper boulders in the sun,
MyThread[1]: Line[3]: Player with Railroads and the Nation's Freight Handler;
MyThread[2]: Line[3]: A tree whose hungry mouth is prest
My problem is: What kind of loop structure could I setup to do this? Read a line from t1_out.txt, write to out.txt, read line from t2_out.txt, write to out.txt, read line from tN_out.txt, write to out.txt? How do I know when one file has reached the end?
Ideas:
Use a while(!done) loop to continue looping until each scanner is done. Keep track of an array of booleans indicating whether or not the Scanner is done reading its file. The Scanners would be in an array as well. The problem with this is how do I tell when ALL are done, to finish my infinite loop? In each iteration see if booleans[i] is done and if not then done = false? No good.
Just read every files lines into its own String[] array. Then figure out a loop to alternate the writing to the out.txt. Problem with this is what happens when I hit array index out of bounds? Also this is not in the specs, it says to read a line, and write a line.
EDIT: The solution was to create an allFilesReachedEOF() method which has an initial boolean of true. It then loops through each one, and if ANY have another line to read, sets the return condition to false. This was my while loops condition: while (!allFilesReachedEOF()).
My problem was that I was trying to control the loop from within the loop. So if a file had another line it would continue, but if ANY file EOF'd, the loop would stop.
Thanks for the help!
You could do a while with a condition that not all the files have reached EOF. Then you iterate through all the files, and for those that haven't reached EOF, you read the next line and write it to your output file. As you go, you update your condition variable for the "while" loop.
Is this what you're looking to do?
It sounds like you could use a Queue to achieve this. Add each t#_out.txt's input to the Queue then implement a loop in which you read a line from the polled input and write it to your output. As long as the read line isn't EOF, re-add the input to the Queue. When the Queue is empty, break out from the loop.
Also I recommend a BufferedWriter for the output, which you flush() at the end so that the actual writing only occurs once.
Here are the main points:
Create a class that implements Runnable whose run() method does what you need one thread to do. It'll likely need fields for threadNumber and filename. The run method should make sure to close() the output streams of the output files
For each thread you need to create, instantiate one of your class (giving it the filename (and other) data it needs) and pass it into the constructor of Thread. Keep a reference to the Thread objects
Call the start() method on all the threads
Call the join() method on all the threads (join waits for the thread to finish)
Do your final Driver task of opening the output files
This can be done by using a do - while "exit condition" loop and an inner for loop for iterating through the output files. Set the exit condition to true before the start of the for loop, and reset it within the for loop if you get at least a line from any of the files.
Files that have reached eof will continue to be read, but will not return any lines. You can choose to print blank lines for these or just skip them.