Improved thread scheduling

Less repeated code and less GC errors.