java并发之固定对象与实例

Immutable Objects

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.

The following subsections take a class whose instances are mutable and derives a class with immutable instances from it. In so doing, they give general rules for this kind of conversion and demonstrate some of the advantages of immutable objects.


译文:
固定对象
  如果一个对象在创建之后它的状态就不能改变了,那么它就是一个固定对象。固定对象的最大可信性作为一种简单的、可信性的编码被广泛接受。
  固定对象通常应用在并发的应用程序中。由于他们不能改变状态,因此他们不能被线程中断打断或者观察到不一致的状态。
  程序员经常拒绝使用固定对象,因为他们担心创建一个对象会比更新一个对象更加耗费。创建对象的耗费经常被过高估计,并且固定对象的使用能够引起一些效率问题。这些包括减少必要的垃圾回收,和在并发时消除代码需要保护固定对象的开销。
  在下一节中,给定了一个固定对象的类和一个可变对象的类。他们给定了一些通用的转换规则,并且描述了一些固定对象的优势。

A Synchronized Class Example

The class, SynchronizedRGB, defines objects that represent colors. Each object represents the color as three integers that stand for primary color values and a string that gives the name of the color.

public class SynchronizedRGB {

    // Values must be between 0 and 255.
private int red;
private int green;
private int blue;
private String name; private void check(int red,
int green,
int blue) {
if (red < 0 || red > 255
|| green < 0 || green > 255
|| blue < 0 || blue > 255) {
throw new IllegalArgumentException();
}
} public SynchronizedRGB(int red,
int green,
int blue,
String name) {
check(red, green, blue);
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
} public void set(int red,
int green,
int blue,
String name) {
check(red, green, blue);
synchronized (this) {
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}
} public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
} public synchronized String getName() {
return name;
} public synchronized void invert() {
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
name = "Inverse of " + name;
}
}

SynchronizedRGB must be used carefully to avoid being seen in an inconsistent state. Suppose, for example, a thread executes the following code:

SynchronizedRGB color =
new SynchronizedRGB(0, 0, 0, "Pitch Black");
...
int myColorInt = color.getRGB(); //Statement 1
String myColorName = color.getName(); //Statement 2

If another thread invokes color.set after Statement 1 but before Statement 2, the value of myColorInt won't match the value of myColorName. To avoid this outcome, the two statements must be bound together:

synchronized (color) {
int myColorInt = color.getRGB();
String myColorName = color.getName();
}

This kind of inconsistency is only possible for mutable objects — it will not be an issue for the immutable version ofSynchronizedRGB.


译文:
一个同步的例子
这个类,SynchronizedRGB,定义颜色对象的类。每一个对象包括三个颜色需要的基本的值和他们的字符串性质的名字。
 1 public class SynchronizedRGB {
2
3 // Values must be between 0 and 255.
4 private int red;
5 private int green;
6 private int blue;
7 private String name;
8
9 private void check(int red,
10 int green,
11 int blue) {
12 if (red < 0 || red > 255
13 || green < 0 || green > 255
14 || blue < 0 || blue > 255) {
15 throw new IllegalArgumentException();
16 }
17 }
18
19 public SynchronizedRGB(int red,
20 int green,
21 int blue,
22 String name) {
23 check(red, green, blue);
24 this.red = red;
25 this.green = green;
26 this.blue = blue;
27 this.name = name;
28 }
29
30 public void set(int red,
31 int green,
32 int blue,
33 String name) {
34 check(red, green, blue);
35 synchronized (this) {
36 this.red = red;
37 this.green = green;
38 this.blue = blue;
39 this.name = name;
40 }
41 }
42
43 public synchronized int getRGB() {
44 return ((red << 16) | (green << 8) | blue);
45 }
46
47 public synchronized String getName() {
48 return name;
49 }
50
51 public synchronized void invert() {
52 red = 255 - red;
53 green = 255 - green;
54 blue = 255 - blue;
55 name = "Inverse of " + name;
56 }
57 }
SynchronizedRGB必须在不一致的状态下必须谨慎使用。假如,例如,一个线程执行如下代码:
1 SynchronizedRGB color =
2 new SynchronizedRGB(0, 0, 0, "Pitch Black");
3 ...
4 int myColorInt = color.getRGB(); //Statement 1
5 String myColorName = color.getName(); //Statement 2

如果另外一个线程在语句一执行之后语句二执行之前又另外一个线程执行color.set方法。myColorInt的值将会匹配myColorName的值。为了避免这种情况发生,这两天语句需要绑到一起。

synchronized (color) {
int myColorInt = color.getRGB();
String myColorName = color.getName();
}

这种不一致唯一可能引起的可变对象,对于固定对象来说这是永远不会发生的。

 
 
 
 
 
 
 
 
 
 
 

作者:Janne Lee 
邮箱:JanneLeeMAC@gmail.com 
出处:http://www.cnblogs.com/accipiter/ 
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 
该文章也同时发布在我的独立博客中-Accipter'blog

 
分类: java

