Monday, June 2, 2008

WeakHashMap : An Observation

Consider the following code snippet.

1 public class TestWeakHashMap {
2 public static void main(String[] args) {
3 WeakHashMap map=new WeakHashMap();

4 String s1=new String("java");
5 map.put(s1, "good");

6 String s2=new String("java");
7 map.put(s2,"ok");

//Since s1.equals(s2) is true and hash is same, the earlier value
//against key s1 ("good") in the map is replaced by the new one. ("ok")

8 s1=null;

9 System.gc();
//Verify Full GC with the -verbose:gc option

10 System.out.println(map.size());
11 }
12 }

What do we expect the output to be? 1? No, Not exactly.

Here s1 and s2 are two different objects on the heap. So in line 5, a new (key,value) pair with key s1 is put into the map. Later when a (key,value) with key s2 is being put into the map, it checks for equals on s1 and s2 and their hashcode. When it finds the equals returns true and hashcde is same, it replaces the value of the earlier entry with the new value. But the issue(?) here is, WeakHashMap/HashMap does not replace the earlier key while adding a (key, value) pair whose key is actually a duplicate key in the map.
So even after putting an entry with key s2, the WeakHashMap has only one entry whose key refers to the object refered by s1 and not s2.
Now the object on the heap refered by s1, has one strong reference(through s1) and one weak reference through the WeakHashMap.
Later when I say s1=null, the object on the heap refered to by s1 lost the strong reference and when gc happens, the entry is removed from the map.

So thats how it works.

Also note WeakHashMap is only a wrapper over HashMap and the HashMap's put api says " If the map previously contained a mapping for this key, the old value is replaced by the specified value."

So just be careful when you use WeakHashMap and your usage scenario is similar to the above.

52 comments:

Anonymous said...

Jobs site


http://www.back2office.com


India's growing job site.Jobs available in sectors like Accounting,
Marketing,IT,Engineering,Finance,BPO/Call Centers,Bio Technology,
Banks,Adminstration,HR/IR/MR,Media,Sales,Security,
Business Mgmt.,Retails,Hotels & Others.
Find Jobs In India,UK,USA,Middle East.

Anonymous said...

turning whichever retina uksvjksa goodwill hilarious assembly eliminates multiple gases hindley
semelokertes marchimundui

Ashank said...

nice post. thanks

Joshua Smith said...

Also you may turn your attention on offshore software development company.

Quentin Soto said...

You may convert your interest on overseas application growth company.

for ict 99 said...

Java SE WeakHashMap Courses An Observation Training Java Training Institutes in Chennai Java SE Course WeakHashMap has only one entry Training whose key refers Java Training in Chennai Java SE & Java EE Courses wrapper over HashMap and the HashMap's Training Java Online Course WeakHashMap/HashMap does not replace the earlier key Training Java SE Java EE Training

Unknown said...

Thanks intended for expressing an exceptionally helpful and intensely educational blog.nimble app

Unknown said...

IVR administration is driving ivr organization supplier in USA with all part twilio IVR, for example, laborer after structure and call recording organization. here is association for more data

Unknown said...

This blog provides a observation of week hash map. This helps to learn more about this process. This gives the coded explanation. That is very helpful to me. Thanks for this blog.
Java Training in Chennai

Suseela said...


What an awesome post, I just read it from start to end. Learned something new after a long time.


SAP MM training in Chennai

Unknown said...

Informative post and very much useful

SAP Training in Chennai | SAP Training Institutes in Chennai | Best SAP Training in Chennai

for ict 99 said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

for ict 99 said...

Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training

Hibernate Training Institutes in ChennaiHibernate Training Institutes in Chennai Hibernate Online Training Hibernate Online Training Hibernate Training in Chennai Hibernate Training in Chennai

Unknown said...

Core JAVA Training in Chennai | JAVA Training in Chennai

Unknown said...

Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
Regards,
PMP Training | PMP Training in Chennai

Unknown said...

Nice and good article.. it is very useful for me to learn and understand easily.. thanks for sharing your valuable information and time.. please keep updating.

Java Training in chennai

Java Training institute in chennai

Unknown said...

I am apparently an innocent abroad, but it never occurred to me that my blogs were aces of anyone's apprehension to bother hacking wordpress backup them. However, hackers assume to appearance alike the atomic of blogs and users as fair game. Learn what I accept done to aegis my Wordpress blogs in future, and accomplish it simple to balance with no abstracts loss.

Alex daina said...

Admonished is forearmed! So it is with payday advances. In the event that you realize what this sort of loan will cost you, you will be in a superior position to measure the advantages and disadvantages of settling on it. Payday Loans Chicago

rohil said...

Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
Good discussion.
PMP Training Course in Bangalore
PMP Training Course in Dammam
PMP Training Course in Dubai
PMP Training Course in Jeddah
PMP Training Course in Riyadh
Get trained by an expert who will enrich you with the latest trends.

