Java Synchronization

Intrinsic Locks and Synchronization

  Synchronization is built around an internal entity known as
the intrinsic lock or monitor lock. (The API
specification often refers to

this entity simply as a "monitor.") Intrinsic locks play a role in both
aspects of synchronization: enforcing exclusive access to an object‘s

state and establishing happens-before relationships that are essential to
visibility.

  Every object has an intrinsic lock associated with it. By convention, a
thread that needs exclusive and consistent access to an object‘s

fields has to acquire the object‘s intrinsic lock before
accessing them, and then release the intrinsic lock when it‘s
done with them. A thread

is said to own the intrinsic lock between the time it has
acquired the lock and released the lock. As long as a thread owns an intrinsic
lock,

no other thread can acquire the same lock. The other thread will block when
it attempts to acquire the lock.

 When a thread releases an intrinsic lock, a happens-before
relationship is established between that action and any subsequent
acquistion

of the same lock.

Locks In Synchronized Methods

  When a thread invokes a synchronized method, it automatically acquires the
intrinsic lock for that method‘s object and releases it when

the method returns. The lock release occurs even if the return was
caused by an uncaught exception.

  You might wonder what happens when a static synchronized method is invoked,
since a static method is associated with a class, not an

object. In this case, the thread acquires the intrinsic lock for
the Class object associated with the class. Thus access
to class‘s static fields is

controlled by a lock that‘s distinct from the lock for any instance of
the class.

  因为静态方法与类相关,与实例无关。因此,static synchronized
method 将获得类的锁。

Synchronized Statements

  Another way to create synchronized code is with synchronized
statements
. Unlike synchronized methods, synchronized statements

must specify the object that provides the intrinsic lock:

public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++;
}
nameList.add(name);
}

  In this example, the addName method needs to
synchronize changes
to lastName and nameCount, but also
needs to avoid synchronizing

invocations of other objects‘ methods. (Invoking other objects‘ methods from
synchronized code can create problems that are described

in the section on Liveness.)
Without synchronized statements, there would have to be a separate,
unsynchronized method for the sole

purpose of invoking nameList.add.

  Synchronized statements are also useful for improving
concurrency with fine-grained synchronization. Suppose, for example,
class

MsLunch has two instance
fields, c1 and c2, that are never used
together. All updates of these fields must be synchronized, but there‘s

no reason to prevent an update of c1 from being interleaved with an
update of c2 — and doing so reduces concurrency by creating

unnecessary blocking. Instead of using synchronized methods or otherwise
using the lock associated with this, we create two objects

solely to provide locks.

public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();

public void inc1() {
synchronized(lock1) {
c1++;
}
}

public void inc2() {
synchronized(lock2) {
c2++;
}
}
}

  Use this idiom with extreme care. You must be absolutely sure that it
really is safe to interleave access of the affected fields.

Reentrant Synchronization

  Recall that a thread cannot acquire a lock owned by another thread. But a
thread can acquire a lock that it already owns. Allowing
a

thread to acquire the same lock more than once enables reentrant
synchronization
. This describes a situation where synchronized code,

directly or indirectly, invokes a method that also contains synchronized
code, and both sets of code use the same lock. Without reentrant

synchronization, synchronized code would have to take many additional
precautions to avoid having a thread cause itself to block.

相关单词:

interleave - 交错,交叉存取的,隔行扫描的

sole - 唯一

Java Synchronization,码迷,mamicode.com

时间: 2024-12-30 02:34:47

Java Synchronization的相关文章

Java Performance Optimization Tools and Techniques for Turbocharged Apps--reference

Java Performance Optimization by: Pierre-Hugues Charbonneau reference:http://refcardz.dzone.com/refcardz/java-performance-optimization Java is among the most widely used programming languages in the software development world today. Java applications

[Java基础] Java线程复习笔记

先说说线程和进程,现代操作系统几乎无一例外地采用进程的概念,进程之间基本上可以认为是相互独立的,共享的资源非常少.线程可以认为是轻量级的进 程,充分地利用线程可以使得同一个进程中执行多种任务.Java是第一个在语言层面就支持线程操作的主流编程语言.和进程类似,线程也是各自独立的,有自 己的栈,自己的局部变量,自己的程序执行并行路径,但线程的独立性又没有进程那么强,它们共享内存,文件资源,以及其他进程层面的状态等.同一个进程内的 多个线程共享同样的内存空间,这也就意味着这些线程可以访问同样的变量和

同步块中对象级别的锁和类级别的锁 —— Thread synchronization, object level locking and class level locking

Java supports multiple threads to be executed. This may cause two or more threads to access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in synch. Synchronization avoids memory consist

Java性能优化攻略详解

如何让Java应用程序运行是一回事,但让他们跑得快就是另外一回事了.在面对对象的环境中,性能问题就像来势凶猛的野兽.但JVM的复杂性将性能调整的复杂程度增加了一个级别.这里Refcard涵盖了JVM internals.class loading(Java8中更新以映射最新的元空间).垃圾回收.故障诊断.检测.并发性,等等. 当前Java是目前软件开发领域中使用最广泛的编程语言之一.Java应用程序在许多垂直领域(银行.电信.医疗保健等)中都有广泛使用.Refcard的目的是,帮助开发者通过专注

最常见的15个Java多线程,并发面试问题

例如,用于DMA交易的高容量和低延迟电子交易系统通常是并发的.大多数情况下,他们专注于微秒延迟,这就是为什么拥有如何有效地最小化延迟和提高吞吐量知识是如此重要. 这些是我最喜欢的关于Java的线程面试问题.我没有提供这些线程访谈问题的答案,但我会尽可能给你一个提示.我会更新帖子就详细的答案,就像我最近在Java中发布的10个Singleton面试问题一样. 15 Java Thread Interview Questions and answers 无论如何,这里是一些常见的Java多线程和并发

临时

This work was partially performed when the first author was a visitor at NCSU, supported by a fellowship from the University of Pisa and MURST, Italy. This work was supported in part by NSF grant CCR-9320992 Design of a Toolset for Dynamic Analysis o

Terracotta tc-config.xml配置说明(这个真的是转的)

<?xml version="1.0" encoding="UTF-8" ?><!--All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. --><!--  tc-config-reference.xml  This is a sample Terracotta configuration file. In it,

垂直打击之JVM剖析

让Java应用程序运行是一回事,但让他们跑得快就是另外一回事了.在面对对象的环境中,性能问题就像来势凶猛的野兽.但JVM的复杂性将性能调整的复杂程度增加了一个级别.这里Refcard涵盖了JVM internals.class loading(Java8中更新以映射最新的元空间).垃圾回收.故障诊断.检测.并发性,等等. 介绍 Java是目前软件开发领域中使用最广泛的编程语言之一.Java应用程序在许多垂直领域(银行.电信.医疗保健等)中都有广泛使用.Refcard的目的是,帮助开发者通过专注于

关于JAVA中的Synchronization和interface误用

最近在写一个手机小应用系统的业务模块有一些对抽象和接口的规划主要是接口部分一般情况下同类或同性质的事物我们都会将其抽离实现接口统一以便业务实现节环更灵活地使用. 课题如下 在interface中声明 Synchronization 描述的方法是否可行要如何做 实际上Java 1.2以前的版本是允许这么做的 public interface DemoInterface{     synchronization void function1(); } 然而1.2以后的版本就不行了且这么做是是错误的.