title: Best way to share object between threads?
body: <p>I have a main <code>Swing</code> app with class members <code>BufferedImage lastCapturedImage</code>,  <code>ScheduledExecutorService executor</code> with 2 threads in the thread pool.</p>
  
  <pre><code>BufferedImage lastCapturedImage;
  ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
  ...
  executor.scheduleWithFixedDelay(imageCaptureRunnable, 100, 1000 / TARGET_FPS, TimeUnit.MILLISECONDS);
  executor.schedule(roboticArmRunnable, 500, TimeUnit.MILLISECONDS);
  </code></pre>
  
  <p>The first <code>Runnable</code> pulls images (<code>BufferedImage</code>) from a webcam and updates a class instance <code>lastCapturedImage</code>.</p>
  
  <pre><code>private final Runnable imageCaptureRunnable = new Runnable() {
  
    @Override
    public void run() {
      lastCapturedImage = webcam.getImage();
    }
  
  };
  </code></pre>
  
  <p>The second <code>Runnable</code> processes the image and controls a robotic arm. The image capturing rate is much faster than the robotic arm consumer and only the most current image is needed by the robotic arm consumer. How best do I share the image in a thread safe way?</p>
  
  <p>After researching this topic, my solution is to wrap the image (<code>lastCapturedImage</code>) in a <code>synchronized</code> block in the <code>roboticArmRunnable</code>'s <code>run()</code> method, and make a copy of the image like this:</p>
  
  <pre><code>private final Runnable roboticArmRunnable = new Runnable() {
  
    @Override
    public void run() {
      while(true){
        BufferedImage clonedCameraCapture;
        synchronized (lastCapturedImage) {
          clonedCameraCapture = copyImage(lastCapturedImage);
        }
        // process the clonedCameraCapture image and move the robotic arm
      }
    }
  };
  </code></pre>
  
  <p>My understanding is that the <code>synchronized</code> block will allow for the <code>roboticArmRunnable</code> to completely make the copy of the image before the <code>imageCaptureRunnable</code> is allowed to update the image. Am I doing this right??</p>
  
  <p>Thanks in advance!</p>