Thursday, 6 June 2019

Explain about WeakHashMap


WeakHashMap is an implementation of Map interface, where Key is a weak reference to an object. If an object has only weak references associated with it, then Garbage collector permitted to reclaim the memory used by the object.

If you would like to know more about weak reference, I would recommend you to go through my below post.

App.java
package com.sample.app;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

public class App {

	public static class Employee {

	}

	public static class EmployeeInfo {

	}

	public static void main(String args[]) throws InterruptedException {
		Map<Employee, EmployeeInfo> map = new WeakHashMap<>();

		Employee emp = new Employee();

		map.put(emp, new EmployeeInfo());

		EmployeeInfo empInfo = map.get(emp);

		if (map.containsValue(empInfo)) {
			System.out.println("Map contains Employee information");
		}

		emp = null;
		System.gc();

		TimeUnit.SECONDS.sleep(5);

		if (map.containsValue(empInfo)) {
			System.out.println("Map contains Employee information");
		} else {
			System.out.println("Map do not contain Employee information");
		}

	}
}

Output
Map contains Employee information
Map do not contain Employee information


You may like


No comments:

Post a Comment