immutable

Guava学习笔记:Immutable(不可变)集合

空扰寡人 提交于 2019-12-04 16:10:23
  不可变集合,顾名思义就是说集合是不可被修改的。集合的数据项是在创建的时候提供,并且在整个生命周期中都不可改变。   为什么要用immutable对象?immutable对象有以下的优点:     1.对不可靠的客户代码库来说,它使用安全,可以在未受信任的类库中安全的使用这些对象     2.线程安全的:immutable对象在多线程下安全,没有竞态条件     3.不需要支持可变性, 可以尽量节省空间和时间的开销. 所有的不可变集合实现都比可变集合更加有效的利用内存 (analysis)     4.可以被使用为一个常量,并且期望在未来也是保持不变的   immutable对象可以很自然地用作常量,因为它们天生就是不可变的对于immutable对象的运用来说,它是一个很好的防御编程(defensive programming)的技术实践。    JDK中实现immutable集合   在JDK中提供了Collections.unmodifiableXXX系列方法来实现不可变集合, 但是存在一些问题,下面我们先看一个具体实例: import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test;

Java 可变对象和不可变对象

为君一笑 提交于 2019-12-03 20:53:26
一、简单定义 不可变对象(Immutable Objects)即对象一旦被创建它的状态(对象的数据,也即对象属性值)就不能改变 ,反之即为可变对象(Mutable Objects)。 不可变对象的类即为不可变类(Immutable Class)。Java平台类库中包含许多不可变类,如String、基本类型的包装类、BigInteger 和 BigDecimal等。 二、优缺点 不可变对象有很多优点: 构造、测试和使用都很简单 线程安全且没有同步问题,不需要担心数据会被其它线程修改 当用作类的属性时不需要保护性拷贝 可以很好的用作Map键值和Set元素 不可变对象最大的缺点就是创建对象的开销,因为每一步操作都会产生一个新的对象。 三、编写不可变类 可以遵照以下几点来编写 一个不可变类 : 确保类不能被继承 - 将类声明为final, 或者使用静态工厂并声明构造器为private 声明属性为private 和 final 不要提供任何可以修改对象状态的方法 - 不仅仅是set方法, 还有任何其它可以改变状态的方法 如果类有任何可变对象属性, 那么当它们在类和类的调用者间传递的时候必须被保护性拷贝 代码-1: import java.util.Date; /** * Planet是一个不可变类,因为当它构造完成之后没有办法改变它的状态 */ public final class

java并发编程——不可变对象

非 Y 不嫁゛ 提交于 2019-12-03 20:53:16
不可变类 不可变类:指这个类的实例一旦创建完成后,就不能改变其成员变量值。如JDK内部自带的8个包装类和String类都是不可变类(Interger、Long和String等)都是不可变类。 所以不可变类并不是指该类是被final修饰的,而是指该类的所有属性是被final修饰的 。 可变类:相对于不可变类,可变类创建实例后可以改变其成员变量值,开发中创建的大部分类都属于可变类。 java中自定义不可变类应该遵守如下原则: 使用private和final修饰符来修饰该类的属性。 提供带参数的构造器,用于根据传入的参数来初始化属性。 仅为该类属性提供getter方法,不要提供setter方法。 如果有必要,重写hashCode和equals方法,同时应保证两个用equals方法判断为相等的对象,其hashCode也应相等。 使用不可变类的好处? Immutable对象是线程安全的,可以不用被synchronize就在并发环境中共享 Immutable对象简化了程序开发,因为它无需使用额外的锁机制就可以在线程间共享 Immutable对象提高了程序的性能,因为它减少了synchroinzed的使用 Immutable对象是可以被重复使用的,你可以将它们缓存起来重复使用,就像字符串字面量和整型数字一样。你可以使用静态工厂方法来提供类似于valueOf()这样的方法

Immutable objects are thread safe, but why?

