Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8367764

Too much optimization breaking a queue.poll()

XMLWordPrintable

    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      When using a LinkedList as a queue across 2 threads poll()ing doesn't get new data after it is added to queue unless a useless function call with a parameter is right afterwards before doing the null check to see if something was obtained from the queue

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      See the code example. (looks a bit useless but it was a minified example, the discovery was a more real usecase)
      it should print out the numbers sent across the queue and the queue length never going up.

      uncommenting the useless function call line on line 15 of the example causes the example to work.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Queue reading to work
      ACTUAL -
      Queue getting fuller and fuller and nothing gets printed at the reading end of the queue

      ---------- BEGIN SOURCE ----------
      import java.util.LinkedList;
      import java.util.Queue;

      public class Repro
      {
          static Queue<String> queue = new LinkedList<>();
          public static void main(String[] args)
          {
              new Thread(
                      ()->
                      {
                          while(true)
                          {
                              String itm = queue.poll();
                              //System.getenv("path"); //useless function call with parameter breaking the optimizations, comment out and nothing gets printed in the if;
                              if(itm != null)
                              {
                                  System.out.println(itm);
                              }
                          }
                      }
              ).start();
              
              try
              {
                  Thread.sleep(100);
              } catch (InterruptedException e)
              {
                  throw new RuntimeException(e);
              }
              System.out.println("Feeding the queue now!");
              for(int i=0;;i++)
              {
                  if(i%1000==0)
                  {
                      try
                      {
                          Thread.sleep(100);
                      } catch (InterruptedException e)
                      {
                          throw new RuntimeException(e);
                      }
                      queue.add(i+"");
                      System.out.println("QLEN="+queue.size());
                  }
              }
          }
      }
      ---------- END SOURCE ----------

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: