`

Effective Java 2nd edition

阅读更多

Item 3: Enforce the singleton property with a private constructor or an enum type

 

While this approach has yet to be widely
adopted
, a single-element enum type is the best way to implement a singleton.

 

have yet to is a phrasal verb, like Certain questions have yet to be clarified.

 

have yet to do sth. = have not yet done sth.

 

interface HasAge {
    public int getAge();
}

public enum Elvis implements HasAge {
    INSTANCE;
    private int age;

    @Override
    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        System.out.println(Elvis.INSTANCE.getAge());
    }
}

 

like this one, static methods in traditional singleton implementation cannot achieve this, as it's non-static method.

 

and why doesn't the enum singleton have the deserialization problem? here's probably the anwser:

 

Enum constants are deserialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not transmitted.

http://electrotek.wordpress.com/2008/08/06/singleton-in-java-the-proper-way/

 

Item 77: For instance control, prefer enum types to readResolve

 

This class restricts access to its constructor to ensure that only a single
instance is ever created

As noted in Item 3, this class would no longer be a singleton if the words
“implements Serializable” were added to its declaration.

 

The readResolve feature allows you to substitute another instance for the one
created by readObject
[Serialization, 3.7].If the class of an object being deserialized
defines a readResolve method with the proper declaration, this method is
invoked on the newly created object after it is deserialized. The object reference
returned by this method is then returned in place of the newly created object. In
most uses of this feature, no reference to the newly created object is retained, so it
immediately becomes eligible for garbage collection.

 

Item 5: Avoid creating unnecessary objects

 

Reuse can be both faster and more stylish. An object can always be reused if it is immutable.

class Person {
    private final Date birthDate;
    // Other fields, methods, and constructor omitted
    /**
     * The starting and ending dates of the baby boom.
     */
    private static final Date BOOM_START;
    private static final Date BOOM_END;

    static {
        Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
        BOOM_START = gmtCal.getTime();
        gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
        BOOM_END = gmtCal.getTime();
    }

    public boolean isBabyBoomer() {
        return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0;
    }
}

 you see, it uses static instances instead of local variables.

 

prefer primitives to boxed primitives, and watch out for unintentional autoboxing.

 

This item should not be misconstrued to imply that object creation is expensive
and should be avoided. On the contrary, the creation and reclamation of small
objects whose constructors do little explicit work is cheap, especially on modern
JVM implementations. Creating additional objects to enhance the clarity, simplicity,
or power of a program is generally a good thing.

 

Item 6: Eliminate obsolete object references


You can think of direct references as strong references that require no extra coding to create or access the object. The remaining three types of references are subclasses of the

    Reference class found in the java.lang.ref package. Soft references are provided by the SoftReference class, weak references by the WeakReference class, and phantom references by PhantomReference.

    Soft references act like a data cache. When system memory is low, the garbage collector can arbitrarily free an object whose only reference is a soft reference. In other words, if there are no strong references to an object, that object is a candidate for release. The garbage collector is required to release any soft references before throwing an OutOfMemoryException.

    Weak references are weaker than soft references. If the only references to an object are weak references, the garbage collector can reclaim the memory used by an object at any time. There is no requirement for a low memory situation. Typically, memory used by the object is reclaimed in the next pass of the garbage collector.

    Phantom references relate to cleanup tasks. They offer a notification immediately before the garbage collector performs the finalization process and frees an object. Consider it a way to do cleanup tasks within an object.

 

import java.lang.ref.WeakReference;

public class WeakTest {
    public static void main(String[] args) {
        String s = new String("Hello");
        WeakReference<String> wr = new WeakReference<String>(s);
        s = null;                                                                    
        System.gc();
        System.out.println(wr.get());
    }
}

s is strong reference, and wr is weak reference, after gc, it prints null, it shows that the object with only the weak reference would be taken back.

 

Item 7: Avoid finalizers

In Java, the garbage collector reclaims the storage associated with an object when it becomes
unreachable , requiring no special effort on the part of the programmer.

 

Item 70: Document thread safety

 

Documenting a conditionally thread-safe class requires care. You must indicate
which invocation sequences require external synchronization, and which lock
(or in rare cases, which locks) must be acquired to execute these sequences. Typically
it is the lock on the instance itself, but there are exceptions. If an object represents
a view on some other object, the client generally must synchronize on the
backing object, so as to prevent its direct modification. For example, the documentation
for Collections.synchronizedMap says this:
It is imperative that the user manually synchronize on the returned map when
iterating over any of its collection views:

Map m = Collections.synchronizedMap(new HashMap());

...

Set s = m.keySet(); // Needn't be in synchronized block

...

synchronized(m) { // Synchronizing on m, not s!

    Iterator i = s.iterator(); // Must be in synchronized block

    while (i.hasNext()) foo(i.next());

}
 

Failure to follow this advice may result in non-deterministic behavior.

 

now the question is why needn't be in synchronized block?

 

answer:

Without Collections.synchronizedMap() (assuming there is no external synchronization) the behaviour will be non-deterministic.
1. The use of the above method ensures that any thread trying to execute a method of Map will be forced to aquire lock on the Map.
2. But the above method does NOT make access through ITERATORS synchronized. So if we are accessing through iterators, such access must be separately synchronized on the Map.
Consider what may happen if we do not use the synchronizedMap() method (and also do not externally synchronize). Then Thread1 and Thread2 may concurrently execute the above code. Thread1 may call keySet() even while Thread2 is concurrently modifying the Map maybe in foo(i.next()). Clearly the results will be unpredicatable.

http://www.coderanch.com/t/231408/threads/java/Synchronized-method-blocks

 

 

分享到:
评论

相关推荐

    [Java] Effective Java 第2版 (英文版)

    [Addison-Wesley] Effective Java 2nd Edition (E-Book) ☆ 出版信息:☆ [作者信息] Joshua Bloch [出版机构] Addison-Wesley [出版日期] 2008年05月28日 [图书页数] 346页 [图书语言] 英语 [图书格式] PDF ...

    Effective-Java-2nd-Edition-(May-2008).zip_effective java

    《Effective Java》是Java编程领域的一本经典著作,由Joshua Bloch撰写,第二版发布于2008年。这本书旨在提供实用的编程指导,帮助开发者写出更高效、更可维护的Java代码。以下是对书中核心知识点的详细解读: 1. *...

    1_Effective_Java_2nd_Edition_proglib_java_Joshua_

    《Effective Java》是Java编程领域的一本经典著作,由知名程序员和计算机科学家Joshua Bloch撰写。这本书的第二版深入探讨了如何编写高效、可维护的Java代码,并提供了许多实用的编程指南和最佳实践。以下是根据标题...

    Effective.Java, 2nd.edition (2008.05)

    《Effective Java》第二版(2008年5月出版)是一本由Joshua Bloch编写的Java编程经典书籍。该书以其深入浅出的写作方式、贴近实际应用的编程指导,对Java编程语言及其面向对象编程的特点进行了详尽的介绍与分析。...

    Java-Effective:Java Effective 2nd Edition书中的源代码

    《Effective Java》是Java开发领域的经典著作,由Joshua Bloch撰写,第二版更是程序员们不可或缺的参考书籍。这本书深入探讨了如何编写出高质量、高效、可维护的Java代码,涵盖了众多最佳实践和设计模式。这里我们将...

    java源码期编译器运行时-Effective-JAVA-Summary:JoshuaBloch的EffectiveJava2ndEditio

    Effective Java 2nd Edition 的总结。 我在学习时使用它并作为快速参考。 它不打算作为本书的独立替代品,因此如果您真的想学习此处介绍的概念,请购买并阅读本书并将此存储库用作参考和指南。 如果你是发布者并且...

    Java弱引用与WeakHashMap

    在《Effective Java 2nd Edition》中,第6条“消除过期的对象引用”提到,虽然Java有垃圾回收机制,但是只要是自己管理的内存,应该警惕内存泄露的问题,例如的对象池、缓存中的过期对象都有可能引发内存泄露的问题...

    Core PYTHON Programming, 2nd Edition (epub 格式, Python 2.5)

    Core PYTHON Programming, 2nd Edition (epub 格式, Python 2.5) Python is an agile, robust, expressive, fully object-oriented, extensible, and scalable programming language. It combines the power of ...

    Packt.Gradle.Effective.Implementations.Guide.2nd.Edition

    作为一款强大的自动化构建工具,Gradle在Java、Android和其他多种语言的项目中广泛应用,其灵活性和扩展性使得它在软件开发领域占据了一席之地。 本书首先从基础开始,详细介绍了Gradle的基本概念,包括它的构建...

    Selenium.Testing.Tools.Cookbook.2nd.Edition.178439251

    This book is intended for software quality assurance/testing professionals, software project managers, or software developers with prior experience in using Selenium and Java to test web-based ...

    Software Development, Design and Coding-2nd Edition-Apress(2017).pdf

    I hope that by the end of the book you’ll have a much better idea of what the design of good programs is like, what makes an effective and productive developer, and how to develop larger pieces of ...

    Java电子书.pdf

    * Effective Java, 2nd Edition(新版):这本书涵盖了 Java 语言的核心技术,包括 Java 语言的语法、Java 虚拟机、Java 库、Java GUI 编程等。 Java 高级编程 * Java 数据库高级编程宝典:这本书涵盖了 Java 语言...

    哪本书适合推荐给 Java 初学者?

    * 《Head First Java, 2nd Edition(中文版)》:这本书不仅内容丰富、有趣且通俗易懂,并且涵盖了所有 Java 相关的基础知识。如果你是 Java 初学者,这本书正适合你。 * 《Java 核心技术(卷 1、2)》:这本书写作...

    最新Java电子书.pdf

    "Swing Extreme Testing"、"MiniEditor"和"Effective Java, 2nd Edition(新版)"涉及UI测试、小型编辑器实现以及编程最佳实践。 "Java2 Api大全完整版 (上)"、"Java 语言程序设计 - 计算机与信息技术专业应用教材"、...

    最新Java电子书文.pdf

    * 《Effective Java, 2nd Edition》:这本书是 Java 语言的经典教材,涵盖了 Java 语言的高级开发技术和最佳实践。 3. Java 数据库应用 * 《Java 数据库高级编程宝典》:这本书涵盖了 Java 语言的数据库应用开发...

Global site tag (gtag.js) - Google Analytics