|
@@ -4,6 +4,7 @@ import hello.domain.World;
|
|
|
|
|
|
import java.util.Arrays;
|
|
|
import java.util.Comparator;
|
|
|
+import java.util.concurrent.atomic.AtomicInteger;
|
|
|
import java.util.concurrent.Callable;
|
|
|
import java.util.concurrent.ExecutionException;
|
|
|
import java.util.concurrent.Future;
|
|
@@ -56,9 +57,11 @@ public class WorldResource {
|
|
|
Session session = emf.createEntityManager().unwrap(Session.class);
|
|
|
session.setDefaultReadOnly(true);
|
|
|
try {
|
|
|
- for (int i = 0; i < queries; i++) {
|
|
|
- worlds[i] = (World) session.byId(World.class).load(randomWorld());
|
|
|
- }
|
|
|
+ //Pick unique random numbers
|
|
|
+ final AtomicInteger i = new AtomicInteger(0);
|
|
|
+ ThreadLocalRandom.current().ints(1, 10001).distinct().limit(queries).forEach(
|
|
|
+ (randomValue)->worlds[i.getAndAdd(1)] = (World) session.byId(World.class).load(randomValue)
|
|
|
+ );
|
|
|
return worlds;
|
|
|
} finally {
|
|
|
session.close();
|
|
@@ -85,13 +88,16 @@ public class WorldResource {
|
|
|
// in the configuration file
|
|
|
|
|
|
// 1. Read and update the entities from the DB
|
|
|
- for (int i = 0; i < queries; i++) {
|
|
|
- final World world = (World) session.byId(World.class).load(randomWorld());
|
|
|
- world.setRandomNumber(randomWorld());
|
|
|
- worlds[i] = world;
|
|
|
- }
|
|
|
-
|
|
|
- // 2. Sort the array to prevent transaction deadlock in the DB
|
|
|
+ final AtomicInteger ii = new AtomicInteger(0);
|
|
|
+ ThreadLocalRandom.current().ints(1, 10001).distinct().limit(queries).forEach(
|
|
|
+ (randomValue)->{
|
|
|
+ final World world = (World) session.byId(World.class).load(randomValue);
|
|
|
+ world.setRandomNumber(randomWorld());
|
|
|
+ worlds[ii.getAndAdd(1)]=world;
|
|
|
+ }
|
|
|
+ );
|
|
|
+
|
|
|
+ // 2. Sort the array to prevent transaction deadlock in the DB
|
|
|
Arrays.sort(worlds, Comparator.comparingInt(World::getId));
|
|
|
|
|
|
// 3. Actually save the entities
|