---

layout: post
title: "Effective JAVA(2)"
category:

tags: []

{% include JB/setup %}

Item 3:

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

A singleton is simple a class that is instantiated exactly once.

Approach 1:
    public static final Elvis INSTANCE = new Elvis();

Approach 2:
    private static final Elvis INSTANCE = new Elvis();
    public static Elvis getInstance() { return INSTANCE; }

The main advantage of the public field approach is that the declarations make it clear that the class is a singleton.

One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return a unique instance for each thread that invokes it. A second advantage, concerning generic types.

To make a singleton class that is implemented using either of the previous approaches serializable. Otherwise, each time a serialized instance is deserialized, a new instance will be created. To prevent this, add this readResolve method to the Elvis class:

// readResolve method to preserve singleton property

private Object readResolve() {
// Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}

There is a third approach to implementing singletons. Simply make an enum type with one element:

// Enum singleton - the preferred approach

public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

A single-element enum type is the best way to implement a singleton.

Item 4:

Enforce noninstantiability with a private constructor

Attempting to enforce noninstantiability by making a class abstract does not work.

A class can be made noninstantiable by including a private constructor:

// Noninstantiable utility class

public class UtilityClass
{
// Suppress default constructor for noninstantiability
private UtilityClass()
{
throw new AssertionError();
}
... // Remainder omitted
}

It guarantees that the class will never be instantiated under any circumstances.

Item 5:

Avoid creating unnecessary objects

You can often avoid creating unnecessary objects by using static factory methods. For example, the static factory method Boolean.valueOf(String) is almost always preferable to the constructor Boolean(String)

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;
    } 
}

The Person class creates Calendar, TimeZone, and Date instances only once, when it is initialized, instead of creating them every time isBabyBoomer is invoked.

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

2015/10/25

---

layout: post
title: "Effective JAVA(1)"
category:

tags: ["读书", "Java"]

{% include JB/setup %}

Item 1:

Consider static factory methods instead of constructors

The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. A class can provide a public static factory method, which is simply a static method that returns an instance of the class.

A class can provide its clients with static factory methods instead of, or in addition to, constructors.

One advantage of static factory methods is that, unlike constructors, they have names.

A static factory with a well-chosen name is easier to use and the resulting client code easier to read. For example, the constructor BigInteger(int, int, Randon)m which returns a BigInteger that is probably prime, would have been better expressed as a static factory method named BigInteger.probablePrime.

In case where a class seems to require multiple constructors with the same signature, replace the constructors with static factory methods and carefully chosen names to highlight their differences.
A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they're invoked.

The Boolean.valueOf(boolean) method illustrates this technique: it never creates an object. Instance control allows a class to guarantee that it is a singleton or noninstantiable. It allows an immutable class to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b

A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.

A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

Map<String, List<String>> m = new HashMap<String, List<String>>();

OR

public static <K, V> HashMap<K, V> newInstance(){
    return new HashMap<K, V>();
} 

Map<String, List<String>> m = HashMap.newInstance();
The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods (names of static methods for different classes could be identical).

Item 2:

Consider a builder when faced with many constructor parameters

Static factories and constructors share a limitation: they do not scale well to large numbers of optional parameters.

Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameter, a third with two optional parameters, and so on.

NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27);

The telecoping constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it.

A second alternative when you are faced with many constructor parameters is the JavaBeans pattern, in which you call a parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest.

The JavaBeans pattern has serious disadvantages of its own. Because construction is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction.

A third alternative is BUILDER Pattern.

Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Finally, the client calls a parameterless build method to generate the object, which is immutable.

public class NutritionFacts 
{
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;

    public static class Builder 
    {
        // Required parameters
        private final int servingSize;
        private final int servings;
        // Optional parameters - initialized to default values
        private int calories      = 0;
        private int fat           = 0;
        private int carbohydrate  = 0;
        private int sodium        = 0;

        public Builder(int servingSize, int servings) 
        {
            this.servingSize = servingSize;
            this.servings    = servings;
        }

        public Builder calories(int val)
        { calories = val;      return this; }

        public Builder fat(int val)
        { fat = val;           return this; }

