Loop for executing multiple methods at the same time? - java

Is there a loop in java that executes multiple methods (or multiple actions) at the same time?
Example:
replace(line1, line2);
replace(line3, line4);
replace(line5, line6);
replace(line7, line8);
replace(line9, line10);
Loop through a file and replace the strings - they aren't in order.

Regarding this code in your question's edit:
replace(line1, line2);
replace(line3, line4);
replace(line5, line6);
replace(line7, line8);
replace(line9, line10);
You simply need one method, replace, called by a for or while loop (depending if you know in advance how many times you'll loop). If this doesn't solve your problem, then (again), please ask a better and clearer question.
There's no need to use threads to do these all at the same time. You state that "I only need to do this once", perhaps, but you need to call replace at least 5 times in this example, so actually a loop that calls replace 5 times passing in different parameters would work nicely. If you had an array of pairs of lines, you could loop through the array with a for loop calling replace as you loop. Again there's no need for a "do together" here but rather a "do in order".
But again you seem to be withholding critical information for unknown reasons. Again, I urge you to study this link: How To Ask Questions The Smart Way

Related

do recopy a string to a new string have more performance impact that recopy an array?

I am new to Java and I do not know which is better
So I got a very strange homework question asked us to split the csv into 2d-array but their're 2 rules
1. you can't use ArrayList
2. You can't import other java class other than file.io
So this make it very challenging since we can't tell the array size yet. So when I readline, I decided to store it in a string first
after finished all the readline, only then I process the ","
So I wonder, do recopy a string to a string to add text have more performance impact or recopy previous array to new array is inefficient?
This is just an example what the csv may look like
1, 2, 3
4, 5, 6
stringRecopy &= reader.readLine()
vs
int[][] arrayRecopy = (copy previous array with new reader.readLine().split(",") here)
I think you are asking the wrong question.
Unless the requirements for your homework assignment explicitly say that performance is the most important criteria, performance is a red herring.
In the real world, the important things about most programs1 are:
They do what they are supposed to do; i.e. functionally complete, no bugs.
They are maintainable; i.e. someone else can read and understand the code, and fix or modify it.
They are implemented efficiently ... in terms of programmer time.
They are fast enough for their intended purpose.
"As fast as possible" is rarely a criteria. Not least because achieving "as fast as possible" usually involves ignoring criteria 1 through 3 above.
So how does that apply here?
Well, what you are doing is worrying about the efficiency of a program that doesn't need to be efficient. Indeed, if I was marking this assignment2, I would pay a lot more attention to 1 and 2 than to performance. A program was written to be fast at the expense of maintainability would be down-marked!
So how would I implement it?
Well, the professional way would be to use ArrayList. But that is not an option3.
So that leaves two approaches:
Read (or process) the input twice. In the first pass work out how big the 2D array needs to be (by counting lines and the max number of commas in a line). Then create the array and do a second pass to populate the array.
Implement the code to grow the arrays as required.
Your criteria for deciding which approach to choose should be based on which one you think is easier >>for you<< to write, and for someone else to understand. Performance should be unimportant.
Finally, I don't think we can answer your actual question without seeing completed versions that implement both of your approaches. It very much depends on how you code them.
But once you have coded them and tested and debugged them, it should not be difficult to measure them. See How do I write a correct micro-benchmark in Java? for advice on how to do it in a way that will give you valid answers.
1 - There are notable exceptions to this.
2 - Note that I won't be marking your assignment, so you would be advised to think about what your teachers are actually looking for. If you are in doubt, you could ask them.
3 - This is not a criticism of the homework. I fully understand why they have made this restriction. This exercise is about learning to program, not (so-called) "best practice" programming in the real world.

IntelliJ debugging - Watch for any variable containing a specific value

Is it possible to put out a global watch or breakpoint, on no specific variable or line of code, with the aim of identifying the first instance of a value?
I'm debugging on an old java6 web app that does a million calculations between multiple databases and dozens of classes with thousands of lines of code each. I'm not exactly sure which of these dozens of classes are being called within this project containing hundreds of classes.
Let's say I'm looking for where "the dog runs" appears in the flow of a calculation: Is it possible to listen for the first appearance of that string with the intention of finding what variable will contain the value?
I do not think that is possible to monitor where a value comes into existence as i think you have asked.
However, you can set "field watchpoints" which are basically expressions like break when x = "the dog runs". When i have used these before the program will run very very slowly.
Refer here for details of how to set it: Intellij breakpoints.
Another technique is to start near the top of where you think a value is being set to what you want. Step over each method until you see where the value set to what you are looking for. Then repeat the process inside the method that you saw it change (i.e. this time step into the method where the value changed).
Within this "second level method", you will probably see another call that sets the value you are looking for. So repeat the process again until you find a system call that sets the value (e.g. a read from a database or a regex match etc).
It sounds tedious, but it is a "divide and conquer" method of the form that eliminates a huge chunk of code that doesn't set the value you are looking for into the one method call that does. Then you divide and conquer the inner workings of that method. In practice, it doesn't take long before you narrow it down.

Too many break statements have the tendency to destructure your code

while reading "Java complete reference seventh edition" in page 100.
I read this statement "However, be careful. Too many break statements have the tendency to destructure your code"
What I don't understand how can break statement change or deconstructed in my code?
Is that in java only or in all programming languages?
Is that something linked to byte-code?
Thanx so much, please do not misunderstand me :)
Too many break statements have the tendency to destructure your code
I believe that the author means that it is more difficult to follow the execution paths in your code. This is because break jumps to a line of your code that potentially can be far away from the line with the break.
The author uses the word de-structure your code. Its just an expression. what he actually meant by that is:
Imagine you writing five loops one inside another having break statements for all the loops. If the loop gets bigger and bigger, there are high chances of losing the execution path as a developer i.e. which loop is being executed and from which loop the control has broken out of.
Imagine the chaos it creates if you have more loops having break for each loop/more break statements for a few loops. The only thing that catches your eye is the break statement .
However, be careful. Too many break statements have the tendency to destructure your code.
This doesn't mean that if you have a switch statement to compare over 100 unique values, then it will de-structure your code. Because, in this case, that's the only need.
But suppose, you are using too many loops, could be anything, for-loop, while-loop, do-while-loop or even if-else conditions, excessively using breakstatement will come out with too many permutations and combinations of execution path which we at development phase might not see. And then, can cause a big trouble at real time execution with multiple values or multiple types of values which may trigger a new, unexplored path of execution. (I mean, those paths, which we were not intended to create.)
So, the author says better to avoid too many break statements. Not all.

