Need to manually synchronize the Synchronized list while iteration when it could be avoided? The Next CEO of Stack OverflowThread safe for static functionJava Concurrency In Practice. Listing 5.6Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loopAvoid synchronized(this) in Java?synchronizedCollection and contains--do I need to synchronize manually?Java synchronized list for loopWhy do I need to synchronize a list returned by Collections.synchronizedListWays to iterate over a list in JavaWhy do we still need external synchronization when a synchronizedList() or Vector is already synchronized?Why not inherit from List<T>?why synchronize a synchronized list?Is it necessary to use synchronizedList instead List if iteration synchronized already?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

Proper way to express "He disappeared them"

Flying from Cape Town to England and return to another province

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

Is there a difference between "Fahrstuhl" and "Aufzug"

Why didn't Khan get resurrected in the Genesis Explosion?

What happened in Rome, when the western empire "fell"?

What flight has the highest ratio of time difference to flight time?

Writing differences on a blackboard

How many extra stops do monopods offer for tele photographs?

Are police here, aren't itthey?

The exact meaning of 'Mom made me a sandwich'

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

Is micro rebar a better way to reinforce concrete than rebar?

Should I tutor a student who I know has cheated on their homework?

Solving system of ODEs with extra parameter

What connection does MS Office have to Netscape Navigator?

When you upcast Blindness/Deafness, do all targets suffer the same effect?

Why did CATV standarize in 75 ohms and everyone else in 50?

Is wanting to ask what to write an indication that you need to change your story?

How to count occurrences of text in a file?

Is there a way to save my career from absolute disaster?

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?



Need to manually synchronize the Synchronized list while iteration when it could be avoided?



The Next CEO of Stack OverflowThread safe for static functionJava Concurrency In Practice. Listing 5.6Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loopAvoid synchronized(this) in Java?synchronizedCollection and contains--do I need to synchronize manually?Java synchronized list for loopWhy do I need to synchronize a list returned by Collections.synchronizedListWays to iterate over a list in JavaWhy do we still need external synchronization when a synchronizedList() or Vector is already synchronized?Why not inherit from List<T>?why synchronize a synchronized list?Is it necessary to use synchronizedList instead List if iteration synchronized already?










7















My question is about synchronizedList method Collections Class.



Javadocs say:



It is imperative that the user manually synchronize on the returned list when iterating over it:



List list = Collections.synchronizedList(new ArrayList());
...
synchronized(list)
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());



Though manually synchroniziation is not required for other methods. I looked into the source code of Collections class
and found shyncronization has already been taken care for all methods like add



public boolean add(E e) 
synchronized(list) return c.add(e);



but not for iterator method. I think iterator method could have also handled synchronization in the same fashion
as above method (it would have avoided the extra work i.e manual synchronization for programmers). i am sure there
must be some concrete reason behind it but i am missing it?



public Iterator<E> iterator() 
return c.iterator(); // Must be manually synched by user!



A way to avoid manual synchronization from Programmer



public Iterator<E> iterator() 
synchronized(list)
return c.iterator(); // No need to manually synched by user!











