Boxing with Java

A bug was recently identified in a project I’m working on. Check the following code out:

Naughty naughty. I had done a very silly thing and used == to test equality of Integer objects! As we all know, when comparing equality on objects we should be using .equals(). However, this bug was intermittent. Comparing Integer to Integer like this works. Sometimes.

Let’s see what’s happening here:

First, we need to check what happens when we compare two ints:

Output:

Comparing unboxed 10 to 10
true

This makes sense. A is of an equal value to B.

Now let’s compare two Integer objects:

Output:

Comparing boxed 10 to 10
true

Great – we have equal values, right? Where’s the problem?

Here:

Change the values to some high number. Let’s say 1000:

Comparing boxed 1000 to 1000
false

Depending on your particular implementation of Java, the value required to trigger this behaviour may vary, but in my case, the equality result changes when a and b are set to 128.

UPDATE: As pointed out by Edwin Nathaniel in the comments, any Java implementation should cache Integer objects according to the following:

“Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS.
The cache is initialized on first usage. The size of the cache may be controlled by the -XX:AutoBoxCacheMax= option.”

This means that the Integer cache limits are configuration dependent, not implementation dependent. Props to Edwin (who also has a rather delicious looking blog) for schooling me on this subject!

Let’s change the code a little and turn our primitives into objects when we do the comparison (this is what’s already happening, by the way, it’s just a little less obvious the way I’ve illustrated it here):

Output:

Comparing boxed 1000 to 1000
false

In case you missed it, the checkBoxed method is expecting Integer objects, not primitives. We pass it primitives, and autoboxing is applied by the compiler, cramming our primitives into objects and giving us a nasty surprise.

Autoboxing allows developers to forget about the tedium of converting between primitives and objects, resulting in tidier code and, in this particular case, more headaches. You don’t gain anything performance-wise as the compiler will still generate the ‘boxing’ code, but it does tend to make life more convenient.

If you want to avoid this problem, you can do the following:

Comparing these two using the checkBoxed method will always output ‘false’, because you are explicitly creating two different objects. The fact that they represent the same value is irrelevant to the JVM. It sees two different objects and tells you so.

You can also use the following comparison instead:

Perhaps the best way to avoid this problem is to be consistent and enforce the rule across your team. Keep in mind that you don’t always know how Bill has implemented his bit of code, and he doesn’t know how you’ve implemented yours – so decide how you’re going to deal with this potential pitfall and make sure you both keep it in mind. Unfortunately for me, I’m the only person working on this project so I can’t blame somebody else.

It’s worth pointing out that autoboxing is applied to all primitive wrapper types, not just Integers, so it is an important feature to keep in mind.

If you use Eclipse, turn on the following handy feature to help you find where autoboxing / unboxing could occur:

This will highlight your code with the following warning:

This is one of those features added to make your life easier. Unfortunately, people new to Java, or idiots like me, may not understand what is happening here and could be writing code laden with boxing issues. Only a good set of coding standards, and a decent code-review process, will help you catch these issues before they become a real problem out in the field.

Acting on ACTA

Humans share things. It is one of the defining traits of our species, and it is something that many people overlook when waxing philosophical about what separates us from the animals. We give things to each other – often in exchange for other things, but often because we get joy from it. We want everyone to like what we like. Some might say we need to feel that others enjoy the same things we do. The internet has allowed people to share who they are with the world like no other medium in humanity’s history. The term ‘Social Media’ and the industry which has sprung up around it is only possible at all because humans love sharing.

Given this innate desire to share, it is incredibly disheartening to see constant attacks on our very ability to do so through the world wide web, often under the guise of preventing piracy or protecting children. The latest round of attacks, SOPA, PIPA and ACTA to name a few, are by and large the result of increasing pressure from entertainment industry lobbyists hell-bent on preserving what many see as outdated business models which are incompatible with the modern world. It is not my intention here to focus on the campaigns already in progress to fend off these attacks, but please at least visit the Wiki links and read the criticism sections.

As both a musician and a software developer, the ability to share is of paramount importance to me. From my perspective as a musician, I want to be able to listen to other musicians create music. I want to be able to share my own music with others, and, if I choose to ever sell music in the future, I want to be able to do so in a way that means customers have the simplest possible way to buy, download, and listen to my tracks. I am confident that many artists feel the same. The multitude of services on the internet which allow artists – be they musicians, directors, writers, or photographers – is astounding, and has opened the door for new businesses and independents like never before. The barrier to entry is now the cost of an internet connection, and your market is the world. This is amazing and it is disappointing that this concept is being touted as dangerous to businesses and jobs when the reality is that the entertainment industry is in a better position than ever before. The same old lines are trotted out again and again, and the traditional media keeps ignoring the point: The entertainment industry is not dying. It is growing faster than it ever has. There is more content being produced and sold globally than at any point in the past. The reason for aggressive attacks like SOPA and ACTA is that the big players are, to put it simply, dinosaurs. Changing their entire approach to selling entertainment is going to be expensive, and they are simply not wired to think of new approaches using the internet. Every single attempt at protecting intellectual property in the digital age has followed the same tactic, and it goes like this:

Buy this, but never, ever share it.

Digital media is unique in that ‘sharing’ generally involves creating a copy – and this is understandably worrying for an industry whose entire business model is based on selling as many copies of the same thing as possible. However, Apple’s successes with iTunes, and the growing consensus that a subscription based model such as Netflix and Spotify is the ‘new way’ have illustrated that there is room for experimentation. There are new models that can be tried. To quote my favourite film, which I have paid numerous times to watch:

Life, and the entertainment industry, will find a way.

