Working with the DataBase remote datetime (JPA)

A few days ago i decided to pick up work on a simple web-game i once tried to created when i was 15 (see related: Generating isometric tiles and slopes). And while working on it i decided the architecture should be able support multiple workers performing on a single database. As a consequence i required all my worker’s to be able to all use the same datetime.

Now as i’m not in control of the host machines to actually perform a time-sync, i figured i should best use the remote-database time as the single truth.

I ended up writing the following utility class, i’m really curious on what you guys think of it.

note: Unfortunately no generic JPA query, but one specific to mysql

package nl.ivojonker.sm.model.util;

import java.sql.Timestamp;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Utility class for obtaining the current datetime from the database server.
 * @author Ivo
 *
 */
@Singleton
@Startup
public class DBDate {

	private static long localCacheDate=System.currentTimeMillis();
	private static long remoteCacheDate=System.currentTimeMillis(); 

	@PersistenceContext 
	private EntityManager em;

	/**
	 * Returns the date-time from the server.
	 * @return
	 */
	public static Date getDate(){
		return new Date(remoteCacheDate+(System.currentTimeMillis()-localCacheDate));
	}

	@PostConstruct
	private void init(){
		long beforRequest=System.currentTimeMillis();
		Timestamp remoteDate = (Timestamp)(em.createNativeQuery("select CURRENT_TIMESTAMP").getSingleResult());
		long latency = System.currentTimeMillis() - beforRequest;
		
		localCacheDate=beforRequest;
		remoteCacheDate=remoteDate.getTime()-latency;
		
		System.out.println(String.format("Local date: %1$s, remote set to date: %2$s, taking into account an estimated latency of: %3$s ms ", new Date(localCacheDate),new Date(remoteCacheDate),latency));
	}
}

 

One thought on “Working with the DataBase remote datetime (JPA)

Leave a Reply

Your email address will not be published. Required fields are marked *