Skip to content

Commit

Permalink
optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
ponfee committed Feb 21, 2024
1 parent 54638eb commit 3d323b2
Show file tree
Hide file tree
Showing 18 changed files with 190 additions and 164 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public interface IntValueEnum<T extends Enum<T> & IntValueEnum<T>> {
String desc();

/**
* Returns IntValueEnum instance is equals Integer value
* Returns this IntValueEnum instance value is equals Integer value
*
* @param value the Integer value
* @return {@code true} if equals
Expand All @@ -54,7 +54,7 @@ default boolean equalsValue(Integer value) {
}

/**
* Returns IntValueEnum instance is equals int value
* Returns this IntValueEnum instance value is equals int value
*
* @param value the int value
* @return {@code true} if equals
Expand All @@ -63,19 +63,16 @@ default boolean equalsValue(int value) {
return value == value();
}

static <T extends Enum<T> & IntValueEnum<T>> T of(Class<T> type, Integer value) {
static <T extends Enum<T> & IntValueEnum<T>> T of(Class<T> type, int value) {
if (type == null) {
throw new IllegalArgumentException("Enum int type cannot be null: " + type);
}
if (value == null) {
throw new IllegalArgumentException("Enum int value cannot be null.");
throw new IllegalArgumentException("Enum class cannot be null.");
}
for (T e : type.getEnumConstants()) {
if (e.value() == value) {
return e;
}
}
throw new IllegalArgumentException("Invalid enum int value: " + value);
throw new IllegalArgumentException("Invalid enum " + type + " int value: " + value);
}

static List<IntValueDesc> values(Class<? extends IntValueEnum<?>> clazz) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,35 +31,24 @@ public final class Threads {

private static final Logger LOG = LoggerFactory.getLogger(Threads.class);

/**
* New thread
*
* @param run the runnable
* @return thread instance
*/
public static Thread newThread(Runnable run) {
Thread thread = new Thread(run);
String callerClassName = Thread.currentThread().getStackTrace()[2].getClassName();
thread.setName(callerClassName.substring(callerClassName.lastIndexOf(".") + 1));
thread.setUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler(LOG));
return thread;
}

/**
* New thread
*
* @param name the thread name
* @param daemon the daemon
* @param priority the priority
* @param run the runnable
* @param logger the uncaught exception handler logger
* @return thread instance
*/
public static Thread newThread(String name, boolean daemon, int priority, Runnable run) {
public static Thread newThread(String name, boolean daemon, int priority, Runnable run, Logger logger) {
Thread thread = new Thread(run);
thread.setName(name);
thread.setDaemon(daemon);
thread.setPriority(priority);
thread.setUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler(LOG));
if (logger != null) {
thread.setUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler(logger));
}
return thread;
}

Expand Down Expand Up @@ -146,8 +135,6 @@ private static void stopThread(Thread thread, long joinMillis, boolean fromAsync
return;
}

thread.interrupt();