Whether those new models are good or bad for content producers is not what I’m concerned with at the moment. I’m happy enough that there is an alternative to the traditional methods. I may not be in the future – but for now, I am relatively comfortable with the idea of paying £10 a month for all the music I like. My only major issue with subscription services is that they necessitate a walled garden – which once again places a barrier to entry on the people who produce the content.

As a software developer, I am obviously concerned with anything that has an impact on how I pay my bills – and my overriding concern with things like SOPA, PIPA, and ACTA is that I am being left out of the conversation. I have no issue with businesses wanting to stop people stealing their products (I am not interested in the debate about whether file-sharing can be called ‘stealing’ for now). A few years ago, when there was no such thing as Spotify, my approach was ‘they’ll figure it out eventually, or they’ll fail. That’s how capitalism works’. Unfortunately (and this is difficult for me to say), the Libertarians are right in this case. What they complain about – the inevitable collusion of corporations and governments to the benefit of a few and the detriment of many – is happening right now. ACTA is a trade agreement that has been organised behind closed doors and pushed in front of our politicians without any discussion with the rest of us having taken place. I want my concerns addressed, because I am terrified that a success for the entertainment industry here will lead to an onslaught against small or independent businesses who are trying new ideas and technology – thereby crippling competition and ensuring that only a few gatekeepers to content remain.

If ACTA and the like are allowed to succeed – then it won’t be long until we stop seeing things like this everywhere:

The argument will be that any website which allows user created content has the potential to be used for illegal file-sharing, and that this is A Very Bad Thing and should be prevented at all costs. Your ability to share things you create or love will disappear, and we will all be worse off for it.

If you’ve ever done anything like this:

then you need to be worried about things like ACTA, and you need to start making a noise about it. I have written to several MPs and MEPs over the last few weeks, and only one so far has had the courtesy to respond – Arlene McCarthy, MEP. A few people have asked me to post her comments on-line, so here’s the full e-mail response:

Dear Mr Halligan

 

Thank you for your recent correspondence regarding the Anti Counterfeiting Trade Agreement (ACTA) between the European Union, Australia, Canada, Japan, Korea, Mexico, Morocco, New Zealand, Singapore, Switzerland and the US.

 

The European Parliament has a formal role in the eventual approval or rejection of this Agreement. The negotiations concluded in November 2010, and each negotiating party is now in the process of ratifying and signing the Agreement. In the EU this requires agreement from the Council of Ministers (made up of the 27 Member States) and the European Parliament. On Thursday 26 January 2012 twenty-two Member States (including the UK) signed the agreement.

 

The European Parliament will now draft a report to recommend whether or not Parliament should give its approval to the Agreement, and this will be done by the International Trade committee. This is expected to begin next month. Parliament’s political leverage over the European Commission has therefore been substantial given that the Agreement cannot be ratified without Parliament’s approval.

 

In addition to its legislative role, Parliament monitored the negotiations throughout the 11 rounds and adopted Resolutions highlighting our priorities to the Commission. In March 2010 Labour Euro MPs co-authored a Resolution where we proposed and successfully incorporated several points on transparency and civil liberties into the Resolutions.

 

Firstly we made it clear that the European Commission – as the EU’s negotiator in ACTA – needed to put pressure on the other participants to open up the negotiations to public scrutiny through the publication of a draft negotiating text.

 

Secondly we stressed that ACTA must target only commercial and not individual counterfeiters. In our opinion the need to address serious counterfeiting should not lead to any erosion of civil liberties. My colleagues and I do not support so called border measures such as the searching by Customs of travellers’ iPods or laptops for illegally downloaded files.

 

Finally we stated that ACTA should not extend beyond the European Community ‘acquis’ or, in other words, no new intellectual property legislation should be created as a result. The European Union is a signatory to various international Agreements on intellectual property such as the World Trade Organisation’s Agreement on Trade Related Intellectual Property Rights (TRIPS). It is important for the European Parliamentary Labour Party that ACTA is consistent with TRIPS and other existing Agreements on Intellectual Property.

 

I and my colleagues share the frustrations of many constituents who believed the negotiations should have been conducted in a more transparent manner. The European Parliament put significant pressure on the European Commission during the negotiations to increase transparency. The Commission was successful in persuading other ACTA negotiating partners to release a consolidated negotiating text. While Parliament continued to call for the further release of all negotiating texts with individual country positions, we were disappointed that further opening up of the negotiations could not be agreed by all negotiating parties.

 

Please be assured that the Parliament’s commitment to transparency also applies to our consideration of the ACTA agreement in the International Trade committee. Once the Parliament analysis and discussions in Parliament begin, debates and considerations of the text will be fully open to the public and streamed live on the European Parliament website.

 

Thank you again for writing to me on this issue. Please be assured that my colleagues and I will analyse the text of the Agreement very carefully before the European Parliament gives its assent.

 

Yours sincerely

 

Arlene McCarthy

Member of the European Parliament

 

Make of her response what you will, but I’d at least like to thank Arlene for having the decency to respond. I am not yet pacified or convinced that ACTA will not be a terrible thing for the internet, but I am a little happier knowing that our MEPs already have concerns.

My goal is to encourage people, whatever opinion they may have on ACTA (and other similar bills and agreements), to talk about it. It’s not just me who feels left out of the conversation. Demand that your representatives start representing you and addressing your concerns. If we don’t stand up now in defence of the ability to share, to create freely, and to discover new and amazing things, then who will? The end-game for the big players is to turn the internet into a passive medium, so that you can only see what they let you see, and they will only let you see what you pay them for. It is the ultimate walled garden, and any competition or innovation will be stamped out and destroyed.