SnowflakeKeyGenerateAlgorithm implements KeyGenerateAlgorithm { @Override public void init() { workerId = getWorkerId(); maxVibrationOffset = getMaxVibrationOffset(); maxTolerateTimeDifferenceMilliseconds = getMaxTolerateTimeDifferenceMilliseconds(); }  @Override void init(); @Override synchronized Comparable<?> generateKey(); @Override String getType(); static final long EPOCH; }
@Test public void assertGenerateKeyWithMultipleThreads() throws ExecutionException, InterruptedException { int threadNumber = Runtime.getRuntime().availableProcessors() << 1; ExecutorService executor = Executors.newFixedThreadPool(threadNumber); int taskNumber = threadNumber << 2; SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm(); keyGenerateAlgorithm.setProps(new Properties()); keyGenerateAlgorithm.init(); Set<Comparable<?>> actual = new HashSet<>(taskNumber, 1); for (int i = 0; i < taskNumber; i++) { actual.add(executor.submit((Callable<Comparable<?>>) keyGenerateAlgorithm::generateKey).get()); } assertThat(actual.size(), is(taskNumber)); }
@Test public void assertSetWorkerIdSuccess() throws NoSuchFieldException, IllegalAccessException { SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm(); Properties props = new Properties(); props.setProperty("worker-id", String.valueOf(1L)); keyGenerateAlgorithm.setProps(props); keyGenerateAlgorithm.init(); Field field = keyGenerateAlgorithm.getClass().getDeclaredField("props"); field.setAccessible(true); assertThat(((Properties) field.get(keyGenerateAlgorithm)).getProperty("worker-id"), is("1")); }
@Test public void assertSetMaxTolerateTimeDifferenceMilliseconds() throws NoSuchFieldException, IllegalAccessException { SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm(); Properties props = new Properties(); props.setProperty("max-tolerate-time-difference-milliseconds", String.valueOf(1)); keyGenerateAlgorithm.setProps(props); keyGenerateAlgorithm.init(); Field field = keyGenerateAlgorithm.getClass().getDeclaredField("props"); field.setAccessible(true); assertThat(((Properties) field.get(keyGenerateAlgorithm)).getProperty("max-tolerate-time-difference-milliseconds"), is("1")); }