share|improve this question




























    7















    My question is about synchronizedList method Collections Class.



    Javadocs say:



    It is imperative that the user manually synchronize on the returned list when iterating over it:



    List list = Collections.synchronizedList(new ArrayList());
    ...
    synchronized(list)
    Iterator i = list.iterator(); // Must be in synchronized block
    while (i.hasNext())
    foo(i.next());



    Though manually synchroniziation is not required for other methods. I looked into the source code of Collections class
    and found shyncronization has already been taken care for all methods like add



    public boolean add(E e) 
    synchronized(list) return c.add(e);



    but not for iterator method. I think iterator method could have also handled synchronization in the same fashion
    as above method (it would have avoided the extra work i.e manual synchronization for programmers). i am sure there
    must be some concrete reason behind it but i am missing it?



    public Iterator<E> iterator() 
    return c.iterator(); // Must be manually synched by user!



    A way to avoid manual synchronization from Programmer



    public Iterator<E> iterator() 
    synchronized(list)
    return c.iterator(); // No need to manually synched by user!











    share|improve this question


























      7












      7








      7


      3






      My question is about synchronizedList method Collections Class.



      Javadocs say:



      It is imperative that the user manually synchronize on the returned list when iterating over it:



      List list = Collections.synchronizedList(new ArrayList());
      ...
      synchronized(list)
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
      foo(i.next());



      Though manually synchroniziation is not required for other methods. I looked into the source code of Collections class
      and found shyncronization has already been taken care for all methods like add



      public boolean add(E e) 
      synchronized(list) return c.add(e);



      but not for iterator method. I think iterator method could have also handled synchronization in the same fashion
      as above method (it would have avoided the extra work i.e manual synchronization for programmers). i am sure there
      must be some concrete reason behind it but i am missing it?



      public Iterator<E> iterator() 
      return c.iterator(); // Must be manually synched by user!



      A way to avoid manual synchronization from Programmer



      public Iterator<E> iterator() 
      synchronized(list)
      return c.iterator(); // No need to manually synched by user!











      share|improve this question
















      My question is about synchronizedList method Collections Class.



      Javadocs say:



      It is imperative that the user manually synchronize on the returned list when iterating over it:



      List list = Collections.synchronizedList(new ArrayList());
      ...
      synchronized(list)
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
      foo(i.next());



      Though manually synchroniziation is not required for other methods. I looked into the source code of Collections class
      and found shyncronization has already been taken care for all methods like add



      public boolean add(E e) 
      synchronized(list) return c.add(e);



      but not for iterator method. I think iterator method could have also handled synchronization in the same fashion
      as above method (it would have avoided the extra work i.e manual synchronization for programmers). i am sure there
      must be some concrete reason behind it but i am missing it?



      public Iterator<E> iterator() 
      return c.iterator(); // Must be manually synched by user!



      A way to avoid manual synchronization from Programmer



      public Iterator<E> iterator() 
      synchronized(list)
      return c.iterator(); // No need to manually synched by user!








      java list collections synchronization java.util.concurrent






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 18 '13 at 17:48









      Răzvan Petruescu

      4301514




      4301514










      asked Sep 18 '13 at 13:27









      M SachM Sach

      16.5k62177272




      16.5k62177272






















          3 Answers
          3






          active

          oldest

          votes


















          17















          I think iterator method could have also handled synchronization in the same fashion as above method




          No, it absolutely couldn't.



          The iterator has no control over what your code does between calls to the individual methods on it. That's the point. Your iteration code will call hasNext() and next() repeatedly, and synchronization during those calls is feasible but irrelevant - what's important is that no other code tries to modify the list across the whole time you're iterating.



          So imagine a timeline of:



          t = 0: call iterator()
          t = 1: call hasNext()
          t = 2: call next()
          // Do lots of work with the returned item
          t = 10: call hasNext()


          The iterator can't synchronize between the end of the call to next() at t=2 and the call to hasNext() at t=10. So if another thread tries to (say) add an item to the list at t=7, how is the iterator meant to stop it from doing so?



          This is the overall problem with synchronized collections: each individual operation is synchronized, whereas typically you want a whole chunky operation to be synchronized.






          share|improve this answer























          • @StevenYang: Because that doesn't prevent changes being made between calls. Basically, read the answer again, carefully :)

            – Jon Skeet
            Oct 8 '15 at 21:43


















          3














          If you don't synchronize the entire iteration, another thread could modify the collection as you iterate, leading to a ConccurentModificationException.



          Also, the returned iterator is not thread-safe.

          They could fix that by wrapping the iterator in a SynchronizedIterator that locks every method in the iterator, but that wouldn't help either – another thread could still modify the collection between two iterations, and break everything.



          This is one of the reasons that the Collections.synchronized*() methods are completely useless.

          For more information about proper thread-safe collection usage, see my blog.






          share|improve this answer






























            1














            If you want to avoid manual synchronization, you have to use a Collection like java.util.concurrent.CopyOnWriteArrayList. Every time an object is added to the list, the underlying datastructure is copyied to avaoid a concurrent modification exception.



            The reason why you need manual serialization on the Iterator in your example is that the Iterator uses the same internal datastructure as the list but they are independend objects and both Iterator and list can be accessed by different threads at any arbitrary moment in time.



            Another aproach would be to make a local copy of the list and iterate over the copy.






            share|improve this answer

























              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%2f18873547%2fneed-to-manually-synchronize-the-synchronized-list-while-iteration-when-it-could%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              17















              I think iterator method could have also handled synchronization in the same fashion as above method




              No, it absolutely couldn't.



              The iterator has no control over what your code does between calls to the individual methods on it. That's the point. Your iteration code will call hasNext() and next() repeatedly, and synchronization during those calls is feasible but irrelevant - what's important is that no other code tries to modify the list across the whole time you're iterating.



              So imagine a timeline of:



              t = 0: call iterator()
              t = 1: call hasNext()
              t = 2: call next()
              // Do lots of work with the returned item
              t = 10: call hasNext()


              The iterator can't synchronize between the end of the call to next() at t=2 and the call to hasNext() at t=10. So if another thread tries to (say) add an item to the list at t=7, how is the iterator meant to stop it from doing so?



              This is the overall problem with synchronized collections: each individual operation is synchronized, whereas typically you want a whole chunky operation to be synchronized.






              share|improve this answer























              • @StevenYang: Because that doesn't prevent changes being made between calls. Basically, read the answer again, carefully :)

                – Jon Skeet
                Oct 8 '15 at 21:43















              17















              I think iterator method could have also handled synchronization in the same fashion as above method




              No, it absolutely couldn't.



              The iterator has no control over what your code does between calls to the individual methods on it. That's the point. Your iteration code will call hasNext() and next() repeatedly, and synchronization during those calls is feasible but irrelevant - what's important is that no other code tries to modify the list across the whole time you're iterating.



              So imagine a timeline of:



              t = 0: call iterator()
              t = 1: call hasNext()
              t = 2: call next()
              // Do lots of work with the returned item
              t = 10: call hasNext()


              The iterator can't synchronize between the end of the call to next() at t=2 and the call to hasNext() at t=10. So if another thread tries to (say) add an item to the list at t=7, how is the iterator meant to stop it from doing so?



              This is the overall problem with synchronized collections: each individual operation is synchronized, whereas typically you want a whole chunky operation to be synchronized.






              share|improve this answer























              • @StevenYang: Because that doesn't prevent changes being made between calls. Basically, read the answer again, carefully :)

                – Jon Skeet
                Oct 8 '15 at 21:43













              17












              17








              17








              I think iterator method could have also handled synchronization in the same fashion as above method




              No, it absolutely couldn't.



              The iterator has no control over what your code does between calls to the individual methods on it. That's the point. Your iteration code will call hasNext() and next() repeatedly, and synchronization during those calls is feasible but irrelevant - what's important is that no other code tries to modify the list across the whole time you're iterating.



              So imagine a timeline of:



              t = 0: call iterator()
              t = 1: call hasNext()
              t = 2: call next()
              // Do lots of work with the returned item
              t = 10: call hasNext()


              The iterator can't synchronize between the end of the call to next() at t=2 and the call to hasNext() at t=10. So if another thread tries to (say) add an item to the list at t=7, how is the iterator meant to stop it from doing so?



              This is the overall problem with synchronized collections: each individual operation is synchronized, whereas typically you want a whole chunky operation to be synchronized.






              share|improve this answer














              I think iterator method could have also handled synchronization in the same fashion as above method




              No, it absolutely couldn't.



              The iterator has no control over what your code does between calls to the individual methods on it. That's the point. Your iteration code will call hasNext() and next() repeatedly, and synchronization during those calls is feasible but irrelevant - what's important is that no other code tries to modify the list across the whole time you're iterating.



              So imagine a timeline of:



              t = 0: call iterator()
              t = 1: call hasNext()
              t = 2: call next()
              // Do lots of work with the returned item
              t = 10: call hasNext()


              The iterator can't synchronize between the end of the call to next() at t=2 and the call to hasNext() at t=10. So if another thread tries to (say) add an item to the list at t=7, how is the iterator meant to stop it from doing so?



              This is the overall problem with synchronized collections: each individual operation is synchronized, whereas typically you want a whole chunky operation to be synchronized.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 18 '13 at 13:29









              Jon SkeetJon Skeet

              1096k69679848470




              1096k69679848470












              • @StevenYang: Because that doesn't prevent changes being made between calls. Basically, read the answer again, carefully :)

                – Jon Skeet
                Oct 8 '15 at 21:43

















              • @StevenYang: Because that doesn't prevent changes being made between calls. Basically, read the answer again, carefully :)

                – Jon Skeet
                Oct 8 '15 at 21:43
















              @StevenYang: Because that doesn't prevent changes being made between calls. Basically, read the answer again, carefully :)

              – Jon Skeet
              Oct 8 '15 at 21:43





              @StevenYang: Because that doesn't prevent changes being made between calls. Basically, read the answer again, carefully :)

              – Jon Skeet
              Oct 8 '15 at 21:43













              3














              If you don't synchronize the entire iteration, another thread could modify the collection as you iterate, leading to a ConccurentModificationException.



              Also, the returned iterator is not thread-safe.

              They could fix that by wrapping the iterator in a SynchronizedIterator that locks every method in the iterator, but that wouldn't help either – another thread could still modify the collection between two iterations, and break everything.



              This is one of the reasons that the Collections.synchronized*() methods are completely useless.

              For more information about proper thread-safe collection usage, see my blog.






              share|improve this answer



























                3














                If you don't synchronize the entire iteration, another thread could modify the collection as you iterate, leading to a ConccurentModificationException.



                Also, the returned iterator is not thread-safe.

                They could fix that by wrapping the iterator in a SynchronizedIterator that locks every method in the iterator, but that wouldn't help either – another thread could still modify the collection between two iterations, and break everything.



                This is one of the reasons that the Collections.synchronized*() methods are completely useless.

                For more information about proper thread-safe collection usage, see my blog.






                share|improve this answer

























                  3












                  3








                  3







                  If you don't synchronize the entire iteration, another thread could modify the collection as you iterate, leading to a ConccurentModificationException.



                  Also, the returned iterator is not thread-safe.

                  They could fix that by wrapping the iterator in a SynchronizedIterator that locks every method in the iterator, but that wouldn't help either – another thread could still modify the collection between two iterations, and break everything.



                  This is one of the reasons that the Collections.synchronized*() methods are completely useless.

                  For more information about proper thread-safe collection usage, see my blog.






                  share|improve this answer













                  If you don't synchronize the entire iteration, another thread could modify the collection as you iterate, leading to a ConccurentModificationException.



                  Also, the returned iterator is not thread-safe.

                  They could fix that by wrapping the iterator in a SynchronizedIterator that locks every method in the iterator, but that wouldn't help either – another thread could still modify the collection between two iterations, and break everything.



                  This is one of the reasons that the Collections.synchronized*() methods are completely useless.

                  For more information about proper thread-safe collection usage, see my blog.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 18 '13 at 13:28









                  SLaksSLaks

                  691k13916501770




                  691k13916501770





















                      1














                      If you want to avoid manual synchronization, you have to use a Collection like java.util.concurrent.CopyOnWriteArrayList. Every time an object is added to the list, the underlying datastructure is copyied to avaoid a concurrent modification exception.



                      The reason why you need manual serialization on the Iterator in your example is that the Iterator uses the same internal datastructure as the list but they are independend objects and both Iterator and list can be accessed by different threads at any arbitrary moment in time.



                      Another aproach would be to make a local copy of the list and iterate over the copy.






                      share|improve this answer





























                        1














                        If you want to avoid manual synchronization, you have to use a Collection like java.util.concurrent.CopyOnWriteArrayList. Every time an object is added to the list, the underlying datastructure is copyied to avaoid a concurrent modification exception.



                        The reason why you need manual serialization on the Iterator in your example is that the Iterator uses the same internal datastructure as the list but they are independend objects and both Iterator and list can be accessed by different threads at any arbitrary moment in time.



                        Another aproach would be to make a local copy of the list and iterate over the copy.






                        share|improve this answer



























                          1












                          1








                          1







                          If you want to avoid manual synchronization, you have to use a Collection like java.util.concurrent.CopyOnWriteArrayList. Every time an object is added to the list, the underlying datastructure is copyied to avaoid a concurrent modification exception.



                          The reason why you need manual serialization on the Iterator in your example is that the Iterator uses the same internal datastructure as the list but they are independend objects and both Iterator and list can be accessed by different threads at any arbitrary moment in time.



                          Another aproach would be to make a local copy of the list and iterate over the copy.






                          share|improve this answer















                          If you want to avoid manual synchronization, you have to use a Collection like java.util.concurrent.CopyOnWriteArrayList. Every time an object is added to the list, the underlying datastructure is copyied to avaoid a concurrent modification exception.



                          The reason why you need manual serialization on the Iterator in your example is that the Iterator uses the same internal datastructure as the list but they are independend objects and both Iterator and list can be accessed by different threads at any arbitrary moment in time.



                          Another aproach would be to make a local copy of the list and iterate over the copy.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 7 at 16:39









                          Community

                          11




                          11










                          answered Sep 18 '13 at 14:12









                          TomWolkTomWolk

                          64749




                          64749



























                              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%2f18873547%2fneed-to-manually-synchronize-the-synchronized-list-while-iteration-when-it-could%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

                              Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                              Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                              Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved