Is this code threadsafe, using Java 8 Lambdas - stream.forEachCan a forEach lambda result in a race condition?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How does the Java 'for each' loop work?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How to avoid Java code in JSP files?How do I convert a String to an int in Java?Creating a memory leak with JavaWhat is a lambda expression in C++11?

What actually is the vector of angular momentum?

SQL Server Management Studio SSMS 18.0 General Availability release (GA) install fails

Is induction neccessary for proving that every injective mapping of a finite set into itself is a mapping onto itself?

Pressure to defend the relevance of one's area of mathematics

FindInstance and cosine system of equations

Is there a legal ground for stripping the UK of its UN Veto if Scotland and/or N.Ireland split from the UK?

Should I replace my bicycle tires if they have not been inflated in multiple years

In Avengers 1, why does Thanos need Loki?

If prion is a protein. Why is it not disassembled by the digestive system?

What was the state of the German rail system in 1944?

Is a lifestealing melee cantrip, in the form of booming blade, unbalanced?

Did we get closer to another plane than we were supposed to, or was the pilot just protecting our delicate sensibilities?

How could a planet have most of its water in the atmosphere?

What is the minimal installation possible in order to run a .jar Java file?

In a vacuum triode, what prevents the grid from acting as another anode?

What are the spoon bit of a spoon and fork bit of a fork called?

If Earth is tilted, why is Polaris always above the same spot?

Selecting a secure PIN for building access

My ID is expired, can I fly to the Bahamas with my passport?

Unknowingly ran an infinite loop in terminal

Why was the battle set up *outside* Winterfell?

Was Unix ever a single-user OS?

Should my Json storage handle exceptions?

What word means "to make something obsolete"?



Is this code threadsafe, using Java 8 Lambdas - stream.forEach


Can a forEach lambda result in a race condition?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How does the Java 'for each' loop work?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How to avoid Java code in JSP files?How do I convert a String to an int in Java?Creating a memory leak with JavaWhat is a lambda expression in C++11?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








3















Assume that I have a list of book elements: List<Book> libraryBooks and the following code:



List<BookAuthor> authors = new ArrayList<>();
libraryBooks.stream().forEach(e ->
authors.add(createAuthor(e));
);


I've looked around and found similar questions, (like here) but I'm not yet convinced. Because I've been reading a book on the subject and the book seems to indicate that the above could introduce race conditions if the stream was run in parallel - but I'm not using a parallel stream, so is the above subject to race conditions? Or is the book wrong/misleading?



Here's the excerpt from the book that I'm referring to:
enter image description here










share|improve this question
























  • "that the above could introduce race conditions if the stream was run in parallel" - It doesn't have to be a parallel stream for it to not be thread-safe. Any other thread could attempt to modify authors while you're adding elements to it inside the forEach.

    – Jacob G.
    Mar 22 at 21:06











  • I'm sure your book shows the correct, idiomatic way of doing what you want. Why not use that idiomatic way?

    – JB Nizet
    Mar 22 at 21:07











  • The above example that I posted is actually a very simple example, but I'm looking at some code in an existing application which actually does something more complex (ie, using a builder to create an object) and then adding that new object to the list, but same idea as the above example that i posted. I'm just wondering if that could cause race conditions?

    – Nena
    Mar 22 at 21:14






  • 1





    @Nena the good practice with streams is to write code that is parallelizable. In general, one should be able to replace stream() by parallelStream() and still have correct code. It's not the case with what you have there, since ArrayList is not thread-safe and would be modified from concurrent threads. That's what the book says: you should write parallel-ready code. If it's sequential, it doesn't have any race condition, since there is no race. But it's not parallel-ready, because it would have a race condition if it as made parallel.

    – JB Nizet
    Mar 22 at 21:30


















3















Assume that I have a list of book elements: List<Book> libraryBooks and the following code:



List<BookAuthor> authors = new ArrayList<>();
libraryBooks.stream().forEach(e ->
authors.add(createAuthor(e));
);


I've looked around and found similar questions, (like here) but I'm not yet convinced. Because I've been reading a book on the subject and the book seems to indicate that the above could introduce race conditions if the stream was run in parallel - but I'm not using a parallel stream, so is the above subject to race conditions? Or is the book wrong/misleading?



Here's the excerpt from the book that I'm referring to:
enter image description here










share|improve this question
























  • "that the above could introduce race conditions if the stream was run in parallel" - It doesn't have to be a parallel stream for it to not be thread-safe. Any other thread could attempt to modify authors while you're adding elements to it inside the forEach.

    – Jacob G.
    Mar 22 at 21:06











  • I'm sure your book shows the correct, idiomatic way of doing what you want. Why not use that idiomatic way?

    – JB Nizet
    Mar 22 at 21:07











  • The above example that I posted is actually a very simple example, but I'm looking at some code in an existing application which actually does something more complex (ie, using a builder to create an object) and then adding that new object to the list, but same idea as the above example that i posted. I'm just wondering if that could cause race conditions?

    – Nena
    Mar 22 at 21:14






  • 1





    @Nena the good practice with streams is to write code that is parallelizable. In general, one should be able to replace stream() by parallelStream() and still have correct code. It's not the case with what you have there, since ArrayList is not thread-safe and would be modified from concurrent threads. That's what the book says: you should write parallel-ready code. If it's sequential, it doesn't have any race condition, since there is no race. But it's not parallel-ready, because it would have a race condition if it as made parallel.

    – JB Nizet
    Mar 22 at 21:30














