Question: I have a simple service providing REST APIs and I'd like to have a background thread in the service that runs periodically retrieving some data from a remote service and update the data to an object, this object is also used by requests.
And my question is what are the best practices for doting this kind of background updating in server side?

In order to have the best concurrencies, my initial idea is to simply using `volatile` on the object and reset this pointer in a background thread, so all requests could see it after update and it's okay for a request to see snapshot of an old version of the object. Is there any downside for this implementation? ReaderWriterLock seems to be another option but too heavy for this?

```
class Service
{
    public volatile String data = "default";
    public void handleRequest(Request req, Response resp)
    {
         resp.setBody(data);
    }
}

class Background implements Runnable
{
     private Service serv;
     // ... 
     public void run()
     {
         serv.data = "reset to "+System.currentTimeMillis();
     }
}

```

Answer: 
Your implementation is perfectly valid. The main purpose of volatile is exactly sharing a reference between threads in a thread-safe manner. In addition to volatile semantic `ReaderWriterLock` (and any locking) allows to execute compound actions together (atomic) without interleaving between threads. But as you don't have any compound actions which should be executed together volatile (which is cheaper than locking) is sufficient in you case.

You can also find `Executors.newSingleThreadScheduledExecutor()` useful for scheduling your background task.
[ScheduledExecutorService](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html) caters your requirement. 

```
/*  You can set pool size depending on your requirement */

ScheduledExecutorService scheduledExecutorService =
    Executors.newScheduledThreadPool(1);

```

You can use one of these two methods.

```
ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                   long initialDelay,
                                   long period,
                                   TimeUnit unit)

```

> 
> Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 \* period, and so on. 
> 
> 
> 

If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

**OR**

```
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                      long initialDelay,
                                      long delay,
                                      TimeUnit unit)

```

> 
> Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
> 
> 
> 

Regarding other query, [ReentrantLock](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html) is better option. If you properly implement locking mechanism, you won't need volatile variables. 

Have a look at this [article](https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html) for other high level concurrency controls.