synchronized 三种用法
- synchronize static method ,synchronized 修饰静态方法
- synchronize instance method , synchronized 修饰实例方法
- synchronize{ //todo } , synchronized 修饰代码块
相对三种方式的实现方式分析:
java 代码:
public class SyncKeyWord {public SyncKeyWord() {}public static synchronized void staticMethod() {}public synchronized void instanceMethod() {}public void codeBlock() {String var1 = "obj";synchronized("obj") {;}}}
字节码文件:
public class keyword.SyncKeyWordminor version: 0major version: 52flags: ACC_PUBLIC, ACC_SUPERConstant pool:#1 = Methodref #4.#21 // java/lang/Object."<init>":()V#2 = String #22 // obj#3 = Class #23 // keyword/SyncKeyWord#4 = Class #24 // java/lang/Object#5 = Utf8 <init>#6 = Utf8 ()V#7 = Utf8 Code#8 = Utf8 LineNumberTable#9 = Utf8 LocalVariableTable#10 = Utf8 this#11 = Utf8 Lkeyword/SyncKeyWord;#12 = Utf8 staticMethod#13 = Utf8 instanceMethod#14 = Utf8 codeBlock#15 = Utf8 StackMapTable#16 = Class #23 // keyword/SyncKeyWord#17 = Class #24 // java/lang/Object#18 = Class #25 // java/lang/Throwable#19 = Utf8 SourceFile#20 = Utf8 SyncKeyWord.java#21 = NameAndType #5:#6 // "<init>":()V#22 = Utf8 obj#23 = Utf8 keyword/SyncKeyWord#24 = Utf8 java/lang/Object#25 = Utf8 java/lang/Throwable{public keyword.SyncKeyWord();descriptor: ()Vflags: ACC_PUBLICCode:stack=1, locals=1, args_size=10: aload_01: invokespecial #1 // Method java/lang/Object."<init>":()V4: returnLineNumberTable:line 9: 0LocalVariableTable:Start Length Slot Name Signature0 5 0 this Lkeyword/SyncKeyWord;public static synchronized void staticMethod();descriptor: ()Vflags: ACC_PUBLIC, ACC_STATIC, ACC_SYNCHRONIZED ## 此处标记 静态/同步Code:stack=0, locals=0, args_size=00: returnLineNumberTable:line 13: 0public synchronized void instanceMethod();descriptor: ()Vflags: ACC_PUBLIC, ACC_SYNCHRONIZED ## 此处标记 同步Code:stack=0, locals=1, args_size=10: returnLineNumberTable:line 17: 0LocalVariableTable:Start Length Slot Name Signature0 1 0 this Lkeyword/SyncKeyWord;public void codeBlock();descriptor: ()Vflags: ACC_PUBLICCode:stack=2, locals=3, args_size=10: ldc #2 // String obj2: dup3: astore_14: monitorenter ## 此处开启 monitor5: aload_16: monitorexit ## 退出 monitor 释放锁7: goto 1510: astore_211: aload_112: monitorexit ## 代码异常时 需要退出 monitor 释放锁13: aload_214: athrow15: returnException table:from to target type5 7 10 any10 13 10 anyLineNumberTable:line 20: 0line 22: 5line 23: 15LocalVariableTable:Start Length Slot Name Signature0 16 0 this Lkeyword/SyncKeyWord;StackMapTable: number_of_entries = 2frame_type = 255 /* full_frame */offset_delta = 10locals = [ class keyword/SyncKeyWord, class java/lang/Object ]stack = [ class java/lang/Throwable ]frame_type = 250 /* chop */offset_delta = 4}
对于代码块, Jvm 开启了一个monitor,这个monitor 控制了对象 obj 的对象锁,其他线程要进入,只能等 monitor释放obj的对象锁
对于 实例方法,对方法进行了 同步标记 ,然后通过获取实例对象的对象锁进行控制
对于静态方法,对方法做了 静态同步标记,通过 锁定 Class对象 的对象锁 进行控制
对应synchronized ,其所有的控制都是基于Java 对象 头的 markwork锁标识来操作的。
对象头的组成部分: Markword 类指针 数组长度(数组对象才有)
- markword
- 32位JVM中markword | 锁状态 | 25bit | | 4bit | 1bit | 2bit | | —- | —- | —- | —- | —- | —- | | | 23bit | 2bit | | 是否偏向锁 | | | 无锁 | 对象Hashcode | | 分代年龄 | 0 | | | 偏向锁 | 线程ID | Epoch | | | | | 轻量级锁 | | | | | | | 重量级锁 | | | | | | | GC标记 | | | | | |
monitor 是由 ObjectMonitor 实现的,
ObjectMonitor() {_header = NULL;_count = 0; ## 等待的线程数_waiters = 0,_recursions = 0;_object = NULL;_owner = NULL; ## 持有锁的线程_WaitSet = NULL; ##处于wait的线程,加入到这个set中_WaitSetLock = 0 ;_Responsible = NULL ;_succ = NULL ;_cxq = NULL ;FreeNext = NULL ;_EntryList = NULL ; ## 处于等待锁block的线程,加入到这里_SpinFreq = 0 ;_SpinClock = 0 ;OwnerIsThread = 0 ;_previous_owner_tid = 0;}
ObjectMonitor 源码
/** Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.** This code is free software; you can redistribute it and/or modify it* under the terms of the GNU General Public License version 2 only, as* published by the Free Software Foundation.** This code is distributed in the hope that it will be useful, but WITHOUT* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License* version 2 for more details (a copy is included in the LICENSE file that* accompanied this code).** You should have received a copy of the GNU General Public License version* 2 along with this work; if not, write to the Free Software Foundation,* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.** Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA* or visit www.oracle.com if you need additional information or have any* questions.**/#ifndef SHARE_VM_RUNTIME_OBJECTMONITOR_HPP#define SHARE_VM_RUNTIME_OBJECTMONITOR_HPP#include "runtime/os.hpp"#include "runtime/park.hpp"#include "runtime/perfData.hpp"// ObjectWaiter serves as a "proxy" or surrogate thread.// TODO-FIXME: Eliminate ObjectWaiter and use the thread-specific// ParkEvent instead. Beware, however, that the JVMTI code// knows about ObjectWaiters, so we'll have to reconcile that code.// See next_waiter(), first_waiter(), etc.class ObjectWaiter : public StackObj {public:enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ } ;enum Sorted { PREPEND, APPEND, SORTED } ;ObjectWaiter * volatile _next;ObjectWaiter * volatile _prev;Thread* _thread;jlong _notifier_tid;ParkEvent * _event;volatile int _notified ;volatile TStates TState ;Sorted _Sorted ; // List placement dispositionbool _active ; // Contention monitoring is enabledpublic:ObjectWaiter(Thread* thread);void wait_reenter_begin(ObjectMonitor *mon);void wait_reenter_end(ObjectMonitor *mon);};// WARNING:// This is a very sensitive and fragile class. DO NOT make any// change unless you are fully aware of the underlying semantics.// This class can not inherit from any other class, because I have// to let the displaced header be the very first word. Otherwise I// have to let markOop include this file, which would export the// monitor data structure to everywhere.//// The ObjectMonitor class is used to implement JavaMonitors which have// transformed from the lightweight structure of the thread stack to a// heavy weight lock due to contention// It is also used as RawMonitor by the JVMTIclass ObjectMonitor {public:enum {OM_OK, // no errorOM_SYSTEM_ERROR, // operating system errorOM_ILLEGAL_MONITOR_STATE, // IllegalMonitorStateExceptionOM_INTERRUPTED, // Thread.interrupt()OM_TIMED_OUT // Object.wait() timed out};public:// TODO-FIXME: the "offset" routines should return a type of off_t instead of int ...// ByteSize would also be an appropriate type.static int header_offset_in_bytes() { return offset_of(ObjectMonitor, _header); }static int object_offset_in_bytes() { return offset_of(ObjectMonitor, _object); }static int owner_offset_in_bytes() { return offset_of(ObjectMonitor, _owner); }static int count_offset_in_bytes() { return offset_of(ObjectMonitor, _count); }static int recursions_offset_in_bytes() { return offset_of(ObjectMonitor, _recursions); }static int cxq_offset_in_bytes() { return offset_of(ObjectMonitor, _cxq) ; }static int succ_offset_in_bytes() { return offset_of(ObjectMonitor, _succ) ; }static int EntryList_offset_in_bytes() { return offset_of(ObjectMonitor, _EntryList); }static int FreeNext_offset_in_bytes() { return offset_of(ObjectMonitor, FreeNext); }static int WaitSet_offset_in_bytes() { return offset_of(ObjectMonitor, _WaitSet) ; }static int Responsible_offset_in_bytes() { return offset_of(ObjectMonitor, _Responsible);}static int Spinner_offset_in_bytes() { return offset_of(ObjectMonitor, _Spinner); }public:// Eventaully we'll make provisions for multiple callbacks, but// now one will suffice.static int (*SpinCallbackFunction)(intptr_t, int) ;static intptr_t SpinCallbackArgument ;public:markOop header() const;void set_header(markOop hdr);intptr_t is_busy() const {// TODO-FIXME: merge _count and _waiters.// TODO-FIXME: assert _owner == null implies _recursions = 0// TODO-FIXME: assert _WaitSet != null implies _count > 0return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList ) ;}intptr_t is_entered(Thread* current) const;void* owner() const;void set_owner(void* owner);intptr_t waiters() const;intptr_t count() const;void set_count(intptr_t count);intptr_t contentions() const ;intptr_t recursions() const { return _recursions; }// JVM/DI GetMonitorInfo() needs thisObjectWaiter* first_waiter() { return _WaitSet; }ObjectWaiter* next_waiter(ObjectWaiter* o) { return o->_next; }Thread* thread_of_waiter(ObjectWaiter* o) { return o->_thread; }// initialize the monitor, exception the semaphore, all other fields// are simple integers or pointersObjectMonitor() {_header = NULL;_count = 0;_waiters = 0,_recursions = 0;_object = NULL;_owner = NULL;_WaitSet = NULL;_WaitSetLock = 0 ;_Responsible = NULL ;_succ = NULL ;_cxq = NULL ;FreeNext = NULL ;_EntryList = NULL ;_SpinFreq = 0 ;_SpinClock = 0 ;OwnerIsThread = 0 ;_previous_owner_tid = 0;}~ObjectMonitor() {// TODO: Add asserts ...// _cxq == 0 _succ == NULL _owner == NULL _waiters == 0// _count == 0 _EntryList == NULL etc}private:void Recycle () {// TODO: add stronger asserts ...// _cxq == 0 _succ == NULL _owner == NULL _waiters == 0// _count == 0 EntryList == NULL// _recursions == 0 _WaitSet == NULL// TODO: assert (is_busy()|_recursions) == 0_succ = NULL ;_EntryList = NULL ;_cxq = NULL ;_WaitSet = NULL ;_recursions = 0 ;_SpinFreq = 0 ;_SpinClock = 0 ;OwnerIsThread = 0 ;}public:void* object() const;void* object_addr();void set_object(void* obj);bool check(TRAPS); // true if the thread owns the monitor.void check_slow(TRAPS);void clear();static void sanity_checks(); // public for -XX:+ExecuteInternalVMTests// in PRODUCT for -XX:SyncKnobs=Verbose=1#ifndef PRODUCTvoid verify();void print();#endifbool try_enter (TRAPS) ;void enter(TRAPS);void exit(bool not_suspended, TRAPS);void wait(jlong millis, bool interruptable, TRAPS);void notify(TRAPS);void notifyAll(TRAPS);// Use the following at your own riskintptr_t complete_exit(TRAPS);void reenter(intptr_t recursions, TRAPS);private:void AddWaiter (ObjectWaiter * waiter) ;static void DeferredInitialize();ObjectWaiter * DequeueWaiter () ;void DequeueSpecificWaiter (ObjectWaiter * waiter) ;void EnterI (TRAPS) ;void ReenterI (Thread * Self, ObjectWaiter * SelfNode) ;void UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) ;int TryLock (Thread * Self) ;int NotRunnable (Thread * Self, Thread * Owner) ;int TrySpin_Fixed (Thread * Self) ;int TrySpin_VaryFrequency (Thread * Self) ;int TrySpin_VaryDuration (Thread * Self) ;void ctAsserts () ;void ExitEpilog (Thread * Self, ObjectWaiter * Wakee) ;bool ExitSuspendEquivalent (JavaThread * Self) ;private:friend class ObjectSynchronizer;friend class ObjectWaiter;friend class VMStructs;// WARNING: this must be the very first word of ObjectMonitor// This means this class can't use any virtual member functions.volatile markOop _header; // displaced object header word - markvoid* volatile _object; // backward object pointer - strong rootdouble SharingPad [1] ; // temp to reduce false sharing// All the following fields must be machine word aligned// The VM assumes write ordering wrt these fields, which can be// read from other threads.protected: // protected for jvmtiRawMonitorvoid * volatile _owner; // pointer to owning thread OR BasicLockvolatile jlong _previous_owner_tid; // thread id of the previous owner of the monitorvolatile intptr_t _recursions; // recursion count, 0 for first entryprivate:int OwnerIsThread ; // _owner is (Thread *) vs SP/BasicLockObjectWaiter * volatile _cxq ; // LL of recently-arrived threads blocked on entry.// The list is actually composed of WaitNodes, acting// as proxies for Threads.protected:ObjectWaiter * volatile _EntryList ; // Threads blocked on entry or reentry.private:Thread * volatile _succ ; // Heir presumptive thread - used for futile wakeup throttlingThread * volatile _Responsible ;int _PromptDrain ; // rqst to drain cxq into EntryList ASAPvolatile int _Spinner ; // for exit->spinner handoff optimizationvolatile int _SpinFreq ; // Spin 1-out-of-N attempts: success ratevolatile int _SpinClock ;volatile int _SpinDuration ;volatile intptr_t _SpinState ; // MCS/CLH list of spinners// TODO-FIXME: _count, _waiters and _recursions should be of// type int, or int32_t but not intptr_t. There's no reason// to use 64-bit fields for these variables on a 64-bit JVM.volatile intptr_t _count; // reference count to prevent reclaimation/deflation// at stop-the-world time. See deflate_idle_monitors().// _count is approximately |_WaitSet| + |_EntryList|protected:volatile intptr_t _waiters; // number of waiting threadsprivate:protected:ObjectWaiter * volatile _WaitSet; // LL of threads wait()ing on the monitorprivate:volatile int _WaitSetLock; // protects Wait Queue - simple spinlockpublic:int _QMix ; // Mixed prepend queue disciplineObjectMonitor * FreeNext ; // Free list linkageintptr_t StatA, StatsB ;public:static void Initialize () ;static PerfCounter * _sync_ContendedLockAttempts ;static PerfCounter * _sync_FutileWakeups ;static PerfCounter * _sync_Parks ;static PerfCounter * _sync_EmptyNotifications ;static PerfCounter * _sync_Notifications ;static PerfCounter * _sync_SlowEnter ;static PerfCounter * _sync_SlowExit ;static PerfCounter * _sync_SlowNotify ;static PerfCounter * _sync_SlowNotifyAll ;static PerfCounter * _sync_FailedSpins ;static PerfCounter * _sync_SuccessfulSpins ;static PerfCounter * _sync_PrivateA ;static PerfCounter * _sync_PrivateB ;static PerfCounter * _sync_MonInCirculation ;static PerfCounter * _sync_MonScavenged ;static PerfCounter * _sync_Inflations ;static PerfCounter * _sync_Deflations ;static PerfLongVariable * _sync_MonExtant ;public:static int Knob_Verbose;static int Knob_SpinLimit;void* operator new (size_t size) throw() {return AllocateHeap(size, mtInternal);}void* operator new[] (size_t size) throw() {return operator new (size);}void operator delete(void* p) {FreeHeap(p, mtInternal);}void operator delete[] (void *p) {operator delete(p);}};#undef TEVENT#define TEVENT(nom) {if (SyncVerbose) FEVENT(nom); }#define FEVENT(nom) { static volatile int ctr = 0 ; int v = ++ctr ; if ((v & (v-1)) == 0) { ::printf (#nom " : %d \n", v); ::fflush(stdout); }}#undef TEVENT#define TEVENT(nom) {;}#endif // SHARE_VM_RUNTIME_OBJECTMONITOR_HPP
