Lazy initialization - It decreases the cost of initializing a class or creating an instance, at the expense of increasing the cost of accessing the lazily initialized field. Depending on what fraction of lazily initialized fields eventually require i…
Java Native Interface(JNI) allows Java applications to call native methods, which are special methods written in native programming languages such as C or C++. Historical usages of native methods Access to platform-specific facilities such as registr…
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st language I have chosen for this migration. It's a nice chance to read some great books like "Effective Java 2nd Edition" and share the note for what I…
Chapter 10 Concurrency Item 66: Synchronize access to shared mutable data synchronized这个关键字不仅保证了同步,还保证了可见性(visibility). 对于变量的读写是原子性的,除非变量类型是long或double.有一个我见过无数遍的例子就是设一个共享的boolean变量,然后从一个线程中断另一个线程的while循环.因为JVM会做优化,但它做优化的前提是假设下面这些代码都是在单线程下运行的,比如可能把wh…
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating and Destroying Objects Consider static factory methods instead of constructors Consider a builder when faced with many constructor parameters Enforce the s…
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Objects Consider static factory methods instead of constructors (factory方法可以拥有名称,可以避免重复创建,比如单例模式) Consider a builder when faced with many constructor parameter…
Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用实例域,例如: 1 /** 2 * 枚举类型错误码 3 * Created by yulinfeng on 8/20/17. 4 */ 5 public enum ErrorCode { 6 FAILURE(0), 7 SUCCESS(1); 8 9 private final int code;…
66.同步访问共享的可变数据 JVM对不大于32位的基本类型的操作都是原子操作,所以读取一个非long或double类型的变量,可以保证返回的值是某个线程保存在该变量中的,但它并不能保证一个线程写入的值对于另一个线程是可见的.因此在读或写原子数据时,使用线程同步是有必须要的,否则将时线程间数据不一致. public class ThreadTest { private static boolean stopRequested; //原子操作 public static void main(Str…
首先这两种方式都是延迟初始化机制,就是当要用到的时候再去初始化. 但是Effective Java书中说过:除非绝对必要,否则就不要这么做. 1. DCL (double checked locking)双重检查: 如果出于性能的考虑而需要对实例域(注意这个属性并没有被static修饰)使用延迟初始化,就使用双重检查模式 public class Singleton { private volatile Singleton uniqueInstance; private Singleton(){…
66:同步访问共享的可变数据 synchronized:1互斥,阻止线程看到的对象处于不一致的状态:2保证线程在进入同步区时能看到变量的被各个线程的所有修改 Java中,除了long或者double,“读”或者“写”一个变量是原子的.注意:是读或者写单个动作是源自的,而不是读写这两个动作整体是原子的. 由于虚拟机会对代码进行优化,所以可能会导致一些错误:可能你想的是在另一线程中改变done的值来终止while循环,但是优化之后却无法做到这样.要避免这样的优化错误,就必须对done同步. //优化…