3












3








3








Assume that I have a list of book elements: List<Book> libraryBooks and the following code:



List<BookAuthor> authors = new ArrayList<>();
libraryBooks.stream().forEach(e ->
authors.add(createAuthor(e));
);


I've looked around and found similar questions, (like here) but I'm not yet convinced. Because I've been reading a book on the subject and the book seems to indicate that the above could introduce race conditions if the stream was run in parallel - but I'm not using a parallel stream, so is the above subject to race conditions? Or is the book wrong/misleading?



Here's the excerpt from the book that I'm referring to:
enter image description here










share|improve this question
















Assume that I have a list of book elements: List<Book> libraryBooks and the following code:



List<BookAuthor> authors = new ArrayList<>();
libraryBooks.stream().forEach(e ->
authors.add(createAuthor(e));
);


I've looked around and found similar questions, (like here) but I'm not yet convinced. Because I've been reading a book on the subject and the book seems to indicate that the above could introduce race conditions if the stream was run in parallel - but I'm not using a parallel stream, so is the above subject to race conditions? Or is the book wrong/misleading?



Here's the excerpt from the book that I'm referring to:
enter image description here







java lambda foreach race-condition






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 21:20







Nena

















asked Mar 22 at 21:03









NenaNena

1941221




1941221












  • "that the above could introduce race conditions if the stream was run in parallel" - It doesn't have to be a parallel stream for it to not be thread-safe. Any other thread could attempt to modify authors while you're adding elements to it inside the forEach.

    – Jacob G.
    Mar 22 at 21:06











  • I'm sure your book shows the correct, idiomatic way of doing what you want. Why not use that idiomatic way?

    – JB Nizet
    Mar 22 at 21:07











  • The above example that I posted is actually a very simple example, but I'm looking at some code in an existing application which actually does something more complex (ie, using a builder to create an object) and then adding that new object to the list, but same idea as the above example that i posted. I'm just wondering if that could cause race conditions?

    – Nena
    Mar 22 at 21:14






  • 1





    @Nena the good practice with streams is to write code that is parallelizable. In general, one should be able to replace stream() by parallelStream() and still have correct code. It's not the case with what you have there, since ArrayList is not thread-safe and would be modified from concurrent threads. That's what the book says: you should write parallel-ready code. If it's sequential, it doesn't have any race condition, since there is no race. But it's not parallel-ready, because it would have a race condition if it as made parallel.

    – JB Nizet
    Mar 22 at 21:30


















  • "that the above could introduce race conditions if the stream was run in parallel" - It doesn't have to be a parallel stream for it to not be thread-safe. Any other thread could attempt to modify authors while you're adding elements to it inside the forEach.

    – Jacob G.
    Mar 22 at 21:06











  • I'm sure your book shows the correct, idiomatic way of doing what you want. Why not use that idiomatic way?

    – JB Nizet
    Mar 22 at 21:07











  • The above example that I posted is actually a very simple example, but I'm looking at some code in an existing application which actually does something more complex (ie, using a builder to create an object) and then adding that new object to the list, but same idea as the above example that i posted. I'm just wondering if that could cause race conditions?

    – Nena
    Mar 22 at 21:14






  • 1





    @Nena the good practice with streams is to write code that is parallelizable. In general, one should be able to replace stream() by parallelStream() and still have correct code. It's not the case with what you have there, since ArrayList is not thread-safe and would be modified from concurrent threads. That's what the book says: you should write parallel-ready code. If it's sequential, it doesn't have any race condition, since there is no race. But it's not parallel-ready, because it would have a race condition if it as made parallel.

    – JB Nizet
    Mar 22 at 21:30

















"that the above could introduce race conditions if the stream was run in parallel" - It doesn't have to be a parallel stream for it to not be thread-safe. Any other thread could attempt to modify authors while you're adding elements to it inside the forEach.

– Jacob G.
Mar 22 at 21:06





"that the above could introduce race conditions if the stream was run in parallel" - It doesn't have to be a parallel stream for it to not be thread-safe. Any other thread could attempt to modify authors while you're adding elements to it inside the forEach.

– Jacob G.
Mar 22 at 21:06













I'm sure your book shows the correct, idiomatic way of doing what you want. Why not use that idiomatic way?

– JB Nizet
Mar 22 at 21:07





I'm sure your book shows the correct, idiomatic way of doing what you want. Why not use that idiomatic way?

