Foreach loop can cause thread concurrency? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've heard that you shouldn't use foreach loop where you can avoid it because it can cause thread concurrency, what does it mean thread concurrency, and is it true ?

So when should you use the for-each loop?
Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel.
These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.
Emphasis mine.
Unless you clear up what you mean with exactly, this would indicate that you're wrong.

Using a for each loop when altering a collection can trigger it to incorrectly detect a concurrent modification which looks like it has been modified by another thread when in fact it has been modified by the same thread.
"for each" doesn't have anything to do with concurrency. You can find the ConcurrentModicationException a number of way, one is to use Iterator.remove().

Related

Should a traditional while loop like this change to streams in Java and how? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 months ago.
Improve this question
Should I focus on trying to change every loop in my project to new Streams ? Should the loop below change to streams and how?
while(characterAfterEncryption > 122) {
characterAfterEncryption -= 26;
}
Trying to avoid using Traditional loops in Java 8.
Unable to find a way how to do it using Streams?
Use streams if and only if the stream-based code is easier to understand than the loop-based code. Streams and loops are both valid Java constructs, and it's the developer's responsibility to decide which one to use.
Streams are designed to support cases where you want to operate on multiple input values, e.g. from lists or sets or other series of data. And this does not apply to your snippet: you have a single input value. So, while it might be possible to create some piece of code that replicates the iterative algorithm using the streams API, the result will surely be very hard to read.
So, forget about "Trying to avoid using Traditional loops in Java 8". There are cases where this is a good idea, but also cases where the traditional loop is exactly the right thing to do. And if you ever tried to debug a streams expression, you'll be even more hesitant to use the streams API.

In Java, does a check of a collection for emptiness before applying a stream functoin chain on it improve performance? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
how does the Stream API perform on empty collections? Does it make sense to check for emptiness before executing a stream command chain on a collection?
For example, is the total runtime better for the first or the second example block?
List a = new ArrayList();
return a.stream.anyMatch("OK"::equals).orElse(null);
vs
List a = new ArrayList();
if(a.isEmpty()) {
return null;
} else {
return a.stream.anyMatch("OK"::equals).orElse(null);
}
I am aware of that the first option is more beautiful, but this is a question about performance.
Does it make sense to check for emptiness before executing a stream command chain on a collection?
It might make from a performance point of view, as it definitely prevents an empty stream spending (a bit) of CPU time doing nothing.
But from a conceptual point of view: not a good idea. The whole point of streams is that you do not care about the number of entries. Streams are (to a large degree) a way to express logic in "functional programming" ways. An empty stream comes back with an "empty" result. That is how they work and should be used.
If you add a distinct check upfront, then your code will also need to provide that empty result for example.
Regarding performance, the thing that you really want to be cautious about: having a lot of stream operations that run very often on small numbers of elements.

Java call performance vs search performance [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Currently my program is filled with many ugly references that often make field or method access look like this: weakReference1.get().weakReference2.get().field1.getSomeCustomObject().field2. I want to move to shorter and faster strong references like field1.field2. But my program design is such that I will also have to go for an ArrayList element-by-element search (in a for-loop) instead of accessing a WeakHashMap by get() method.
Thus, I'd like to understand, can moving to simpler references compensate for rejecting HashMap performance wise. Herewith I presume that WeakHashMap.get() is much faster than a loop-search of ArrayList.
Can someone, please, give me a rough estimate? Or maybe there's even an appropriate comparison table like this one. I'd appreciate that.
Thank you.
Currently my program is filled with many ugly references that often make field or method access look like this:
weakReference1.get().weakReference2.get().field1.getSomeCustomObject().field2
Given that the objects involved are not Data Transfer Objects
this is a violation of the law of Demeter aka Don't talk to Strangers / Tell, don't ask!
Following this LoD principle you should move the operations working with the data in field2 to a new method in the class SomeCustomObject.

Get out of a foreach [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My C++ teacher once told me that if I have to use a break to get out of a loop I didn't think enough about the loop condition.
So did she (very good teacher btw) just fail to mention that foreach loops are an exception to this rule (which I have generally found to be true) or is there indeed a way to get out of a foreach loop without using a break?
I am asking in general, but most interesting for me would be for Java or PHP.
Edit:
In case I haven't made this clear, I am wondering if there is a way to get out of a foreach-loop without using a break. Not sure what this whole commotion is about, what's wrong with that question?
foreach loops don't have any exit condition except for the implicit "when there are no more items to iterate over", so it is not possible to break out of them early while avoiding break without using some sort of a terrible hack (e.g. throwing exception, modifying the iterated collection, setting a boolean flag dontContinue and checking it in each iteration, etc.).
For ordinary loops, there indeed always is an obvious way to avoid using break (stop the current iteration using continue or if, and put the early exit condition into loop's condition), however whether such approach leads to a more readable code than using break is disputable.
In some cases, the reason for you to want to break out of a loop early is because you finished whatever task needed to be done, or found the needed item. In such cases, consider putting the particular functionality into a separate method and using return instead of break.

Instantiating an object to make code faster [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a Utils class that loads a large list of Strings (a static variable) and defines a function that uses this list.
I use this function in another class Solution. Currently, I am calling Utils.my_function every time I use it (in a big for loop, so it is called thousands times). Would it be faster if I instantiate a Utils in Solution? (would the list of words defined in Utils be defined only one time?)
a large list of Strings (a static variable)
...
would the list of words defined in Utils be defined only one time?
By definition, a static variable is loaded only once. So it's already the fastest you can do.
EDIT : the devs who code Java are smart. It's very likely that the JVM can detect your array is accessed very often, and will optimise its operations, whether it is a static or instance variable. However I cannot give you more information than this, and maybe some Java experts can give you a more accurate answer.
Well, as already pointed out that static is only called once anyway. Another thing you can do is batch processing -- http://java.dzone.com/articles/batch-processing-best
Instead of looping by each line -- call a set of lines at a time then perform your functions, then move to the next set, etc. You would need to profile your app to see how many lines would yield a good response for the app.

Categories

Resources