java并发之固定对象与实例的更多相关文章

  1. 【翻译十五】-java并发之固定对象与实例

    Immutable Objects An object is considered immutable if its state cannot change after it is construct ...

  2. Java 并发之共享对象

    上一篇文章说的是,避免多个线程在同一时间访问对象中的同一数据,这篇文章来详细说说共享和发布对象. 在没有同步的情况下,我们无法预料编译器.处理器安排操作执行的顺序,经常会发生以为“一定会”发生的动作实 ...

  3. Java中的匿名对象代码实例

    /* 匿名对象:就是没有名字的对象. 匿名对象的应用场景: A:调用场景,仅仅只调用一次的时候. 注意:调用多次的时候,不合适. 那么,这种匿名调用有什么好处吗? 有,匿名对象调用完毕就是垃圾.可以被 ...

  4. Java访问子类对象的实例变量

    对于Java这种语言来说,一般来说,子类可以调用父类中的非private变量,但在一些特殊情况下, Java语言可以通过父类调用子类的变量 具体的还是请按下面的例子吧! package com.yon ...

  5. 【Java学习】类、对象、实例—类是对象的抽象,对象是类的实例

    类.对象.实例的关系是什么,如果不能很好的理解什么是类什么是对象就无法讲清楚, 类:某种事物与另一种事物具有相似性,比如哈士奇和泰迪,我们发现他们有一些相似的特性和行为,在生物学上,他们都属于“狗”, ...

  6. 深入理解Java并发之synchronized实现原理

    深入理解Java类型信息(Class对象)与反射机制 深入理解Java枚举类型(enum) 深入理解Java注解类型(@Annotation) 深入理解Java类加载器(ClassLoader) 深入 ...

  7. Java内存区域与对象创建过程

    一.java内存区域 Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若干个不同的数据区域.这些区域都有各自的用途,以及创建和销毁的时间,有的区域随着虚拟机进程的启动而存在,有的区域则 ...

  8. Java生成MD5加密字符串代码实例

    这篇文章主要介绍了Java生成MD5加密字符串代码实例,本文对MD5的作用作了一些介绍,然后给出了Java下生成MD5加密字符串的代码示例,需要的朋友可以参考下   (1)一般使用的数据库中都会保存用 ...

  9. java入门---变量类型&类变量&局部变量&实例变量&静态变量

        在Java语言中,所有的变量在使用前必须声明.声明变量的基本格式如下:     type identifier [ = value][, identifier [= value] ...] ; ...

随机推荐

  1. krpano音量控制(我们已经转移到krpano中国网站 krpano360.com)

    需求: 实现音量控制,这是官网的样例, 本文已经转移 到 krpano中文网 p=148">http://krpano360.com/? p=148 很多其它教程关注微信公众号 krp ...

  2. java设计模式之二抽象工厂模式(Abstract Factory)

    工厂方法模式有一个问题就是,类的创建依赖工厂类,也就是说,如果想要拓展程序,必须对工厂类进行修改,这违背了闭包原则,所以,从设计角度考虑,有一定的问题,如何解决?就用到抽象工厂模式,创建多个工厂类,这 ...

  3. Hadoop-2.4.1完全分布式环境搭建

      Hadoop-2.4.1完全分布式环境搭建   Hadoop-2.4.1完全分布式环境搭建 一.配置步骤如下: 主机环境搭建,这里是使用了5台虚拟机,在ubuntu 13系统上进行搭建hadoop ...

  4. 浅谈移动Web开发(上):深入概念

    PPI 什么是PPI PPI的复杂之处在于如果他所属的上下文环境不同,意义也会完全不一样. 当我们在谈论显示设备的PPI时,它代指的屏幕的像素密度:当我们在谈论和图片相关时,我们谈论的是打印时的分辨率 ...

  5. Nodejs使用coffeescript编写的用户注册/登陆代码(MySQL)

    记录一下,以备后用 Settings = require '../../settings.js' exports.register = (req, res) -> nick_name = req ...

  6. AutoMapper 创建嵌套对象映射(原创)

    之前在做DTO转换时,用到AutoMapper.但DTO的层次太深了,无奈官方没针对嵌套类型提供好的解决方案,于是自己实现了一下: 思路:采用递归和反射很好的避免手工创建嵌套对象的映射. 第一个版本, ...

  7. 疯狂html5演讲(两):HTML5简经常使用的元素和属性(一个):html5保留经常使用的元素

    html5取出一小部分的元素和属性:主要删除的各种元素和属性与文档相关的风格.例<font>.width等待,html5建议规范css样式表来控制html文档样式. 1.基本元素 < ...

  8. openwrt构建过程探索

    参考网站:http://wiki.openwrt.org/doc/howto/buildroot.exigence 需要下载必要的库文件,编译器等... 1 首先要获得openwrt的源码,参考ope ...

  9. 织梦不仅是链接到其他调用next

    //打开系统文件织梦 /include/arc.archives.class.php 找到GetPreNext函数 function GetPreNext($gtype='') { $rs = ''; ...

  10. 常用在网站上的30个jQuery插件

    jQuery插件是网页设计师最喜欢的.从图像滑块,图像画廊和导航插件,它们是如此众多,如此多样,如此惊人的和互动可以制作美化网站.在本文的在30个插件中,我认为必须在网站建设时用到.当然你现在可能不善 ...