        public Builder carbohydrate(int val)
        { carbohydrate = val;  return this; }

        public Builder sodium(int val)
        { sodium = val;        return this; }

        public NutritionFacts build() 
        {
            return new NutritionFacts(this);
        } 
    }

    private NutritionFacts(Builder builder) 
    {
        servingSize  = builder.servingSize;
        servings     = builder.servings;
        calories     = builder.calories;
        fat          = builder.fat;
        sodium       = builder.sodium;
        carbohydrate = builder.carbohydrate;
    } 
}
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();

The builder pattern is a good choice when designing classes whose constructor or static factories would have more than a handful of parameters.

2015/10/25

---

layout: post
title: "Memcached"
category:

tags: ["读文章"]

{% include JB/setup %}

  • 需要被缓存的对象或数据以key/value对的形式保存在服务器端,每个被缓存的对象或数据都有唯一的标示符key,存取操作通过这个key进行。保存到memcached中的对象或数据放置到内存中,并不会作为文件存储在磁盘上,所以存取速度非常快。

  • 由于没有对这些对象进行持久性存储,因此在服务器端的服务重启之后存储在内存中的这些数据就会消失。而且当存储的容量达到启动时设定的值时,就自动使用LRU算法删除不用的缓存,memcacahed是为缓存而设计的服务器,因此在设计之初没有过多考虑数据的永久性问题。

  • Memcached利用Slab Allocation机制来分配和管理内存。

  • 传统的内存管理方式是:使用完通过malloc非配的内存后通过free来回收内存。这种方式容易产生内存碎片并降低操作系统对内存的管理效率。

  • Slab A类location机制不存在这样的问题,它按照预先规定的大小,将分配的内存分割成特定长度的内存块,再把尺寸相同的内存块分成组,这些内存块不会释放,可以重复利用。

  • Memcached服务器端保存着一个空闲的内存块列表,当有数据存入时根据接收到的数据大小,分配一个能存下这个数据的最小内存块。这种方式有时会造成内存浪费,(例如:将一个200字节的数据存入一个300字节的内存块中,会有100字节内存被浪费掉,不能使用)。避免浪费内存的方法是,预先计算出应用存入的数据大小,或把同一业务类型的数据存入一个Memcached服务器中,确保存入的数据大小相对均匀,这样就可以减少对内存的浪费。还有一种方法是,在启动时指定“-f”参数,能在某种程度上控制内存组之间的大小差异。在应用中使用memcached时,通常可以不重新设置这个参数,而用默认值“1.25”进行部署。

  • 缓存一般用来保存一些经常存取的对象或数据,通过缓存来存取对象或数据要比磁盘存取快很多。Memcache是一种内存缓存,把经常存取的对象或数据缓存在内存中,内存中缓存的这些数据通过API的方式被存取,数据就像一张大的HASH表,以key-value对的方式存在。

  • Memcache通过缓存经常被存取的对象或数据,来减轻数据库的压力,提高网站的响应速度,构建速度更快的可拓展的Web应用。

Memcache和数据库协作的流程:
  • 检查客户端的请求的数据是否在Memcached中存在,如果存在,直接把请求的数据返回,不再对数据进行任何操作。
  • 如果请求的数据不在Memcache中,就去查询数据库,把从数据库中获取的数据返回给客户端,同时把数据缓存一份到Memcache中。
  • 每次更新数据库(如更新、删除数据库的数据)的同时更行Memcache中的数据,保证Memcache中的数据和数据库中的数据一致。
  • 当分配给Memcache内存空间用完之后,会使用LRU策略加到期失效策略,失效的数据首先被替换掉,然后在替换掉最近未使用的数据。

Memcached使用一种Lazy Expiration策略,自己不会监控存入的key/value对是否过期,而是在获取key值时查看记录的时间戳,检查key/value对空间是否过期。这种策略不会在过期检测上浪费cpu资源。

2015/10/25

---

layout: post
title: "CDN"
category:

tags: ["读文章"]