匿名 (未验证) 提交于 2019-12-03 09:05:37
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: If one thread is creating populating the reference variable of the immutable class by creating its object and at the second time the other thread kicks in before the first thread completes and creates another object of the immutable class, won't the immutable class usage be thread unsafe? Creating a immutable object also says that all fields to marked as final as..... "it may be necessary to ensure correct behavior if a reference to a newly created instance is passed from one thread to another without synchronization" Are they trying to say

Is an immutable Bitmap faster then a mutable one?

匿名 (未验证) 提交于 2019-12-03 03:04:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: The Bitmap class has a method copy() with the signature below: public Bitmap copy(Bitmap.Config config, boolean isMutable) Is there a performance difference between a mutable and an immutable Bitmap ? 回答1: Romain Guy answered in the comments: To answer the original question: no, there is no performance difference. There are some optimizations we could implement for mutable bitmaps though. Hopefully in a future release :) 回答2: There is no performance difference. This will not affect the performance of your app. If you want to perform any

Cannot borrow as mutable because it is also borrowed as immutable

匿名 (未验证) 提交于 2019-12-03 02:28:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I am learning Rust and I don't quite get why this is not working. #[derive(Debug)] struct Node { value: String, } #[derive(Debug)] pub struct Graph { nodes: Vec<Box<Node>>, } fn mk_node(value: String) -> Node { Node { value } } pub fn mk_graph() -> Graph { Graph { nodes: vec![] } } impl Graph { fn add_node(&mut self, value: String) { if let None = self.nodes.iter().position(|node| node.value == value) { let node = Box::new(mk_node(value)); self.nodes.push(node); }; } fn get_node_by_value(&self, value: &str) -> Option<&Node> { match self

Immutable object pattern in C# - what do you think? [closed]

匿名 (未验证) 提交于 2019-12-03 02:13:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I have over the course of a few projects developed a pattern for creating immutable (readonly) objects and immutable object graphs. Immutable objects carry the benefit of being 100% thread safe and can therefore be reused across threads. In my work I very often use this pattern in Web applications for configuration settings and other objects that I load and cache in memory. Cached objects should always be immutable as you want to guarantee they are not unexpectedly changed. Now, you can of course easily design immutable objects as in the

Immutable value as inout argument

匿名 (未验证) 提交于 2019-12-03 01:33:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I would like to have a pointer as a parameter of a class. But when I am trying to code the init, I am having this error: Cannot pass immutable value of type 'AnyObject?' as inout argument class MyClass { var valuePointer: UnsafeMutablePointer<AnyObject?> init(value: inout AnyObject?) { self.valuePointer = &value } } I would like to create some instance of MyClass which can all refer to the same "value". Then, when I am editing this value in this class, it would change everywhere else. This is the first time I'm working with pointer in Swift.

Immutable.js Push into array in nested object

匿名 (未验证) 提交于 2019-12-03 01:33:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: Assume there is an object: const object = { 'foo': { 'bar': [1, 2, 3] } } I need to push 4 to object.foo.bar array. Right now I'm doing it like this: const initialState = Immutable.fromJS(object) const newState = initialState.setIn( ['foo', 'bar', object.foo.bar.length], 4 ) console.log(newState.toJS()) But I don't really like it, since I need to use object.foo.bar.length in the path. In my real example object is nested much deeper, and getting array's length looks very ugly. Is there another, more convenient way? 回答1: This should work

What makes immutable objects to be published without safe publication techniques?

匿名 (未验证) 提交于 2019-12-03 00:56:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: What does it mean to say that immutable objects can be published even without resorting to safe publication idioms? I have read Java Concurrency in Practice ( Chapter 3 , Sharing Objects ) but still not able to comprehend the statement : Immutable objects can be published through any mechanism. V/S Effectively immutable objects should be safely published. Edit: I have been through a similar question on SO and the answers but still unable to understand how immutable objects can be published safely because there is a chance that the field