Guest User

Untitled

a guest
Dec 17th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. import org.cactoos.Scalar;
  2. import org.cactoos.scalar.SyncScalar;
  3. import org.cactoos.scalar.True;
  4. import org.junit.Test;
  5.  
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.atomic.AtomicInteger;
  9. import java.util.concurrent.atomic.AtomicLong;
  10.  
  11. public final class SyncTest {
  12.  
  13. final class DoubleCheckScalar<T> implements Scalar<T> {
  14. private final Scalar<T> origin;
  15. private volatile T value;
  16.  
  17. DoubleCheckScalar(Scalar<T> origin) {
  18. this.origin = origin;
  19. }
  20.  
  21. @Override
  22. public T value() throws Exception {
  23. if (value == null) {
  24. synchronized (this) {
  25. if (value == null) {
  26. value = origin.value();
  27. }
  28. }
  29. }
  30. return value;
  31. }
  32. }
  33.  
  34. @Test
  35. public void syncTest() throws Exception {
  36. final Scalar<Boolean> target = new SyncScalar<>(new True());
  37. final long time = test(target);
  38. System.out.printf("SyncScalar: %d ns\n", time);
  39. }
  40.  
  41. @Test
  42. public void doubleCheckTest() throws Exception {
  43. final Scalar<Boolean> target = new DoubleCheckScalar<>(new True());
  44. final long time = test(target);
  45. System.out.printf("DoubleCheckScalar: %d ns\n", time);
  46. }
  47.  
  48. /*
  49. * My results:
  50. * DoubleCheckScalar: 307_492_591 ns
  51. * SyncScalar: 2_045_077_027 ns
  52. */
  53.  
  54. private static long test(Scalar<?> target) throws Exception {
  55. // warm up
  56. for (int i = 0; i < 1000; i++) {
  57. target.value();
  58. }
  59.  
  60. final int iterations = 10_000_000;
  61. AtomicInteger pending = new AtomicInteger(iterations);
  62. final ExecutorService pool = Executors.newFixedThreadPool(20);
  63. //test
  64. AtomicLong sum = new AtomicLong();
  65. for (int i = 0; i < iterations; i++) {
  66. pool.submit(() -> {
  67. final long start = System.nanoTime();
  68. try {
  69. target.value();
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. final long end = System.nanoTime();
  74. final long time = end - start;
  75. sum.addAndGet(time);
  76. pending.decrementAndGet();
  77. });
  78.  
  79. }
  80. while (pending.get() > 0) {
  81. Thread.sleep(100);
  82. }
  83. pool.shutdown();
  84. return sum.get();
  85. }
  86. }
Add Comment
Please, Sign In to add comment