Java Thread in JVM
(wang hailong)
本文从JVM的角度探讨Java Thread的语法和编译结果。如果需要获得第一手资料,请直接访问以下的资源——Java语言规范,Java虚拟机规范中有关线程的定义说明。
本文旨在介绍这些比较重要的线程相关的规范,基本上不另作发挥。(除了提到微软的“公共语言基础构造”。:-)
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Java Language Specification
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#30531
JVM Specification
http://java.sun.com/docs/books/vmspec/2nd-edition/html/Compiling.doc.html#6530
http://java.sun.com/docs/books/vmspec/2nd-edition/html/Instructions2.doc9.html
http://java.sun.com/docs/books/vmspec/2nd-edition/html/Threads.doc.html
Microsoft CLI -- Common Language Infrastructure (sorry, off the topic :-)
http://msdn.microsoft.com/net/ecma/
1.synchronized method 的java语言规范
详见http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#30531。
用synchronized关键字修饰的方法,分为两种情况:(static)静态方法,和实例方法。
(static)静态方法的“锁”是这个拥有这个方法的对象的Class对象;实例方法的“锁”是this,拥有这个方法的当前对象实例。
怎么理解这段话,看一看下面的例子就明白了。
下面两段代码的效果完全相同。代码1 ==代码2。
代码1:
class Test {
int count;
synchronized void bump() { count++; }
static int classCount;
static synchronized void classBump() {
classCount++;
}
}
代码2:
class BumpTest {
int count;
void bump() {
synchronized (this) {
count++;
}
}
static int classCount;
static void classBump() {
try {
synchronized (Class.forName("BumpTest")) {
classCount++;
}
} catch (ClassNotFoundException e) {
...
}
}
}
2.synchronized关键字的编译结果
这一节,我们来看一看synchronized关键字编译之后的java虚拟机指令是什么。
如果需要第一手资料,请参见java虚拟机规范相关的部分
http://java.sun.com/docs/books/vmspec/2nd-edition/html/Compiling.doc.html#6530
这段规范里面讲到,java虚拟机规范提供两条指令,monitorenter和monitorexit,来支持线程。但是对于上一节讲到的,用synchronized修饰的方法来说,并不使用这两个方法,而只是简单地用ACC_SYNCHRONIZED标志修饰。虚拟机调用方法的时候会检查这个标志,进行同步。
synchronized语句的编译结果对应monitorenter和monitorexit两条指令。
比如,下面的代码:
void onlyMe(Foo f) {
synchronized(f) {
doSomething();
}
}
的编译结果是
Method void onlyMe(Foo)
0 aload_1 // Push f
1 astore_2 // Store it in local variable 2
2 aload_2 // Push local variable 2 (f)
3 monitorenter // Enter the monitor associated with f
4 aload_0 // Holding the monitor, pass this and...
5 invokevirtual #5 // ...call Example.doSomething()V
8 aload_2 // Push local variable 2 (f)
9 monitorexit // Exit the monitor associated with f
10 return // Return normally
11 aload_2 // In case of any throw, end up here
12 monitorexit // Be sure to exit monitor...
13 athrow // ...then rethrow the value to the invoker
3.monitorenter和monitorexit
详见http://java.sun.com/docs/books/vmspec/2nd-edition/html/Instructions2.doc9.html
monitorenter定义的一段节录:
Operation : Enter monitor for object
Operand Stack : ..., objectref <?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" /><shapetype id="_x0000_t75" stroked="f" filled="f" path="m@4@5l@4@11@9@11@9@5xe" o:preferrelative="t" o:spt="75" coordsize="21600,21600"><stroke joinstyle="miter"></stroke><formulas><f eqn="if lineDrawn pixelLineWidth 0"></f><f eqn="sum @0 1 0"></f><f eqn="sum 0 0 @1"></f><f eqn="prod @2 1 2"></f><f eqn="prod @3 21600 pixelWidth"></f><f eqn="prod @3 21600 pixelHeight"></f><f eqn="sum @0 0 1"></f><f eqn="prod @6 1 2"></f><f eqn="prod @7 21600 pixelWidth"></f><f eqn="sum @8 21600 0"></f><f eqn="prod @7 21600 pixelHeight"></f><f eqn="sum @10 21600 0"></f></formulas><path o:connecttype="rect" gradientshapeok="t" o:extrusionok="f"></path><lock aspectratio="t" v:ext="edit"></lock></shapetype><shape id="_x0000_i1025" style="WIDTH: 13.5pt; HEIGHT: 9.75pt" alt="" type="#_x0000_t75"><imagedata o:href="http://java.sun.com/docs/books/vmspec/2nd-edition/html/chars/arrwdbrt.gif" src="file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif"></imagedata></shape>...
Description :
The objectref must be of type reference
.
Each object has a monitor associated with it. The thread that executes monitorenter gains ownership of the monitor associated with objectref. If another thread already owns the monitor associated with objectref, the current thread waits until the object is unlocked, then tries again to gain ownership. If the current thread already owns the monitor associated with objectref, it increments a counter in the monitor indicating the number of times this thread has entered the monitor. If the monitor associated with objectref is not owned by any thread, the current thread becomes the owner of the monitor, setting the entry count of this monitor to 1.
这段话的意思是说,monitorenter操作的目标一定要是一个对象,类型是reference。Reference实际就是堆里的一个存放对象的地址。每个对象(reference)都有一个monitor对应,如果有其它的线程获取了这个对象的monitor,当前的线程就要一直等待,直到获得monitor的线程放弃monitor,当前的线程才有机会获得monitor。
如果monitor没有被任何线程获取,那么当前线程获取这个monitor,把monitor的entry count设置为1。表示这个monitor被1个线程占用了。
当前线程获取了monitor之后,会增加这个monitor的时间计数,来记录当前线程占用了monitor多长时间。
我们看到,monitor这个词在java虚拟机规范规定出现,但是在java语言和API文档里面并没有出现。monitor是藏在线程同步后面的原理和概念。
4.Threads and Locks
详见http://java.sun.com/docs/books/vmspec/2nd-edition/html/Threads.doc.html。
这段规范详细地介绍了thread和lock的原理。下面给出这段规范的highlight。
8.4 Nonatomic Treatment of double
and long
Variables (double和long类型的非原子操作。)
8.7 Rules for volatile
Variables
8.10 Example: Possible Swap
8.11 Example: Out-of-Order Writes
如果对列出的这些highlight感兴趣,请访问相应的java虚拟机规范网址。
5.Why specification?
本文主要讨论java相关规范的内容。规范文档非常重要,尤其对于java,C#这种生成中间代码的语言来说。
上面说的是java的相关规范。这里顺便提一下微软.Net的相关规范。
微软的“公共语言基础构造”规范:
Microsoft CLI -- Common Language Infrastructure (sorry, off the topic :-)
http://msdn.microsoft.com/net/ecma/
这个网址上有C#语言规范,CLI规范的下载。
Enjoy it. :-)
分享到:
相关推荐
JVM内核的各个组成部分 Runtime data areas shared among all threads: Method area: holds the details of each class loaded by the class loader subsystem. Heap: holds every object being created by the ...
Moving on, you'll also learn how to enhance performance using Java interoperability and JVM-specific features from Clojure; you'll even master language features such as asynchronous channels, actors, ...
most importantly, this book will show you the breaking changes in Java 9., What You'll Learn, Discover what is new in the Process APIInspect a thread’s stack with the Stack-Walking APIUse the jlink ...
20 Thread Synchronization Monitors Object Locking Synchronization Support in the Instruction Set Synchronized Statements Synchronized Methods Coordination Support in Class Object On the CD-ROM ...
49. Java虚拟机(JVM)中的线程调度器负责管理线程,调度器把线程的优先级分为10个级别,分别用Thread类中的类常量表示,每个Java线程的优先级都在常数________和_______之间,即Thread.MIN_PRIORIY和Thread.MAX_...
Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics at okio.Okio.source(Okio.kt) at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:144) ...
Thread t=new Thread(inc); t.start(); t=new Thread(dec); t.start(); } } private synchronized void inc(){ j++; System.out.println(Thread.currentThread().getName()+"-inc:"+j); } private synchronized ...
jstack生成的Thread Dump日志.docx 系统线程状态 (Native Thread Status) 系统线程有如下状态: ...死锁线程,一般指多个线程调用期间进入了相互资源占用,导致一直等待无法...JVM线程运行状态 (JVM Thread Status)
in Java Other Concurrency Resources JVM 数据结构和算法 设计模式 面向对象设计原则 Creational Patterns 3 Structural Patterns Behavioral Patterns Netty Netty 核心 ...
1.2.3 Java Virtual Machine(JVM) 2 1.2.4 面向对象的程序设计语言 2 1.2.5 线程(thread) 2 1.2.6 垃圾回收机制(garbage collection) 2 1.3 安装Java程序开发工具(JDK1.5) 2 1.3.1 安装JAVA 2 Standard ...
189、Can a Java Thread be started from Servlet class, and what will be the implications? 45 190、What is HTTP Session tracking and why is it important? 45 191、What is session management, and how is ...
sleep是线程类(Thread)的方法,导致此线程暂停执行指定时间,给执行机会给其他线程,但是监控状态依然保持,到时后会自动恢复。调用sleep不会释放对象锁。 wait是Object类的方法,对此对象调用wait方法导致本线程...
Arthas开源的Java诊断工具 更新日志:v3.5.1Add vmtool commandRemove the useless resetClassFileTransformer in Enhancer对于非chunk response,返回标准的content-length字段The jvm command may throw ...
当然除了Python代码(译者注:链接里面讲述了Python的全局解释器锁,解释了原因),不过你仍然可以使用Jython在JVM上运行你的程序,来利用多处理器电脑的强大能力。 然而,并发程序的复杂程度远远超出了人类大脑...
Exception in thread http-nio-8080-exec-1027 java.lang.OutOfMemoryError: Java heap space Exception in thread http-nio-8080-exec-1031 java.lang.OutOfMemoryError: Java heap space 看线程名称应该是tomcat的...
Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: /usr/lib/jvm/java-11-openjdk-amd64/lib/libawt_xawt.so 5、重新安装jdk解决以上问题 sudo apt install openjdk-11-jdk -y 6、...
JVM Management: Java SE 6.0 Monitoring and Management Architecture Identifying Processes and Threads Obtaining a Thread Dump Using WLS Memory: Define Java Heap Garbage Collection Review Configuring ...
如果在一个jvm里创建太多的线程,可能会使系统由于过度消耗内存或“切换过度”而导致系统资源不足。为了防止资源不足,服务器应用程序需要采取一些办法来限制任何给定时刻处理的请求数目,尽可能减少创建和销毁线程...
Author Dan Woods—a member of the Ratpack core team—provides a progressively in-depth tour of Ratpack and its capabilities, from basic concepts to tools and strategies to help you construct fast, ...