Poison


  • 首页

  • 归档

  • 标签

  • 搜索
close
Poison

Thread.yield()

发表于 2021-10-18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
public static native void yield();

在 ConcurrentHashMap 的 initTable 方法中,可以看到对该方法的使用,源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Initializes table, using the size recorded in sizeCtl.
*/
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}

可以看出,若当前线程判断 table 当前时刻已经在被其他线程进行初始化时,则调用 Thread.yield() 提示调度程序当前线程愿意放弃对当前处理器的使用权,以尝试降低对 CPU 的争用。

阅读全文 »
Poison

Thread.State

发表于 2021-10-18

JVM 中的线程可能处于以下状态:

  • NEW
  • RUNNABLE
  • BLOCKED
  • WAITING
  • TIMED_WAITING
  • TERMINATED

JVM 中的线程在任意时刻只能处于一种状态。这些状态仅是 JVM 虚拟机中的线程状态,并不反应操作系统的线程状态。

记录这个问题是因为之前在我们的监控服务中经常探测到持续的 RUNNABLE 线程,经过定位,发现是我们自身的用于监控堆转储文件的线程,其实在操作系统中的状态并不是 R,即并不是运行中或位于运行队列中,我们用一个例子来说明,在我们的线程转储中,经常发现如下的线程数据:

1
2
3
4
5
6
"Thread-5" #16 daemon prio=5 os_prio=0 tid=0x00007f4920006800 nid=0x2d runnable [0x00007f49338e9000]
java.lang.Thread.State: RUNNABLE
at sun.nio.fs.LinuxWatchService.poll(Native Method)
at sun.nio.fs.LinuxWatchService.access$600(LinuxWatchService.java:47)
at sun.nio.fs.LinuxWatchService$Poller.run(LinuxWatchService.java:314)
at java.lang.Thread.run(Thread.java:748)

该方法在 JVM 线程转储中一直处于 RUNNABLE 状态,但是,根据 nid=0x2d 我们转换出对应的 Linux 轻量级进程 id:45 通过如下命令查询轻量级进程状态(其中的 1 为 JVM 进程的 id):

1
cat /proc/1/task/45/status | grep 'State:'

可以得到以下输出:

1
State: S (sleeping)

得到的状态为 S,在 Linux 文档中对应的解释为:interruptible sleep (waiting for an event to complete),这也验证了 Java 文档中的说法,JVM 中的线程状态并不反应操作系统中的线程状态。

同理,最常见的 Netty 执行 Epoll 的线程栈帧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"NettyClientWorker-4-7" #424 daemon prio=5 os_prio=0 tid=0x00007f28080ba000 nid=0x1b5 runnable [0x00007f27f2341000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
at sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
at sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
- locked <0x00000000e11e1d90> (a io.netty.channel.nio.SelectedSelectionKeySet)
- locked <0x00000000e11e1e80> (a java.util.Collections$UnmodifiableSet)
- locked <0x00000000e11e1da8> (a sun.nio.ch.EPollSelectorImpl)
at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
at io.netty.channel.nio.SelectedSelectionKeySetSelector.select(SelectedSelectionKeySetSelector.java:62)
at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:756)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:411)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)

其在 JVM 中的线程状态为 RUNNABLE, 在操作系统级别的状态也为 S (sleeping)。

Reference

Thread.State (Java Platform SE 8 )
ps(1) - Linux manual page
Processes and Threads (The Java™ Tutorials > Essential Java Classes > Concurrency)

Poison

Classloader Hierarchy for Tomcat

发表于 2021-10-14

关于 Tomcat 的类加载器层次,我之前也只是看过文档中的介绍,并未深入理解,直到一次问题排查,对其有了更深入的理解,本文作简要记录。

在一次处理 java.sql.DriverManager 相关的问题时,看到 DriverManager 文档中有以下描述:

Applications no longer need to explicitly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

于是果断把一个数据源工具类中的 Class.forName() 方法调用进行了移除。原实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package me.tianshuang.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataSourceUtil {

public static Connection getConnection(String url, String driverClassName, String username, String password) {
try {
Class.forName(driverClassName);
return DriverManager.getConnection(url, username, password);
} catch (SQLException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}

}
阅读全文 »
Poison

Double Brace Initialization

发表于 2021-10-08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package me.tianshuang;

import java.util.HashMap;
import java.util.Map;

public class DoubleBraceTest {

private static Map<String, String> map = new HashMap<String, String>() {{
put("key1", "value1");
put("key2", "value2");
put("key3", "value3");
}};

}

以上代码使用了双括号初始化,其中外层那一对括号创建了一个匿名内部类,里层的那一对括号是一个实例初始化块。对于上面这一段源码,进行编译后我们可以在目录看到两个 class 文件,分别是 DoubleBraceTest.class 与 DoubleBraceTest$1.class,其中 DoubleBraceTest$1.class 是我们定义的 HashMap 类的匿名子类,其反编译源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package me.tianshuang;

import java.util.HashMap;

final class DoubleBraceTest$1 extends HashMap<String, String> {
DoubleBraceTest$1() {
this.put("key1", "value1");
this.put("key2", "value2");
this.put("key3", "value3");
}
}
阅读全文 »
Poison

Class.isAssignableFrom

发表于 2021-10-07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Determines if the class or interface represented by this
* {@code Class} object is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the specified
* {@code Class} parameter. It returns {@code true} if so;
* otherwise it returns {@code false}. If this {@code Class}
* object represents a primitive type, this method returns
* {@code true} if the specified {@code Class} parameter is
* exactly this {@code Class} object; otherwise it returns
* {@code false}.
*
* <p> Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* or via a widening reference conversion. See <em>The Java Language
* Specification</em>, sections 5.1.1 and 5.1.4 , for details.
*
* @param cls the {@code Class} object to be checked
* @return the {@code boolean} value indicating whether objects of the
* type {@code cls} can be assigned to objects of this class
* @exception NullPointerException if the specified Class parameter is
* null.
* @since JDK1.1
*/
public native boolean isAssignableFrom(Class<?> cls);

该 native 方法在我开发 Java Agent 的过程中进行了调试,发现对于满足实现关系的类,如果不是由相同的类加载器加载,则会返回 false。

阅读全文 »
1…131415…26

130 日志
119 标签
GitHub LeetCode
© 2025 Poison 蜀ICP备16000644号
由 Hexo 强力驱动
主题 - NexT.Mist