– JB Nizet
Mar 22 at 21:07













The above example that I posted is actually a very simple example, but I'm looking at some code in an existing application which actually does something more complex (ie, using a builder to create an object) and then adding that new object to the list, but same idea as the above example that i posted. I'm just wondering if that could cause race conditions?

– Nena
Mar 22 at 21:14





The above example that I posted is actually a very simple example, but I'm looking at some code in an existing application which actually does something more complex (ie, using a builder to create an object) and then adding that new object to the list, but same idea as the above example that i posted. I'm just wondering if that could cause race conditions?

– Nena
Mar 22 at 21:14




1




1





@Nena the good practice with streams is to write code that is parallelizable. In general, one should be able to replace stream() by parallelStream() and still have correct code. It's not the case with what you have there, since ArrayList is not thread-safe and would be modified from concurrent threads. That's what the book says: you should write parallel-ready code. If it's sequential, it doesn't have any race condition, since there is no race. But it's not parallel-ready, because it would have a race condition if it as made parallel.

– JB Nizet
Mar 22 at 21:30






@Nena the good practice with streams is to write code that is parallelizable. In general, one should be able to replace stream() by parallelStream() and still have correct code. It's not the case with what you have there, since ArrayList is not thread-safe and would be modified from concurrent threads. That's what the book says: you should write parallel-ready code. If it's sequential, it doesn't have any race condition, since there is no race. But it's not parallel-ready, because it would have a race condition if it as made parallel.

– JB Nizet
Mar 22 at 21:30













1 Answer
1






active

oldest

votes


















0














When you need to create a new list of items by applying a function to each of the elements, then map is the function you should use. This is how you should write it:



List<BookAuthor> authors = libraryBooks.stream()
.map(e -> createAuthor(e))
.collect(Collectors.toList());





share|improve this answer


















  • 5





    Can you explain in what way this answers OP's question? I understand that this is the proper way to build a List with streams in general, but how does it answer the question of thread safety?

    – mypetlion
    Mar 22 at 21:12











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307740%2fis-this-code-threadsafe-using-java-8-lambdas-stream-foreach%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














When you need to create a new list of items by applying a function to each of the elements, then map is the function you should use. This is how you should write it:



List<BookAuthor> authors = libraryBooks.stream()
.map(e -> createAuthor(e))
.collect(Collectors.toList());





share|improve this answer


















  • 5





    Can you explain in what way this answers OP's question? I understand that this is the proper way to build a List with streams in general, but how does it answer the question of thread safety?

    – mypetlion
    Mar 22 at 21:12















0














When you need to create a new list of items by applying a function to each of the elements, then map is the function you should use. This is how you should write it:



List<BookAuthor> authors = libraryBooks.stream()
.map(e -> createAuthor(e))
.collect(Collectors.toList());





share|improve this answer


















  • 5





    Can you explain in what way this answers OP's question? I understand that this is the proper way to build a List with streams in general, but how does it answer the question of thread safety?

    – mypetlion
    Mar 22 at 21:12













0












0








0







When you need to create a new list of items by applying a function to each of the elements, then map is the function you should use. This is how you should write it:



List<BookAuthor> authors = libraryBooks.stream()
.map(e -> createAuthor(e))
.collect(Collectors.toList());





share|improve this answer













When you need to create a new list of items by applying a function to each of the elements, then map is the function you should use. This is how you should write it:



List<BookAuthor> authors = libraryBooks.stream()
.map(e -> createAuthor(e))
.collect(Collectors.toList());






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 22 at 21:08









marstranmarstran

11.2k22743




11.2k22743







  • 5





    Can you explain in what way this answers OP's question? I understand that this is the proper way to build a List with streams in general, but how does it answer the question of thread safety?

    – mypetlion
    Mar 22 at 21:12












  • 5





    Can you explain in what way this answers OP's question? I understand that this is the proper way to build a List with streams in general, but how does it answer the question of thread safety?

    – mypetlion
    Mar 22 at 21:12







5




5





Can you explain in what way this answers OP's question? I understand that this is the proper way to build a List with streams in general, but how does it answer the question of thread safety?

– mypetlion
Mar 22 at 21:12





Can you explain in what way this answers OP's question? I understand that this is the proper way to build a List with streams in general, but how does it answer the question of thread safety?

– mypetlion
Mar 22 at 21:12



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307740%2fis-this-code-threadsafe-using-java-8-lambdas-stream-foreach%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Obelisk of Theodosius Contents History Description Notes Bibliography Further reading External links Navigation menuAge of spirituality : late antique and early Christian art, third to seventh centuryOver 60 picturesObelisks of the World41°00′21.24″N 28°58′31.43″E / 41.0059000°N 28.9753972°E / 41.0059000; 28.97539727724550-7235741376235741376

밀양 대씨 역사 각주 함께 보기 둘러보기 메뉴밀양 대씨

1973년 목차 사건 문화 탄생 사망 노벨상 달력 둘러보기 메뉴