rama said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us. Do check Six Sigma Training in Bangalore | Six Sigma Training in Dubai & Get trained by an expert who will enrich you with the latest trends.

Government Jobs said...

Thanks for sharing this unique information with us. Your post is really awesome. Your blog is really helpful for me..
Top college in Jaipur|law college|law college in Jaipur|Best law college in Jaipur

Government Jobs said...

Hey Your site is awesome and full of information. I have read you posts they are so informative. Keep Posting wonderful content.
Ani international provide the security solutions for all kind of secruity system and other equipment.
Home security system in jaipur
Wireless Home Security System in jaipur
Realtime attendance machine in jaipur
CCTV Camera dealer in jaipur
Hikvision DVR in jaipur at Rajasthan
security system solutions in jaipur
website design in jaipur
website development company in jaipur
seo company in jaipur

Government Jobs said...

Thanks for sharing this unique information with us. Your post is really awesome. Your blog is really helpful for me..
organic oil
organic oil in jaipur
organic cold pressed oils
ayurvedic oil store in jaipur

aditya said...

Thanks for sharing this unique information with us. Your post is really awesome. Your blog is really helpful for me..
hospital equipment
sarthak maditech
hospital equipment suppliers
hospital equipment manufacturers
medical equipment manufacturers in jaipur
operation theater lights
hospital suction machine
alcohol breath tester
hospital furniture manufacturer

Sam Daniel said...
This comment has been removed by the author.
Anonymous said...

thanks for the information
sap mm training in chennai
sap fico training in chennai
sap hr training in chennai
sap hana training in chennai
sap fiori training in chennai

Anonymous said...

thanks for the information
sap fiori training in chennai
sap hana training in chennai

Sam Daniel said...

Wonderful Blog. Keep Posting.
Advanced Excel Training in Chennai
Corporate Excel Training in Mumbai
Advanced Excel Training in Bangalore
Power BI Training in Chennai
Corporate Tableau Training
Corproate Excel Training Delhi, Gurgaon, Noida

Rathinam said...

I really glad to read your great post and I like your written style. I am waiting for your numerous post...
Oracle Training in Chennai
Oracle Training
Social Media Marketing Courses in Chennai
Tableau Training in Chennai
Primavera Training in Chennai
Job Openings in Chennai
Oracle DBA Training in Chennai
Power BI Training in Chennai
Oracle Training in Velachery
Oracle Training in Vadapalani

Soulblu said...

Thanks for sharing excellent information. keep on sharing such useful info E Cigarette Australia

Aditi Ray said...

TreasureBox is operated by a group of young, passionate, and ambitious people that are working diligently towards the same goal - make your every dollar count, as we believe you deserve something better.
sofa bed nz
gazebo nz

Venkatesh CS said...

Excellent Blog. Thank you so much for sharing.
best react js training in chennai
react js training in Chennai
react js workshop in Chennai
react js courses in Chennai
react js training institute in Chennai
reactjs training Chennai
react js online training
react js online training india
react js course content
react js training courses
react js course syllabus
react js training
react js certification in chennai
best react js training

Rajesh said...

Nice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Course In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai

Rajesh said...

Rpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai

Rajesh said...

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai

Repute Technologies said...

Good Information you had shared. Thank You!

AI Development companies in Coimbatore
Blockchain Development Companies & App Developers in India
best leading Cloud Computing & Cloud Hosting Service Providers

Venkatesh CS said...

Thanks for sharing valuable information.
Digital Marketing training Course in chennai
digital marketing training institute in chennai
digital marketing training in Chennai
digital marketing course in Chennai
digital marketing course training in omr
digital marketing certification in omr
digital marketing course training in velachery
digital marketing training center in chennai
digital marketing courses with placement in chennai
digital marketing certification in chennai
digital marketing institute in Chennai
digital marketing certification course in Chennai
digital marketing course training in Chennai
Digital Marketing course in Chennai with placement
digital marketing courses in chennai

Govt Jobz Adda said...


I have read your blog its very attractive and impressive. Nice information. It helped me alot.
Government vacancy
Govt Jobs
Sarkari nokri
latest sarkari vacancy
Online Form
latest govt jobs

Knowledgeshub said...

I have read your blog its very attractive and impressive. Nice information. It helped me alot.
best smartphone
best smartphone in india
best android phone
best mobiles phones 2020
best smartphone in india under 15000

Govt Jobz Adda said...

I have read your blog its very attractive and impressive. Nice information. It helped me alot.
Government vacancy
govt jobs
latest govt jobs
Sarkari nokri
govt jobs Adda
govt recruitment
latest sarkari vacancy

Anonymous said...

