A ConsString Gotcha
Jim Laskey (Oracle)
james.laskey at oracle.com
Sun Oct 13 09:28:56 PDT 2013
The complication there is that every time you have an Object argument/field you would have to have an if instanceof ConsString cast String sequence, which is a huge performance hit. ConsString was introduced to significantly improve performance (high frequency operation), so it's a bit of a dilemma. The team has debated this several times. It might be better in the long run to be able to properly declare the HashMap with something like;
var StringHashMap = Java.type("java.util.HashMap<java.lang.String, java.lang.Object>");
or even better
var JObject = Java.type("java.lang.Object");
var JString = Java.type("java.lang.String");
var StringHashMap = Java.type("java.util.HashMap", JString, JObject);
Just my 2 cents.
Cheers,
-- Jim
On 2013-10-13, at 11:33 AM, Tal Liron <tal.liron at threecrickets.com> wrote:
> ConsString can cause some hard-to-find bugs when interacting with Java classes.
>
> Consider this code:
>
> var map = new java.util.HashMap
>
> var prefix = 'a'
> var key = prefix + 'b'
>
> map.put(key, 'hello')
>
> print(map.get(key) + '\n')
> print(map.get('ab') + '\n')
>
> It will output 'hello' and then 'null'. The reason is that key is a ConsString. See for yourself:
>
> for (var i = map.keySet().iterator(); i.hasNext(); ) {
> print(i.next().getClass() + '\n')
> }
>
> This can cause some very hard-to-find bugs. I know too well. :). I'm not sure how best to deal with it, but here are some suggestions.
>
> 1. Document it in the user guide, possibly with the simple example I gave above. I expect that many of these bugs will happen when dealing with generic classes, such as those in java.util. The workaround for the example above:
>
> var key = String(prefix + 'b')
>
> But that's hardly intuitively necessary.
>
> 2. It may be a good idea for Nashorn to always coerce ConsString into String when interacting with Java, even if the method signature expects an Object.
>
> The one downside I can think of is that it will make it impossible to offer special handling for ConsString in Java classes. This would seem, however, to be quite a rare usage and may not be worth the potential for awful bugs.
>
> What do you think?
>
>
More information about the nashorn-dev
mailing list