From 430956cfd5b5701af8068913f7170926bc42e47b Mon Sep 17 00:00:00 2001 From: Erving Date: Fri, 25 Jun 2021 16:02:08 +0800 Subject: [PATCH] fix ExecutingRunnable hashcode (#141) --- .../sofa/common/thread/ExecutingRunnable.java | 13 ++++++++++++- .../common/thread/SofaThreadPoolExecutorTest.java | 8 ++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alipay/sofa/common/thread/ExecutingRunnable.java b/src/main/java/com/alipay/sofa/common/thread/ExecutingRunnable.java index 1c33a9c1..707caa85 100644 --- a/src/main/java/com/alipay/sofa/common/thread/ExecutingRunnable.java +++ b/src/main/java/com/alipay/sofa/common/thread/ExecutingRunnable.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.common.thread; +import java.util.Objects; + /** * The wrapper to the {@link Runnable} to save it's execute {@link Thread} * @author huzijie @@ -35,6 +37,8 @@ class ExecutingRunnable implements Runnable { private volatile boolean printed; + private Integer hashCode; + public ExecutingRunnable(Runnable originRunnable) { if (originRunnable == null) { throw new NullPointerException(); @@ -42,9 +46,16 @@ public ExecutingRunnable(Runnable originRunnable) { this.originRunnable = originRunnable; } + // ExecutingRunnable won't be executed by more than one thread @Override public int hashCode() { - return toString().hashCode(); + if (hashCode == null) { + // Save hashcode for later retrieval + // ExecutingRunnable is saved in a map, we may fail to remove if this changes + hashCode = Objects.hash(originRunnable, thread); + } + + return hashCode; } @Override diff --git a/src/test/java/com/alipay/sofa/common/thread/SofaThreadPoolExecutorTest.java b/src/test/java/com/alipay/sofa/common/thread/SofaThreadPoolExecutorTest.java index 11aa424d..cbd5092c 100644 --- a/src/test/java/com/alipay/sofa/common/thread/SofaThreadPoolExecutorTest.java +++ b/src/test/java/com/alipay/sofa/common/thread/SofaThreadPoolExecutorTest.java @@ -45,6 +45,14 @@ public void cleanExecutor() throws InterruptedException { } } + @Test + public void testThreadNameChanged() throws InterruptedException { + int old = threadPool.getStatistics().getExecutingTasks().size(); + threadPool.execute(() -> Thread.currentThread().setName("test-name")); + Thread.sleep(1000); + Assert.assertEquals(old, threadPool.getStatistics().getExecutingTasks().size()); + } + @Test public void testDecayedTask() throws Exception { Assert.assertTrue(isMatch(getInfoViaIndex(0), INFO, String.format(