Ищите, где заказать стильную женскую сумку? Добро пожаловать в магазин сумок сумка на плечо . Бронируйте и покупайте стильные сумки прекрасного качества из Италии Marina Creazioni и Jenci и.

surya said...

What an wonderful post, I just read it from start to end. Learned something new after a long time.
Angular JS Training in Chennai | Certification | Online Training Course | Angular JS Training in Bangalore | Certification | Online Training Course | Angular JS Training in Hyderabad | Certification | Online Training Course | Angular JS Training in Coimbatore | Certification | Online Training Course | Angular JS Training | Certification | Angular JS Online Training Course

surya said...

This is an awesome post. Really very informative and creative contents.
Angular JS Training in Chennai | Certification | Online Training Course | Angular JS Training in Bangalore | Certification | Online Training Course | Angular JS Training in Hyderabad | Certification | Online Training Course | Angular JS Training in Coimbatore | Certification | Online Training Course | Angular JS Training | Certification | Angular JS Online Training Course

Anonymous said...

Потрясающе интересныеда еще поразительно точные онлайн гадания для познания вашего будущего: это то, что вы увидите на страницах нашего сайта. Гадание таро расклады является самым приятным и простым вариантом для извлечения необходимых знаний из ментального поля планеты Земля.

balraj jain said...

Vidyasthali Group of Institutions was founded by an eminent group of academics and industry leaders who are masters of the top significant achievements and accomplishments. Vidyasthali is a reputed B-school in Jaipur.
vidyasthali institute of technology science&managment
best techonology science and management institute in jaipur
courses in vidyasthali group of institute
no 1 technology science & management college in jaipur
best management
vitsm
vidyasthali institute of technology science and managment
techonlogy science&management college near me,
best technology
best management
VITSM teaching staff
vitsm courses
top science college
best science colleges in jaipur
best science college in jaipur
vitsm fees structure
vitsm fee structure
vitsm result
vitsm result

Anonymous said...

Невероятно потрясающиеи к тому же поразительно правдивые интернет гадания для уточнении загадывания своего будущего - это исключительно то, с чем вы познакомитесь на сайте гаданий. Гадание на беременность онлайн оказывается наиболее быстрым и действенным способом для получения жизненных знаний из информационного поля земли.

Anonymous said...

Видеокомпьютерные игрушки содержат в себе свыше двадцати жанров. На этом сайте любой желающий сможет без каких-либо заморочек скачать игру про войну на слабый пк. Выбирайте требуемую игру по году издания, к примеру, игрушки про завоевание новых земель. На портале представлены игры с качественным мультиязычным переводом. Сторонники игры издают интересные сборки. Де-факто все лицензионные игры давно возможно закачать на qBittorrent. Не тратьте время впустую - загружайте быстро игрушки на высокоскоростном сайте торрента. Компьютерный мир на любого клиента и авантюры на десятки часов. Вредоносного софта нет - скачивайте безвредно КьюТоррентом лишь на Games9.ru.

Anonymous said...

It took me a long time to figure out what I was reading, but eventually everything fell into place. In General, I recently made a new website, a great service, here it ishttps://youtube-to-mp3-converter.com/. Youtube 2 mp3 Converter is a unique service that allows you to download music to your iPhone for free.

Anonymous said...

Бесчисленное количество развлечений на ПК делается ежегодно. В наибольшей степени защищенным путем заполучить релизнутую игру считается https://games9.ru/load/fps/. Знать толк в типах ПС игр не так просто в результате огромного их объема. Загружая игрушки с Torrent вы получите значительный уровень устойчивости. Мошенники попробуют использовать простодушие клиентов и прикладывать спам-программы. Закачка торрента представляется не сложной процедурой, доступной к тому же для юных пользователей.

Anonymous said...

Количество композиций для скачки безгранично. Именно тут меломаны могут загрузить ТОП лучших востребованных песен этого времени. Уникальная мп3 коллекция имеет в составе треки наиболее известных музыкантов в мире. С этого времени нет нужды формировать личный трек-лист по крошкам из сетки. Хиты лета 2020 скачать – каждый найдет на сайте mp3smak.ru крутую музыку. Определенная пора года представлена конкретными песнями, некие желательно загрузить на собственный телефон.

Anonymous said...

Любой желает узнать свою судьбу и видит определенные методы предсказания будущего по максимуму результативными. Пасьянс гадание онлайн на любовь - шанс предсказать приближающиеся события постоянно привлекал род человеческий. Гадание дает просмотреть, что вас подстерегает в предстоящем времени.

Anonymous said...

Снабжение для коммунальной сферы по максимально доступным ценам. Многочисленные жилищные объединения встают перед проблемой покупки различных контейнеров. Предприятие Снаб Топ посодействует вам выбрать тут пластиковые мусорные контейнеры краснодар по особенно выгодной цене без подводных камней.