{% include JB/setup %}

  • A content delivery network or content distribution network is a system of computers containing copies of data placed at various nodes of a network. When properly designed and implemented, a CDN can improve access to the data it caches by increasing access bandwidth and redundancy and reducing access latency, Data content types often caches in CDNs including web objects, downloadable objects....

  • The capacity sum of strategically placed servers can be higher than the network backbone capacity. This can result in an impressive increase in the number of concurrent users. For instance, when there is a 10 Gbit/s network backbone and 200 Gbit/s central server capacity, only 10 Gbit/s can be delivered. But when 10 servers are moved to 10 edge locations, total capacity can be 10 10 Gbit/s.

  • Strategically placed edge servers decrease the load on interconnects, public peers, private peers and backbones, freeing up capacity and lowering delivery costs. It uses the same principle as above. Instead of loading all traffic on a backbone or peer link, a CDN can offload these by redirecting traffic to edge servers.

  • CDN generally deliver content over TCP and UDP connections.

  • TCP throughput over a network is affected by both latency and packet loss. In order to reduce both of these parameters, CDNs traditionally place servers as close to the edge networks that users are on as possible. Theoretically the closer the content the faster the delivery, although network distance may not be the factor that leads to best performance. End users will likely experience less jitter, fewer network peaks and surges, and improved stream quality- especially in remote areas. The increased reliability allows a CDN operator to deliver HD quality content with high Quality of Service, low costs and low network load. Some providers also utilize TCP acceleration technology to further boost CDN’s performance and end-user experiences.

  • CDN nodes are usually deployed in multiple locations, often over multiple backbones. These nodes cooperate with each other to satisfy requests for content by end users, transparently moving content to optimize the delivery process. Optimization can take the form of reducing bandwidth costs, improving end-user performance (reducing page load times and improving user experience), or increasing global availability of content.

  • Requests for content are typically algorithmically directed to nodes that are optimal in some way. When optimizing for performance, locations that are best for serving content to the user may be chosen. This may be measured by choosing locations that are the fewest hops, the fewest number of network seconds away from the requesting client, or the highest availability in terms of server performance (both current and historical), so as to optimize delivery across local networks. When optimizing for cost, locations that are least expensive may be chosen instead.

  • In an optimal scenario, these two goals tend to align, as servers that are close to the end user at the edge of the network may have an advantage in performance or cost. The edge network is grown outward from the origin/s by further acquiring (via purchase, peering, or exchange) co- location facilities, bandwidth and servers.

  • The Internet was designed according to the end-to-end principle. This principle keeps the core network relatively simple and moves the intelligence as much as possible to the network end-points: the hosts and clients. As a result the core network is specialized, simplified, and optimized to only forward data packets.

  • Content Delivery Networks augment the end-to-end transport network by distributing on it a variety of intelligent applications employing techniques designed to optimize content delivery. The resulting tightly integrated overlay uses web caching, server-load balancing, request routing, and content services.

  • Web caches store popular content on servers that have the greatest demand for the content requested. These shared network appliances reduce bandwidth requirements, reduce server load, and improve the client response times for content stored in the cache.

  • Server-load balancing uses one or more techniques including service based (global load balancing) or hardware based, known as a web switch, content switch, or multilayer switch to share traffic among a number of servers or web caches. Here the switch is assigned a single virtual IP address. Traffic arriving at the switch is then directed to one of the real web servers attached to the switch. This has the advantage of balancing load, increasing total capacity, improving scalability, and providing increased reliability by redistributing the load of a failed web server and providing server health checks.

  • A content cluster or service node can be formed using a layer 4-7 switch balance load across a number of servers or a number of web caches within the network.

  • Request routing directs client requests to the content source best able to serve the request. This may involve directing a client request to the service node that is closest to the client, or to the one with the most capacity.

  • CDNs use a variety of methods of content delivery including, but not limited to, manual asset coping, active web caches, and global hardware load balancers.

  • Although peer-to-peer is not traditional CDN technology, it is increasingly used to deliver content to end users. P2P claims low cost and efficient distribution. Even though P2P actually generates more traffic than traditional client-server CDNs for the edge provider (because a
    peer also uploads data instead of just downloading it) it’s welcome by parties running content delivery/distribution services. The real strength of P2P shows when one has to distribute data in high demand, like the latest episode of a television show or some sort of software patch/update in short period of time. One of the advantages of this is that the more people who download the same data, the more efficient P2P is for the provider, slashing the cost of the transit fees that a CDN provider has to pay to their upstream IP transit providers.

