Backport of https://github.com/hazelcast/hazelcast/pull/1386

https://github.com/hazelcast/hazelcast/pull/1386
Slightly different code that the original change, hopefully it's more readable.