Improved Java implementation