Java Basic Key-Value store

Memory store (also often called key-value store because of such kind of storage system), is a usefull tool. It is, many times, used as a temporary database like memcache or Redis. For example, I show up many times how to store php session inside such system to be able to share data with other server.

I was working recently on a Jersey App (a Java app so), and I face out that memory store does not exist in such system by default (and does not seems to exist). There is the HashMap but it’s not enough for making a good memory store (but it’s a good start).

The fact that Java always run, allow us to make such system by using only default Java system. So I decide to start my own, basic, memory key-value pair storage, in a full Java way.

package com.memory;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Timeout functionnality for the memory store
 * @author Deisss (LGPLv3)
 * @version 0.1
 */
class TimeoutMemoryStore extends TimerTask{
	private String key;

	/**
	 * Constructor
	 * @param key The key to use & store
	 */
	public TimeoutMemoryStore(String key){
		this.key = key;
	}

	@Override
	public void run() {
		if(this.key != null & this.key.length() > 0){
			MemoryStore.delete(this.key);
		}
	}
}

/**
 * The memory store will keep data inside the class, for a specific amout of time
 * @author Deisss (LGPLv3)
 * @version 0.1
 */
public class MemoryStore {
	//This will store any kind of object, related to a specific key value in string
	private static HashMap<String, Object> mem;

	/**
	 * Add an object into the memory store
	 * @param obj The object to store
	 * @return The key stored
	 */
	public static String add(Object obj){
		return add(obj, 0);
	}

	/**
	 * Add an object into the memory store
	 * @param obj The object to store
	 * @param timeout The delay in ms
	 * @return The key store
	 */
	public static String add(Object obj, long timeout){
		//If the system is not functionnal
		if(mem == null){
			erase();
		}

		//Generating a unique id
		String gen = generate(16);
		while(mem.containsKey(gen)){
			gen = generate(16);
		}

		mem.put(gen, obj);

		//Create a delete operation after timeout
		if(timeout > 0){
			new Timer().schedule(new TimeoutMemoryStore(gen), timeout);
		}

		return gen;
	}

	/**
	 * Get a specific object regarding key
	 * @param key The key to search
	 * @return The object retrieve, or null if nothing found
	 */
	public static Object get(String key){
		if(mem.containsKey(key)){
			return mem.get(key);
		}else{
			return null;
		}
	}

	/**
	 * Delete an entry from the memory store
	 * @param key The key to delete
	 * @return The delete value result (true if the object has been found, false in other case)
	 */
	public static boolean delete(String key){
		if(mem.containsKey(key)){
			mem.remove(key);
			return true;
		}
		return false;
	}

	/**
	 * Empty the memory store
	 */
	public static void erase(){
		mem = new HashMap<String, Object>();
	}

	/**
	 * This generate a random string of the given size
	 * @param length The output length to retrieve
	 * @return The generated string
	 */
	private static String generate(int length){
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		int charLength = chars.length();
		String pass = "";
		for(int x=0; x<length; x++){
			int i = (int) Math.floor(Math.random() * charLength);
			pass += chars.charAt(i);
		}
		return pass;
	}
}

From that class, only the MemoryStore should be accessed, you can use it like this :

//Set a value
String key = Store.add(new String("test"));

//Get a value
String value = (String) Store.get(key);

//Delete a value
Store.delete(key);

//Destroy the full store
Store.erase();

//Set a value with timeout (in ms)
String key = Store.add(new String("second test"), 2000);

//After 2000ms (2s), the value will be deleted from store

Here so a basic store system, a key-value one.

Publicités

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

%d blogueurs aiment cette page :