跳至主要内容

博文

目前显示的是 2015的博文

Patterns Learned Fom `Iterator`

Pattern one: When it comes to iterators, we can easily come up with that its use in abstracting the container and simplify the iteration operation like following example shows: Iterator it = container . iterator () while ( it . hasNext ()) { a = it . next (); // do something } No matter which kind of container you are using (the container has to be iterable and as far as I know, the commonly-used container are all iterable.), you can re-use this piece of code without any change. And this may be extract as a method, like following: public void doIterate ( Iterator it ) { while ( it . hasNext ()) { a = it . next (); // do something } } You can even make it more general with another parameter: public void doIterate ( Iterator it , Function f ) { while ( it . hasNext ()) { a = it . next (); f ( a ); } } This kind of design pattern can isolate the module of handling elements in container, whic

Singleton and Synchronization

Why synchronized in singleton I will describe what I encounter to convince you it is really needed to do so. I have the Class A in the Thread-use : Singleton s1 = Singleton.getInstance(); synchronized(s1){ while (!B.ready){ s1.wait(); } // read from singleton } Then Class B in Thread-readData : // notice the volatile static volatile boolean ready = false; Singleton s2 = Singleton.getInstance(); synchronized(s2){ // read data than write to singleton ready = true; s2.notify(); } Then Singleton : public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } This getInstance() is not synchronized now. If the first thread enter the if clause first, then the second thread get the cpu also enter it ( if clause ) when the instance are still null , so they create two Singleton and return separately . As a result, the s1 and s2 point to the different objects which cause

Learning Note: constant

一. Java Java use `final` to represent a constant: compile-time constant value initialized at run-time but not change ever since data can be: primitive -- the data can't be changed object reference -- the reference can't change but the object can change // can also be compile -time constants:   public static final int VALUE_THREE = 39 ; // can also be run-time constants: private final int i4 = rand . nextInt ( 20 ); static final int INT_5 = rand . nextInt ( 20 ); // a final reference private final String s1 = new String ( "s1" );   二. c++ c++ using the keyword `const` to address this: compile-time constant value initialized at run-time but not change ever since (see following -- cited from stackoverflow) As a static or function-local variable: const int x = calcConstant();     As a class member: struct ConstContainer { ConstContainer( int x) : x(x) {} c