2015/10/25

---

layout: post
title: "Design Patterns"
category:

tags: [“Java”, "设计模式"]

{% include JB/setup %}

Adapter

保持系统的多态性。让第三方接口符合系统已定义的的接口。

你把数据给我,我来带你转给第三方办,你不要关心我是怎么办到的,你不关心我找谁办的,反正肯定给你办成。

我的系统里已经实现了点、线、正方形,现在客户要求我们实现一个圆形

我们会建立一个Circle类来继承Shape,然后需要去实现display、fill、undisplay方法

但是这时我发现同事已经实现了一个画圆的类,但是他的方法名为displayIt、fillIt、undisplayIt

我们不能直接使用这个类,因为那样无法保持多态性,

class Circle extends Shape
{
    private XXCircle pxc; 

    public Circle()
    { 
        pxc = new XXCircle(); 
    } 

    public void display()
    { 
        pxc.displayIt(); 
    } 
} 

Abstract Factory

public interface Creator
{
  public ProductA factoryA();
  public ProductB factoryB();
}

具体工厂类1:

public class ConcreteCreator1 implements Creator
{
  public ProductA factoryA()
  {
        return new ProductA1();
  }

  public ProductB factoryB()
  {
        return new ProductB1();
  }
}

具体工厂类2:

public class ConcreteCreator2 implements Creator
{
  public ProductA factoryA()
  {
        return new ProductA2();
  }

  public ProductB factoryB()
   {
      return new ProductB2();
  }
}

Factory--->UnixFactory/WinFactory

Button--->UnixButton/WinButton
Text----->UnixText/WinText
Unix产品族和Windows产品族,不会同时使用。

//两种抽象产品:水果、蔬菜
public interface Fruit
{

}
public interface Veggie
{

}

//四种具体产品:北方水果,热带水果,北方蔬菜,热带蔬菜
//Northern Fruit
public class NorthernFruit implements Fruit
{
  private String name;
  public NorthernFruit(String name)
  {

  }
  public String getName()
  {
        return name;
  }
  public void setName(String name)
  {
        this.name = name;
  }
}
//TropicalFruit
public class TropicalFruit implements Fruit
{
  private String name;
  public TropicalFruit(String name)
  {

  }
  public String getName()
  {
      return name;
  }
  public void setName(String name)
  {
      this.name = name;
  }
}
//NorthernVeggie
public class NorthernVeggie implements Veggie
{
  private String name;
  public NorthernVeggie(String name)
  {

  }
  public String getName()
  {
      return name;
  }
  public void setName(String name)
  {
      this.name = name;
  }
}
//TropicalVeggie
public class TropicalVeggie implements Veggie
{
  private String name;
  public TropicalVeggie(String name)
  {

  }
  public String getName()
  {
      return name;
  }
  public void setName(String name)
  {
      this.name = name;
  }
}
//抽象工厂角色
public interface Gardener
{
  public Fruit createFruit(String name);
  public Veggie createVeggie(String name);
}
//具体工厂角色:北方工厂,热带角色
public class NorthernGardener implements Gardener
{
  public Fruit createFruit(String name)
  {
      return new NorthernFruit(name);
  }
  public Veggie createVeggie(String name)
  {
      return new NorthernVeggie(name);
  }
}
public class TropicalGardener implements Gardener
{
  public Fruit createFruit(String name)
  {
      return new TropicalFruit(name);
  }
  public Veggie createVeggie(String name)
  {
      return new TropicalVeggie(name);
  }
}

Facade

Decorator

要点喝的,有奶茶,咖啡,茶。另外每一种饮品还能加上珍珠,糖,布丁之类的料。

最后我点:奶茶加珍珠加布丁。

public abstract class Beverage
{
    String description = "Unknow Beverage";

    public String getDescription()
    {
        return description;
    }
    public abstract double cost();
}

