title: Rendering an Image Using Threads Cause Noisy Pictures
body: <p>I've built my own basic ray tracer.
  I've tried to optimize its performance, so I thought of using threads.
  When I render without threads - all looks good, but when I've tried to use threads - I've got a noisy picture with black stripes on it.</p>
  
  <p>This is the code. for every line of pixels, I've created a new executor to calculate the pixel colors in that line:</p>
  
  <pre class="lang-java prettyprint-override"><code>public void renderImage(){
          Camera camera = _scene.get_camera();
  
          for (int i = 0; i &lt; _imageWriter.getWidth(); ++i){
              final int iFinal = i;
  
              ExecutorService executor = Executors.newSingleThreadExecutor();
              executor.submit(() -&gt; {
                  for (int j = 0; j &lt; _imageWriter.getHeight(); ++j){
                      ArrayList&lt;Ray&gt; rays = camera.constructRaysThroughPixel(
                              _imageWriter.getNx(), _imageWriter.getNy(),
                              iFinal, j, _scene.get_screenDistance(),
                              _imageWriter.getWidth(), _imageWriter.getHeight()
                      );
  
                      Color color = new Color();
                      for (Ray ray: rays) {
  
                          ArrayList&lt;GeoPoint&gt; intersectionPoints = _scene.get_geometries().findIntersections(ray);
  
                          if (intersectionPoints.isEmpty() == true) {
                              color = color.add(_scene.get_background());
                          }
                          else {
                              GeoPoint closestPoint = getClosestPoint(intersectionPoints);
  
                              color = color.add(new Color(calcColor(closestPoint, new Ray(camera.get_origin(), closestPoint.point.subtract(camera.get_origin())))));
                          }
                      }
  
                      int length = rays.size();
                      color = color.scale(1.0/length);
  
                      _imageWriter.writePixel(iFinal, j, color.getColor());
  
                  }
              });
          }
      }
  </code></pre>
  
  <p>This is what I've gotten when I used threads:
  <a href="https://i.stack.imgur.com/XNzN2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XNzN2.jpg" alt="enter image description here"></a></p>
  
  <p>This is what I've gotten when I didnt use threads:
  <a href="https://i.stack.imgur.com/bmMmK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bmMmK.jpg" alt="enter image description here"></a></p>