title: Proper way to clear a buffer in a different thread
body: <p>I am faced with this problem.<br>
  I have a processor class <code>Processor</code> that receives data from a client app, does a bunch of calculations and insert the result into a database.<br>
  I split the insert to DB to a different class <code>DataLayer</code><br>
  To avoid blocking the thread, I made the <code>DataLayer</code> class doesn't insert into the database right away but instead add the results to a list <code>List&lt;Result&gt; buffer</code>.<br>
  Every hour, the <code>DataLayer</code> would take the buffer insert to the database and clear the buffer<br>
  Now I am sure I could run into a race condition when clearing the buffer.<br>
  What is the right way to do this to avoid any concurrency issues</p>
  <p>code snippet:</p>
  <pre><code>public class Processor{
    
    private DataLayer dataLayer = new DataLayer();
  
    void accept(List&lt;Data&gt; data){
       //receive data from client app
       List&lt;Result&gt; results = calculateResults(data);
       saveResults(results)
    }
  
    List&lt;Result&gt; calculateResults(List&lt;Data&gt; data){
  
    void saveResults(List&lt;Result&gt; results){
       dataLayer.insertToDB(results);
    }
  
   }
  
  
  public class DataLayer {
  
     private ThreadPoolTaskScheduler taskScheduler;
  
     private List&lt;Result&gt; buffer = new ArrayList&lt;&gt;();
  
     public DataLayer(){
        scheduleHourlyCheck();
     }
  
     void insertToDB(List&lt;Result&gt; results){
        this.buffer.add(results)
     }
  
     scheduleHourlyCheck(){
       taskScheduler.schedule(() -&gt; {
         jdbcTemplate.update(...)
         buffer.clear()   // ------&gt; i am sure this shouldn't be done
       }, everyHour)
     }
  }
  </code></pre>
  <p>My issue is this:
  <code>buffer.clear()</code></p>
  <p>I am sure this could cause concurrency issues<br>
  what is the proper way to handle this?</p>