public abstract class CondimentDecorator extends Beverage
{
    public abstract String getDescription();
}

public class Espresso extends Beverage
{
    public Espresso()
    {
        description = "Espresso";
    }
    public double cost()
    {
        return 1.99;
    }
}

public class Mocha extends CondimentDecorator
{
    Beverage beverage;

    public Mocha(Beverage beverage)
    {
        this.beverage = beverage;
    }
    public String getDescription
    {
        return beverage.getDescription + ", Mocha";
    }
    public double cost()
    {
        return .2 + beverage.cost();
    }
}

public class Whip extends CondimentDecorator
{
    Beverage beverage;

    public Mocha(Beverage beverage)
    {
        this.beverage = beverage;
    }
    public String getDescription
    {
        return beverage.getDescription + ", Whip";
    }
    public double cost()
    {
        return .9 + beverage.cost();
    }
}

public class StarbuzzCoffee
{
    public static void main(String args[])
    {
        Beverage beverage = new Espresso();
        beverage = new Mocha(beverage);
        beverage = new Mocha(beverage);
        beverage = new Whip(beverage);

        System.out.println(beverage.getDescription + " $"
            + beverage.cost());
    }
}

Singleton

Observer

Observer更多的体现的是订阅与发布的思想
举个例子说明,Bea论坛上都会定期发布一些举办活动的通告,而想参加活动的都需要先去注册一下,然后报名
报名后,Bea会给所有的参加者发一封通知信,告诉又有人参加了
当然了,如果你取消注册,那么到时候将收不到通知了。

public interface BeaNotice 
{  
    public void addObserver(Observer o);  
    public void removeObserver(Observer o);  
    public void addUser();  
}  

public class BeaNoticeImpl implements BeaNotice
{  
    private List observers = new ArrayList();  

    public void addObserver(Observer o){  
        observers.add(o);  
    }  

    public void removeObserver(Observer o){  
        observers.remove(o);  
    }  

    public void notifyAllObservers(){  
        for(int i = 0; i < observers.size(); i++){  
            ((Observer)observers.get(i)).update(this);  
        }  
    }  

    public void addUser(){  
        //数据库操作,向数据库插入一个用户的信息,然后通知所有注册的用户  
        notifyAllObservers();  
    }  
}  

public interface Observer 
{  
    public void update(BeaNoticeImpl bns);   

}  

public class WelcomeLetterObserver implements Observer 
{  
    BeaNotice beaNotice = null;  

    public WelcomeLetterObserver(BeaNotice beaNotice){  
        this.beaNotice = beaNotice;  
        beaNotice.addObserver(this);  
    }  

    public void update(BeaNoticeImpl bns) {  
        System.out.println("This is a welocme letter!");  
    }  

}  

public class OtherNoticeObserver implements Observer 
{  
    BeaNotice beaNotice = null;  

    public OtherNoticeObserver(BeaNotice beaNotice){  
        this.beaNotice = beaNotice;  
        beaNotice.addObserver(this);  
    }  

    public void update(BeaNoticeImpl bns) {  
        System.out.println("there is other Notice!");  
    }  

}  

Strategy

Proxy

有两个同学B和C,B是男的,C是女的,你晚上想给女同学C打电话咨询点事,
但是你女友不让所以,你只能通过你的男同学B和C通话,
然后把让B把反馈的结果告诉你

public interface IStudent 
{  
     public String answerSomeQuestion();  
}  

public class IGirlImpl implements IStudent 
{  
    public String answerSomeQuestion()
    {  
        System.out.println("answer some question");  
        return "this is my answer";  
    }  
}  

public class IBoyProxyImpl implements IStudent 
{  
    IGirlImpl girl = null;  
    public String answerSomeQuestion() 
    {  
        System.out.println("do someting before method invoke");  
        if(girl == null)
        {  
            girl = new IGirlImpl();  
        }  
        String returnValue = girl.answerSomeQuestion();  
        System.out.println("do someting after method invoke");  
        return returnValue;  
    }  
}  

Reference

设计模式之Adapter模式, http://lizwjiang.iteye.com/blog/86391

2015/10/25