Quantcast
Viewing all articles
Browse latest Browse all 1037

Clean Expired Element from HashMap while Adding more Elements at the Same Time – Java Timer, TimerTask and futures() – Complete Example

Image may be NSFW.
Clik here to view.
Delete Expired Element from Hashmap Every Second

Hashmap, ArrayList, Static Map, Vectors, etc are the most used Java collection framework elements. There are infinite number of scenarios you could use this as per your need.

This example is very interesting Java Example. We are going to perform below operation on single HashMap().

  • Create crunchifyMap Object
  • Keep adding element to Map every second which has expire time set to 5 seconds
  • Check for expired element like cache every second and delete from map if expired
  • After 5 seconds you will get always same size and always 5 elements as you are adding and deleting expired elements every second

Also if you have below questions then you are at right place:

  • What is Passive Expiring Map Example
  • Concurrent Map with timed out element
  • Java Cache Map Example
  • Java TimerTask Example
  • Evictor – a Java Concurrent Map Example

Let’s get started:

Point-1

  • Create Timer element crunchifyTimer
  • Schedules the specified task CrunchifyReminder() for repeated fixed-delay execution which is 1 second
  • In scheduled task
    • add element into crunchifyMap
    • check for expired element from crunchifyMap and delete

Point-2

  • During addElement() operation
    • We are associating current time for each element
  • During crunchifyClearExipredElementsFromMap() operation
    • We are checking for current time with element’s time
    • If time difference is more than 5 seconds then just delete element from crunchifyMap

Point-3

  • During add and remove operation print element on Eclipse console
  • 1st added element will be removed 1st and so on
  • Please check Eclipse console output for result

Here is a Java program:

package crunchify.com.tutorials;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Crunchify.com 
 * 
 * - Keep adding element to Map every second which has expire time set to 5 seconds
 * - Check for expired element every second and delete from map if expired 
 * - After 5 seconds you will get always same size as you are adding and deleting expired elements every second
 * 
 */

public class CrunchifyCleanExipredMapElements {

	Timer crunchifyTimer;
	private static long EXPIRED_TIME_IN_SEC = 5l;
	private static Map<Double, ArrayList<Date>> crunchifyMap = new HashMap<>();

	public static void main(String args[]) {
		new CrunchifyCleanExipredMapElements(1);
		log("Start Adding element every second\n\n");
	}

	public CrunchifyCleanExipredMapElements(int seconds) {
		crunchifyTimer = new Timer();
		crunchifyTimer.schedule(new CrunchifyReminder(), 0, seconds * 1000);
	}

	class CrunchifyReminder extends TimerTask {
		public void run() {
			
			// We are checking for expired element from map every second
			crunchifyClearExipredElementsFromMap(crunchifyMap);

			// We are adding element every second
			addElement();

		}
	}

	public void addElement() {
		crunchifyAddElementToMap(Math.random(), crunchifyMap);
	}

	// Check for element's expired time. If element is > 5 seconds old then remove it
	private static void crunchifyClearExipredElementsFromMap(Map<Double, ArrayList<Date>> map) {
		Date currentTime = new Date();
		Date actualExpiredTime = new Date();
		
		// if element time stamp and current time stamp difference is 5 second then delete element
		actualExpiredTime.setTime(currentTime.getTime() - EXPIRED_TIME_IN_SEC * 1000l);
		System.out.println("crunchifyMap size:" + map.size());

		Iterator<Entry<Double, ArrayList<Date>>> crunchifyIterator = map.entrySet().iterator();
		while (crunchifyIterator.hasNext()) {
			Entry<Double, ArrayList<Date>> entry = crunchifyIterator.next();
			ArrayList<Date> crunchifyElement = entry.getValue();

			while (crunchifyElement.size() > 0
					&& crunchifyElement.get(0).compareTo(actualExpiredTime) < 0) {
				log("----------- Element Deleted: " + entry.getKey());
				crunchifyElement.remove(0);
			}

			if (crunchifyElement.size() == 0) {
				crunchifyIterator.remove();
			}
		}
	}

	// Adding new element to map with current timestamp 
	private static void crunchifyAddElementToMap(Double digit, Map<Double, ArrayList<Date>> myMap) {
		ArrayList<Date> crunchifyList = new ArrayList<>();
		myMap.put(digit, crunchifyList);
		crunchifyList.add(new Date());
		log("+++++++++++ Element added:" + digit + "\n");
	}

	private static void log(String string) {
		System.out.println(string);

	}
}

Console Output:

Image may be NSFW.
Clik here to view.
Check for Expired and deleted element from crunchifyMap - complete example

Now Start Adding element every second

crunchifyMap size:0
+++++++++++ Element added:0.3321090256163167

crunchifyMap size:1
+++++++++++ Element added:0.29778458088827553

crunchifyMap size:2
+++++++++++ Element added:0.1650913469916243

crunchifyMap size:3
+++++++++++ Element added:0.12229083719470968

crunchifyMap size:4
+++++++++++ Element added:0.536557757275355

crunchifyMap size:5
----------- Element Deleted: 0.3321090256163167
+++++++++++ Element added:0.013565449767778959

crunchifyMap size:5                <===== same size as we are deleting expired element
----------- Element Deleted: 0.29778458088827553
+++++++++++ Element added:0.599557897686096

crunchifyMap size:5
----------- Element Deleted: 0.1650913469916243
+++++++++++ Element added:0.09771019697128791

crunchifyMap size:5
----------- Element Deleted: 0.12229083719470968
+++++++++++ Element added:0.47324898477566835

Have something to add to this article? Please chime in and join the conversation below.

The post Clean Expired Element from HashMap while Adding more Elements at the Same Time – Java Timer, TimerTask and futures() – Complete Example appeared first on Crunchify.
Author: App Shah Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 1037

Trending Articles