How to iterate over an array list in a thread safe manner (Java)

I have an array list that I am using in my multi-threaded application, and I want a way to somehow be able to iterate through the array while not causing any exceptions to be thrown when I add a element to the list as I am iterating. Is there a way to stop the array list from being modified while I iterate through it?
Edit:
I now realize that my question was very poorly submitted, and the down votes are deserved. This is an attempt to fix my question.
What I want to do is have some way to 'block' the list before I iterate through it so that I don't get a concurrent modification exception. The issue is that the iterating will take quite a bit of processor time to complete, because the list will be very large, and the action I wish to carry out on each element will take a fair amount of time. This is an issue if I use synchronized methods, because the add method will block for a large amount of time and decrease application performance. So what I am trying to do is create a class that imitates an array list, except that when it is 'blocked', and a method tries to modify it, it will store that request, and when the list is 'unblocked' it will perform all the requests in a separate thread. The issue is that when I try to implement this strategy, I have to store the requests in some sort of list, and run into the same problems I do before, with having to block the ability to add to the request list while the request thread is iterating over the requests. I'm at a loss for how to implement this solution, or even if it is the correct one. if anyone could help me that would be much appreciated.
Your options are either to work with synchronization or use implementation provided in package java.util.concurrent. You also need to read up on the issue. you are asking a very fundamental and classical question and there is a LOT of info on this issue.But here are your basic options:
Use syncronization - veru expensive performance wise but is absolutely bullet-proof. read up in synchronizedterm or read up on Lock interface and its implementations. Also see about Semaphore class. Note that this option would create a very serious bottle neck in your performance
As one of the comments said use CopyOnWriteArrayList class. Also has some draw backs but in majority of cases is a better option then full synchronization.
When choosing between the 2 options consider the following points: while synchranization is a bullet-proof solution if done right, it is a very tidious work that demands a lot of testing which is not trivial. So this is already a big draw back. Plus in majority of cases reads outnumber writes or Array size is small enough (say up to few hundreds elements) where copy on write is acceptable. So it is my guess that majority of cases CopyOnWriteArrayList would be preferable. The point is that there is no clear cut answer when choosing between the two options above. A programmer needs to look at the circumstances and choose the option that fits his/her case better

Java - Creating a string by selecting certain numbers from within a text file

I have a .txt file that has numbers 1-31 in it called numbers. I've set up a scanner like this:
cardCreator = new Scanner (new File ("numbers"));
After this, I'm kind of confused on which methods I could use.
I want to set up a conditional statement that will go through numbers, evaluate each line (or numbers 1-31), and include each number a string called numbersonCard, if they meet certain criteria.
I can kind of picture how this would work (maybe using hasNext(), or nextLine() or something), but I'm still a little overwhelmed by the API...
Any suggestions as to which methods I might use?
Computer science is all about decomposition. Break your problem up into smaller ones.
First things first: can you read that file and echo it back?
Next, can you break each line into its number pieces?
Then, can you process each number piece as you wish?
You'll make faster progress if you can break the problem down.
I think Java Almanac is one of the best sources of example snippets around. Maybe it can help you with some of the basics.
Building upon duffymo's excellent advice, you might want to break your problem down into high-level pseudocode. The great thing about this is, you can actually write these steps as comments in your code, and then solve each bit as a separate problem. Better still, if you break down the problem right, you can actually place each piece into a separate method.
For example:
// Open the file
// Read in all the numbers
// For each number, does it meet our criteria?
// If so, add it to the list
Now you can address each part of the problem in a somewhat isolated fashion. Furthermore, you can start to see that you might break this down into methods which can open the file (and deal with any errors thrown by the API), read in all the numbers from the file, determine whether a given number meets your criteria, etc. A little clever method naming, and your code will literally read like the pseudocode, making it more maintainable in the future.
To give a little more specific help than the excellent answers duffymo and Rob have given, your instincts are right. You probably want something like this:
cardCreator = new Scanner (new File ("numbers"));
while (cardCreator.hasNextInt()) {
int number = cardCreator.nextInt();
// do something with number
}
cardCreator.close();
hasNext() and nextInt() will save you from getting a String from the Scanner and having to parse it yourself. I'm not sure if Scanner's default delimiter will interpret a Windows end-of-line CRLF to be one or two delimiters, though.

Categories

Resources