if (Thread.currentThread() == thread) {
if (fromAsync) {
LOG.warn("Call stop on self thread: {}\n{}", thread.getName(), getStackTrace());
Expand All @@ -158,6 +145,9 @@ private static void stopThread(Thread thread, long joinMillis, boolean fromAsync
return;
}

// do interrupt
thread.interrupt();

// wait joined
if (joinMillis > 0) {
try {
Expand All @@ -181,7 +171,6 @@ private static void stopThread(Thread thread) {
return;
}

thread.interrupt();
try {
// 调用后,thread中正在执行的run方法内部会抛出java.lang.ThreadDeath异常
// 如果在run方法内用 try{...} catch(Throwable e){} 捕获住,则线程不会停止执行
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public static Set<String> fieldDiff(Class<?> a, Class<?> b) {
*/
public static List<Field> listFields(Class<?> clazz) {
if (clazz.isInterface() || clazz == Object.class) {
return null; // error class args
throw new IllegalArgumentException("Class cannot be interface or Object.class: " + clazz);
}

List<Field> list = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,20 @@
package cn.ponfee.disjob.common.util;

import cn.ponfee.disjob.common.collect.Collects;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.junit.jupiter.api.Test;
import org.mockito.internal.util.collections.Sets;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
* Collects test
Expand Down Expand Up @@ -53,4 +59,44 @@ public void testNewArray() {
assertThat(array2).hasSize(9);
}

private static String test = "xxx";
private static final String STR = "123";

@Test
public void testReflect() throws IllegalAccessException {
// static field
Field f = FieldUtils.getField(CollectsTest.class, "test", true);
assertThat("xxx").isEqualTo(test);
assertThat("xxx").isEqualTo(FieldUtils.readField(f, (Object) null));
FieldUtils.writeField(f, (Object) null, "yyy", true);
assertThat("yyy").isEqualTo(test);
assertThat("yyy").isEqualTo(FieldUtils.readField(f, (Object) null));

// static final field
Field f1 = FieldUtils.getField(CollectsTest.class, "STR", true);
Field f2 = FieldUtils.getField(CollectsTest.class, "STR", true);
assertThat(f1).isSameAs(f1);
assertThat(f1 == f2).isFalse();
assertThat(f1).isNotSameAs(f2); // f1 != f2
assertThat(f1).isEqualTo(f2);

assertThat("123").isEqualTo(STR);
assertThat("123").isEqualTo(FieldUtils.readField(f1, (Object) null));

assertThatThrownBy(() -> FieldUtils.writeField(f1, (Object) null, "abc", true))
.isInstanceOf(IllegalAccessException.class)
.hasMessage("Can not set static final java.lang.String field cn.ponfee.disjob.common.util.CollectsTest.STR to java.lang.String");

Fields.put(CollectsTest.class, f1, "abc");
assertThat("123").isEqualTo(STR); // 编译时直接替换为`123`
assertThat("abc").isEqualTo(FieldUtils.readField(f1, (Object) null));

Method m1 = MethodUtils.getMatchingMethod(ClassUtils.class, "decodeURL", URL.class);
Method m2 = MethodUtils.getMatchingMethod(ClassUtils.class, "decodeURL", URL.class);
assertThat(m1).isSameAs(m1);
assertThat(m1 == m2).isFalse();
assertThat(m1).isNotSameAs(m2);
assertThat(m1).isEqualTo(m2);
}

}
6 changes: 0 additions & 6 deletions disjob-dispatch/disjob-dispatch-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,6 @@
<artifactId>disjob-registry-api</artifactId>
<version>${project.parent.version}</version>
</dependency>
<!-- round-robin route: RedisAtomicCounter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,11 @@ public final boolean dispatch(List<ExecuteTaskParam> tasks) {
/**
* Assign a worker and dispatch to the assigned worker.
*
* @param tasks the list of execution task param
* @param group the group
* @param tasks the list of execution task param
* @return {@code true} if the first dispatch successful
*/
public final boolean dispatch(List<ExecuteTaskParam> tasks, String group) {
public final boolean dispatch(String group, List<ExecuteTaskParam> tasks) {
if (CollectionUtils.isEmpty(tasks)) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,74 +1,80 @@
/*
* Copyright 2022-2024 Ponfee (http://www.ponfee.cn/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cn.ponfee.disjob.dispatch.route.count;

import cn.ponfee.disjob.common.spring.RedisKeyRenewal;
import cn.ponfee.disjob.core.base.JobConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.function.Function;

/**
* Atomic counter based redis INCRBY command.
*
* @author Ponfee
*/
public class RedisAtomicCounter extends AtomicCounter {

private final String counterRedisKey;
private final StringRedisTemplate stringRedisTemplate;
private final RedisKeyRenewal redisKeyRenewal;

/**
* Function<String, AtomicCounter>: group -> new RedisAtomicCounter(group, stringRedisTemplate)
*
* @param group the group
* @param stringRedisTemplate the StringRedisTemplate
* @see cn.ponfee.disjob.dispatch.route.RoundRobinExecutionRouter#RoundRobinExecutionRouter(Function)
*/
public RedisAtomicCounter(String group,
StringRedisTemplate stringRedisTemplate) {
this.counterRedisKey = JobConstants.DISJOB_KEY_PREFIX + ":route:counter:" + group;
this.stringRedisTemplate = stringRedisTemplate;
this.redisKeyRenewal = new RedisKeyRenewal(stringRedisTemplate, counterRedisKey);
}

@Override
public long get() {
String ret = stringRedisTemplate.opsForValue().get(counterRedisKey);
if (StringUtils.isBlank(ret)) {
return 0;
}
redisKeyRenewal.renewIfNecessary();
return Long.parseLong(ret);
}

@Override
public void set(long newValue) {
stringRedisTemplate.opsForValue().set(counterRedisKey, Long.toString(newValue));
redisKeyRenewal.renewIfNecessary();
}

@Override
public long addAndGet(long delta) {
Long value = stringRedisTemplate.opsForValue().increment(counterRedisKey, delta);
redisKeyRenewal.renewIfNecessary();
return value == null ? 0 : value;
}

}
///*
// * Copyright 2022-2024 Ponfee (http://www.ponfee.cn/)
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * https://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package cn.ponfee.disjob.dispatch.route.count;
//
//import cn.ponfee.disjob.common.spring.RedisKeyRenewal;
//import cn.ponfee.disjob.core.base.JobConstants;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.data.redis.core.StringRedisTemplate;
//
//import java.util.function.Function;
//
///**
// * Atomic counter based redis INCRBY command.
// *
// * <dependency>
// * <groupId>org.springframework.boot</groupId>
// * <artifactId>spring-boot-starter-data-redis</artifactId>
// * <optional>true</optional>
// * </dependency>
// *
// * @author Ponfee
// */
//public class RedisAtomicCounter extends AtomicCounter {
//
// private final String counterRedisKey;
// private final StringRedisTemplate stringRedisTemplate;
// private final RedisKeyRenewal redisKeyRenewal;
//
// /**
// * Function<String, AtomicCounter>: group -> new RedisAtomicCounter(group, stringRedisTemplate)
// *
// * @param group the group
// * @param stringRedisTemplate the StringRedisTemplate
// * @see cn.ponfee.disjob.dispatch.route.RoundRobinExecutionRouter#RoundRobinExecutionRouter(Function)
// */
// public RedisAtomicCounter(String group,
// StringRedisTemplate stringRedisTemplate) {
// this.counterRedisKey = JobConstants.DISJOB_KEY_PREFIX + ":route:counter:" + group;
// this.stringRedisTemplate = stringRedisTemplate;
// this.redisKeyRenewal = new RedisKeyRenewal(stringRedisTemplate, counterRedisKey);
// }
//
// @Override
// public long get() {
// String ret = stringRedisTemplate.opsForValue().get(counterRedisKey);
// if (StringUtils.isBlank(ret)) {
// return 0;
// }
// redisKeyRenewal.renewIfNecessary();
// return Long.parseLong(ret);
// }
//
// @Override
// public void set(long newValue) {
// stringRedisTemplate.opsForValue().set(counterRedisKey, Long.toString(newValue));
// redisKeyRenewal.renewIfNecessary();
// }
//
// @Override
// public long addAndGet(long delta) {
// Long value = stringRedisTemplate.opsForValue().increment(counterRedisKey, delta);
// redisKeyRenewal.renewIfNecessary();
// return value == null ? 0 : value;
// }
//
//}
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ private static CuratorFramework createCuratorFramework(ZkConfig config) throws I
CuratorFramework curatorFramework = builder.build();

curatorFramework.start();
boolean isStarted = curatorFramework.getState().equals(CuratorFrameworkState.STARTED);
boolean isStarted = curatorFramework.getState() == CuratorFrameworkState.STARTED;
Assert.state(isStarted, () -> "Snowflake curator framework not started: " + curatorFramework.getState());
boolean isConnected = curatorFramework.blockUntilConnected(5000, TimeUnit.MILLISECONDS);
Assert.state(isConnected, () -> "Snowflake curator framework not connected: " + curatorFramework.getState());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public CuratorFrameworkClient(ZookeeperRegistryProperties config, ReconnectCallb
curatorFramework.getConnectionStateListenable().addListener(new CuratorConnectionStateListener());

curatorFramework.start();
boolean isStarted = curatorFramework.getState().equals(CuratorFrameworkState.STARTED);
boolean isStarted = curatorFramework.getState() == CuratorFrameworkState.STARTED;
Assert.state(isStarted, () -> "Curator framework not started: " + curatorFramework.getState());
boolean isConnected = curatorFramework.blockUntilConnected(config.getMaxWaitTimeMs(), TimeUnit.MILLISECONDS);
Assert.state(isConnected, () -> "Curator framework not connected: " + curatorFramework.getState());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public EventSubscribeService(SchedGroupService schedGroupService) {

public static void subscribe(EventParam param) {
if (param != null && param.getType() != null) {
// putIfAbsent不会更新param
MAP.compute(param.getType(), (k, v) -> param);
// add or update value
MAP.put(param.getType(), param);
}
}

Expand Down
Loading

0 comments on commit 3d323b2

Please sign in to comment.