Thursday, March 5, 2015

Trying to prove that WeakMap is actually weak

I don't have a ton of experience with weak maps, but I would expect the following to work:
// File: example.js
var key = {};
var indirectReference = {};
indirectReference['key'] = (function() { var m = {}; m['foo'] = 'bar'; return m; })();
var map = new WeakMap();

map.set(key, indirectReference['key']);
console.log('Has key after setting value: %s', map.has(key));

delete indirectReference['key'];
console.log('Has key after deleting value: %s', map.has(key));

global.gc();
console.log('Has key after performing global.gc(): %s', map.has(key));
I downloaded the latest version of io.js (so that I could have a JavaScript runtime with WeakMap and global.gc() and ran it as follows:
./iojs --expose-gc example.js
Here is what I see:
Has key after setting value: true
Has key after deleting value: true
Has key after performing global.gc(): true
Despite my best efforts, I can't seem to get WeakMap to give up the value that is mapped to key. Am I doing it wrong? Obviously I'm making some assumptions here, so I'm curious where I'm off.

Ultimately, I would like to be able to use WeakMap to write some tests to ensure certain objects get garbage collected and don't leak memory.

27 comments:

  1. In the JS weakmap implementation, the keys are held by weak references, not the values? So, like, if you want to associate an Element with some Object, but you want that Object to go away if the Element goes away.

    (I think the API is actually specifically designed to not allow the use case you have in mind, where you're monitoring the gc, but I don't know the background reasoning behind that)

    ReplyDelete
  2. Google Ephemeron. That's what a WeakMap is.

    It's just a way of "attaching" hidden properties to the keys. When you have the map and the key you can get hold of a property, the value. When either the key or the map are GCed, the value will not be kept alive any more.

    You could use ES6 symbols for the same thing, where the symbol plays the role of the WeakMap, and you use the symbol to put a property on the key:

    // Solution with WeakMap. If either the map or the key are unreachable then
    // the value is also unreachable (unless it's reachable some other way).
    var map = new WeakMap();
    map[key] = value

    // Solution with Symbol. If the key becomes unreachable then the value can
    // become unreachable, but if you have the key you can always get the symbol
    // using getOwnPropertySymbols, so the value cannot be collected unless the
    // key is collected.
    var map = Symbol(); // Creates a new primitive symbol object
    key[symbol] = value;

    You were probably expecting WeakMap to behave like WeakReference from Java. That would mean that the JS program could detect when a GC had taken place, which would inevitably introduce compatibility issues between the JS engines. This is probably one of the reasons it hasn't happened.

    ReplyDelete
  3. Nick and Erik, yep, you're right, I was assuming WeakMap was going to behave like WeakReference from Java, so that's the source of my problems.

    I suspect the only way to do what I want is to explicitly expose this functionality from V8/Node. Obviously that would introduce an incompatibility across JS engines, but my intention is to use it only for memory leak tests, so I could live with that.

    ReplyDelete
  4. The concept applies in a variety of disciplines,[5] with both the nature of the evidence or justification and the criteria for sufficiency being area-dependent. In the area of oral and written communication such as conversation, dialog. Dubai Mobile App Developer

    ReplyDelete
  5. "Nice Blog!!
    Norton login is one of the easiest platform that allows you to manage products download Norton antivirus and protect your device from online threats.
    Norton Account
    Norton Setup"

    ReplyDelete
  6. Good Post!!
    AOL Mail serve all the emails in your account, with aol email will get all updates on your mails promptly by creating aol account.
    AOL Account
    AOL Gold Download

    ReplyDelete
  7. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai

    Python Training in Chennai Python Training in Chennai The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

    ReplyDelete
  8. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Hi! We are ro plant supplier Great points made up above! And whole house water filter dubai thanks… I think this is one of the most important information for me. And i am glad reading your article. But should remark on few general things…

    ReplyDelete
  9. If you are interested to learn
    Roku.com/link create account guidelines, let me suggest an article titled, How to create Roku account. Read the post a few days back. I’m impressed after reading. Spend your free time reading the article. Also, create your Roku account to proceed with Roku.com/link activation. Also do not forget to share the post on your social media profile
    Let us activate Roku using Roku account and stream the entertaining Roku channels

    ReplyDelete
  10. Cara mengecilkan perut Sugar and carbohydrates are the highest sources of saturated fat. So by reducing sugar and carbohydrates, the calories that enter the body shrink. Ngobrol Sehat It is advisable to swap sugar and carbohydrates for foods that are high in energy and low in fat. Ngobrol Sehat Having a small belly and thighs and nice as the desire of the majority of women. For those of you who have a large belly and thigh size, of course you want to have a smaller size to support your performance. Ngobrol Sehat Here's how to reduce the stomach and thighs naturally.
    Hidup Sehat | Hidup Sehat

    ReplyDelete
  11. The WeakMap object is a collection of value pairs in which the keys and If you want to have a list of keys. you should use a MapKinemaster Gold

    ReplyDelete
  12. This article is really very amazing, from this post we can get more information about 6 reasons you need to unplug from technology. It was my dream to become a scientist and invent something better for our world and I am addicted to technology. It is 100% right that TV computer, smartphones become an unbreakable part of our daily life and it is the main source of our entertainment. Nobody can't compromise with these devices. The promotion of these devices depends on advertisement because it has always been the key tool to increase your product popularity. Advertising becomes a business and it has long remained unchanged. If anyone wants to zoek softwareontwikkelaar you can see more details on this. Advertising had to adjust to a new market with the internet help of software development. Do you know that the specific set of techniques and methods to boost your product through digital media?

    ReplyDelete
  13. I swear! Weakmap is taken into its literal sense. Lately; I have been busy with my studies that I don’t find time for anything else, even now I was just taking assignment writing services from https://bestassignmentwriter.co.uk/. But I felt the need to give my honest opinion about the weak map.

    ReplyDelete
  14. When I read an article on this topic, 메가슬롯 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

    ReplyDelete
  15. RockStar Jackets is incredibly pleased to announce ourselves as the most dependable manufacturers and exporters of a variety of products comprising of Leather Garments.
    Nicolas Cage Vista Theatre Color Out Of Space Premiere Steel Nail Studded Leather Jacket
    Steve & Barry's Ohio State Buckeyes Letterman Leather Jacket

    ReplyDelete
  16. We are providing chat for creators, so all creators are able to chat with each others.
    How to create an NFT

    ReplyDelete
  17. Panther Jackets Is A Leather Jackets WareHouse Providing Jackets In USA, Canada and UK.With Free Shipping
    Gucci Bomber Style Black Leather Jacket
    San Francisco Dons Varsity Wool Jacket

    ReplyDelete
  18. Health is more important in our life other then any thing, all we should care about the health, weight lose is very important factor on weight lose we all need to take care of our weight.
    facts about weight loss
    fun facts about weight loss

    ReplyDelete
  19. RightJackets is the best place for you to get the most original custom made products and more.We have the biggest range of a variety of products.
    Perks And Mini Mutagenesis Black Bomber Jacket
    Gender Fluid Mr.Hyde Bomber Yellow Satin Jacket

    ReplyDelete
  20. We Introduce Bomber Jacket In United State With Premium Quality Leather Used In Making Leather Jackets

    ReplyDelete
  21. love IGI 3. The game's features that you'll love after downloading include Improved Artificial Intelligence. More improved graphics, better sound as well as SFX Music. Game Weapons are new. Game plots are engaging. There are new features in the IGI 3 Game Control Panel and missions include new objectsMetro Exodus Download Pc Game Free andc clip studio paint key and stellar data recovery standard serial key with spotify premium free pc also manycam activation code and true Korean horror films due imyfone registration code so metasploit pro activation key and avs video editor activation key as o avid media composer ultimate crackIGI 3. The game's features that you'll love after downloading include Improved Artificial Intelligence. More improved graphics, better sound as well as SFX Music. Game Weapons are new. Game plots are engaging. There are new features in the IGI 3 Game Control Panel and missions include new objects.

    ReplyDelete
  22. Panther Jackets Is A Leather Jackets WareHouse Providing Jackets In USA, Canada and UK.With Free Shipping.

    def jam varsity jacket

    ReplyDelete