Skip to content

Commit

Permalink
[java] 高并发 System.currentMills()
Browse files Browse the repository at this point in the history
  • Loading branch information
SunYufei committed Sep 30, 2024
1 parent 7b90c34 commit bcc64d3
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
29 changes: 29 additions & 0 deletions java/src/main/java/clock/SystemClock.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package clock;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
* 高并发下的 System.currentMills()
*/
public final class SystemClock {
private final AtomicLong now;

public static long now() {
return InstanceHolder.INSTANCE.now.get();
}

private static class InstanceHolder {
private static final SystemClock INSTANCE = new SystemClock();
}

private SystemClock() {
this.now = new AtomicLong(System.currentTimeMillis());
Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}).scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), 1L, 1L, TimeUnit.MILLISECONDS);
}
}
45 changes: 45 additions & 0 deletions java/src/test/java/clock/SystemClockTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package clock;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SystemClockTest {
@Test
public void sequence() throws InterruptedException {
long first = SystemClock.now();
Thread.sleep(100);
long second = SystemClock.now();
long diff = second - first;
System.out.println("first: " + first + " second: " + second + " diff: " + diff);
Assertions.assertTrue(diff >= 100);
}

@Test
public void parallel() throws InterruptedException {
int threads = 50;
CyclicBarrier barrier = new CyclicBarrier(threads);
CountDownLatch countDownLatch = new CountDownLatch(threads);
try (ExecutorService executor = Executors.newFixedThreadPool(threads)) {
for (int i = 0; i < threads; i++) {
executor.submit(() -> {
try {
barrier.await();
//
System.out.println(SystemClock.now());
//
countDownLatch.countDown();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
});
}
countDownLatch.await();
}
}
}

0 comments on commit bcc64d3

Please sign in to comment.