JobDatabase: fix multithreading issues
The implementation of the next() query was wrong and could cause read failures (as shown by the newly added tests, if run with 300+ jobs).
The new implementation can also cause some reads to fail, but this is handled and next() can be just called again.