yuyee

          2010年11月8日 #

          適配器

          適配器模式:將一個現(xiàn)有類實現(xiàn)的功能接口轉(zhuǎn)變?yōu)榭蛻粝M慕涌?/span>

          場景:你想使用一個已經(jīng)存在的類,但是這個類的接口不符合需求,所以需要適配

          2中實現(xiàn):一種是繼承,一種是委托,先來看看繼承

             

          第一步:系統(tǒng)現(xiàn)有功能

          package com.google.desginpattern.adapter;
          /**
           * 現(xiàn)有系統(tǒng)提供的功能
           * 
           * 
          @author Administrator
           * 
           
          */
          public class BMWCar {
          public void quickDriver() {
          System.out.println(
          "寶馬太快");
          }
          }

           

          第二步:客戶需要的接口

          package com.google.desginpattern.adapter;
          /**
           * 客戶需要的接口
           * 
          @author Administrator
           *
           
          */
          public interface Car {
          public void driver();
          public void brake();
          }

           

          第三步:實現(xiàn)客戶需要的功能

          package com.google.desginpattern.adapter;
          /**
           * 匹配客戶需求的實現(xiàn)
           * 
          @author Administrator
           *
           
          */
          public class CarAdapter extends BMWCar implements Car {
          @Override
          public void brake() {
          System.out.println(
          "剎車");
          }
          @Override
          public void driver() {
          quickDriver();
          }
          }

           

          測試類:

           

          package com.google.desginpattern.adapter;


          public class Test {

          public static void main(String[] args) {


          Car car 
          = new CarAdapter();

          car.brake();

          car.driver();

          }


          }

          輸出:

          剎車

          寶馬太快

          如果是委托的方式,改寫adapter

          package com.google.desginpattern.adapter;
          /**
           * 匹配客戶需求的實現(xiàn)
           * 
           * 
          @author Administrator
           * 
           
          */
          public class CarAdapter implements Car {
          private BMWCar car;
          @Override
          public void brake() {
          System.out.println(
          "剎車");
          }
          @Override
          public void driver() {
          car.quickDriver();
          }
          public BMWCar getCar() {
          return car;
          }
          public void setCar(BMWCar car) {
          this.car = car;
          }
          }

           

          posted @ 2010-11-29 22:28 羔羊| 編輯 收藏

          裝飾器


          裝飾器:裝飾器模式主要用于系統(tǒng)擴張功能用,在系統(tǒng)原有的功能上,擴展出其他的功能,JDKIO包用到很多,比如datainputstream之類,需要用其他流進行構(gòu)造的上層類,符合面向?qū)ο笤O計的開閉原則

          下面我來寫個例子:

          首先,寫一個Car模版,定義基本屬性及行為功能driver

          package com.google.desginpattern.decoration;
          //其實這是個模版
          public abstract class Car {
          private int spreed;
          public int getSpreed() {
          return spreed;
          }
          public void setSpreed(int spreed) {
          this.spreed = spreed;
          }
          public abstract void driver();
          }

           

          第二步:具體車比如寶馬,這是目前系統(tǒng)中這個類能提供的功能

          package com.google.desginpattern.decoration;
          //目前系統(tǒng)中此類的功能
          public class BMWCar extends Car {
          @Override
          public void driver() {
          System.out.println(
          "我開著寶馬車");
          }
          }

           

          現(xiàn)在我想在這個類上擴展出其他功能,比如:泡妞

          第三步:定義一個裝飾模板,為什么給他定義個模板呢~因為可以給這個BMWCar類裝飾很不同的功能,不只泡妞一個~

          繼承Car父類,覆蓋driver功能,調(diào)用Car引用完成driver功能

          package com.google.desginpattern.decoration;
          //裝飾器父類
          public abstract class DecorationCar extends Car {
          // 引入car
          private Car car;
          @Override
          public void driver() {
          car.driver();
          // 調(diào)用此car來完成裝飾器的功能
          }
          public Car getCar() {
          return car;
          }
          public void setCar(Car car) {
          this.car = car;
          }
          }

           

          第四步:具體的裝飾功能,添加一個構(gòu)造函數(shù),參數(shù)為Car,為裝飾父類Car引用賦值,其實就是原來具體的功能類,回想下IO包里經(jīng)常new的代碼段就明白~~

          package com.google.desginpattern.decoration;
          //具體的裝飾類,添加額外的泡妞功能
          public class DecorationBMWCar extends DecorationCar {
          public DecorationBMWCar(Car car) {
          super.setCar(car);
          }
          @Override
          public void driver() {
          // TODO Auto-generated method stub
          super.driver();// 調(diào)用原來的功能
          System.out.println("泡妞");// 添加額外的功能
          }
          }

           

          測試類:構(gòu)造的方法很像IO包里的流

          package com.google.desginpattern.decoration;
          public class Test {
          public static void main(String[] args) {
          Car car 
          = new DecorationBMWCar(new BMWCar());
          car.driver();
          }
          }

           

          輸出:

          我開著寶馬車

          泡妞

          posted @ 2010-11-29 21:36 羔羊| 編輯 收藏

          IOC初始化和互相引用解決

               摘要: 觀察IOC中容器初始化某個Bean順序,現(xiàn)先一個JAVABean類,看看控制臺輸出:package com.google.aop.exception.ioc; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory...  閱讀全文

          posted @ 2010-11-10 16:27 羔羊| 編輯 收藏

          AbstractQueuedSynchronizer看看


          API中的解釋:為實現(xiàn)依賴于先進先出 (FIFO) 等待隊列的阻塞鎖定和相關同步器(信號量、事件,等等)提供一個框架。此類的設計目標是成為依靠單個原子 int 值來表示狀態(tài)的大多數(shù)同步器的一個有用基礎。子類必須定義更改此狀態(tài)的受保護方法,并定義哪種狀態(tài)對于此對象意味著被獲取或被釋放。假定這些條件之后,此類中的其他方法就可以實現(xiàn)所有排隊和阻塞機制。子類可以維護其他狀態(tài)字段,但只是為了獲得同步而只追蹤使用 getState()、getState()getState()setState(int)compareAndSetState(int, int) 方法來操作以原子方式更新的 int 值。
          此類采用模板模式設計,此類為一個抽象類,但是沒抽象方法,每個sync子類需要實現(xiàn)5個受保護的方法

          這個5個方法在AbstractQueuedSynchronizer 都拋出throw new UnsupportedOperationException();
          AbstractQueuedSynchronizer 中有3個屬性:主要聲明一個狀態(tài)和一個wait queue,通過

          wait queue中Node 為一個雙向鏈表,需要去理解Node中幾個靜態(tài)字段值的意義,下面為他的源碼:
          static final class Node {
                  /** waitStatus value to indicate thread has cancelled */
                  static final int CANCELLED =  1;
                  /** waitStatus value to indicate successor's thread needs unparking */
                  static final int SIGNAL    = -1;
                  /** waitStatus value to indicate thread is waiting on condition */
                  static final int CONDITION = -2;
                  /** Marker to indicate a node is waiting in shared mode */
                  static final Node SHARED = new Node();
                  /** Marker to indicate a node is waiting in exclusive mode */
                  static final Node EXCLUSIVE = null;

                  /**
                   * Status field, taking on only the values:
                   *   SIGNAL:     The successor of this node is (or will soon be)
                   *               blocked (via park), so the current node must
                   *               unpark its successor when it releases or
                   *               cancels. To avoid races, acquire methods must
                   *               first indicate they need a signal,
                   *               then retry the atomic acquire, and then,
                   *               on failure, block.
                   *   CANCELLED:  This node is cancelled due to timeout or interrupt.
                   *               Nodes never leave this state. In particular,
                   *               a thread with cancelled node never again blocks.
                   *   CONDITION:  This node is currently on a condition queue.
                   *               It will not be used as a sync queue node until
                   *               transferred. (Use of this value here
                   *               has nothing to do with the other uses
                   *               of the field, but simplifies mechanics.)
                   *   0:          None of the above
                   *
                   * The values are arranged numerically to simplify use.
                   * Non-negative values mean that a node doesn't need to
                   * signal. So, most code doesn't need to check for particular
                   * values, just for sign.
                   *
                   * The field is initialized to 0 for normal sync nodes, and
                   * CONDITION for condition nodes.  It is modified only using
                   * CAS.
                   */
                  volatile int waitStatus;

                  /**
                   * Link to predecessor node that current node/thread relies on
                   * for checking waitStatus. Assigned during enqueing, and nulled
                   * out (for sake of GC) only upon dequeuing.  Also, upon
                   * cancellation of a predecessor, we short-circuit while
                   * finding a non-cancelled one, which will always exist
                   * because the head node is never cancelled: A node becomes
                   * head only as a result of successful acquire. A
                   * cancelled thread never succeeds in acquiring, and a thread only
                   * cancels itself, not any other node.
                   */
                  volatile Node prev;

                  /**
                   * Link to the successor node that the current node/thread
                   * unparks upon release. Assigned once during enqueuing, and
                   * nulled out (for sake of GC) when no longer needed.  Upon
                   * cancellation, we cannot adjust this field, but can notice
                   * status and bypass the node if cancelled.  The enq operation
                   * does not assign next field of a predecessor until after
                   * attachment, so seeing a null next field does not
                   * necessarily mean that node is at end of queue. However, if
                   * a next field appears to be null, we can scan prev's from
                   * the tail to double-check.
                   */
                  volatile Node next;

                  /**
                   * The thread that enqueued this node.  Initialized on
                   * construction and nulled out after use.
                   */
                  volatile Thread thread;

                  /**
                   * Link to next node waiting on condition, or the special
                   * value SHARED.  Because condition queues are accessed only
                   * when holding in exclusive mode, we just need a simple
                   * linked queue to hold nodes while they are waiting on
                   * conditions. They are then transferred to the queue to
                   * re-acquire. And because conditions can only be exclusive,
                   * we save a field by using special value to indicate shared
                   * mode.
                   */
                  Node nextWaiter;

                  /**
                   * Returns true if node is waiting in shared mode
                   */
                  final boolean isShared() {
                      return nextWaiter == SHARED;
                  }

                  /**
                   * Returns previous node, or throws NullPointerException if
                   * null.  Use when predecessor cannot be null.
                   * @return the predecessor of this node
                   */
                  final Node predecessor() throws NullPointerException {
                      Node p = prev;
                      if (p == null)
                          throw new NullPointerException();
                      else
                          return p;
                  }

                  Node() {    // Used to establish initial head or SHARED marker
                  }

                  Node(Thread thread, Node mode) {     // Used by addWaiter
                      this.nextWaiter = mode;
                      this.thread = thread;
                  }

                  Node(Thread thread, int waitStatus) { // Used by Condition
                      this.waitStatus = waitStatus;
                      this.thread = thread;
                  }


              }
          獲取鎖定調(diào)用的方法,其實這個方法是阻塞的:
            public final void acquire(int arg) {
                  if (!tryAcquire(arg) &&
                      acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
                      selfInterrupt();
              }
          如果獲取不成功則調(diào)用如下方法:
             final boolean acquireQueued(final Node node, int arg) {
                  try {
                      boolean interrupted = false;
                      for (;;) {
                          final Node p = node.predecessor();
                          if (p == head && tryAcquire(arg)) {//當節(jié)點是頭節(jié)點且獨占時才返回
                              setHead(node);
                              p.next = null; // help GC
                              return interrupted;
                          }
                          if (shouldParkAfterFailedAcquire(p, node) &&
                              parkAndCheckInterrupt())//阻塞并判斷是否打斷,其實這個判斷才是自旋鎖真正的猥瑣點,
          意思是如果你的前繼節(jié)點不是head,而且當你的前繼節(jié)點狀態(tài)是Node.SIGNAL時,你這個線程將被park(),直到另外的線程release時,發(fā)現(xiàn)head.next是你這個node時,才unpark,你才能繼續(xù)循環(huán)并獲取鎖
                              interrupted = true;
                      }
          shouldParkAfterFailedAcquire這個方法刪除所有waitStatus>0也就是CANCELLED狀態(tài)的Node,并設置前繼節(jié)點為signal
           private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
                  int s = pred.waitStatus;
                  if (s < 0)
                      /*
                       * This node has already set status asking a release
                       * to signal it, so it can safely park
                       */
                      return true;
                  if (s > 0) {
                      /*
                       * Predecessor was cancelled. Skip over predecessors and
                       * indicate retry.
                       */
             do {
          node.prev = pred = pred.prev;
             } while (pred.waitStatus > 0);
             pred.next = node;
          }
                  else
                      /*
                       * Indicate that we need a signal, but don't park yet. Caller
                       * will need to retry to make sure it cannot acquire before
                       * parking.
                       */
                      compareAndSetWaitStatus(pred, 0, Node.SIGNAL);
                  return false;
              }


          使用LockSupport.park(this),禁用當前線程
          private final boolean parkAndCheckInterrupt() {
                  LockSupport.park(this);//block
                  return Thread.interrupted();
              }
          釋放鎖:
              public final boolean release(int arg) {
                  if (tryRelease(arg)) {
                      Node h = head;
                      if (h != null && h.waitStatus != 0)
                          unparkSuccessor(h);//unblock
                      return true;
                  }
                  return false;
              }
          private void unparkSuccessor(Node node) {
                  /*
                   * Try to clear status in anticipation of signalling.  It is
                   * OK if this fails or if status is changed by waiting thread.
                   */
                  compareAndSetWaitStatus(node, Node.SIGNAL, 0);

                  /*
                   * Thread to unpark is held in successor, which is normally
                   * just the next node.  But if cancelled or apparently null,
                   * traverse backwards from tail to find the actual
                   * non-cancelled successor.
                   */
                  Node s = node.next;
                  if (s == null || s.waitStatus > 0) {
                      s = null;
                      for (Node t = tail; t != null && t != node; t = t.prev)
                          if (t.waitStatus <= 0)
                              s = t;
                  }
                  if (s != null)
                      LockSupport.unpark(s.thread);
              }


                  } catch (RuntimeException ex) {
                      cancelAcquire(node);
                      throw ex;
                  }
              }
            

          看下ReentrantLock鎖中sync的實現(xiàn):
           static abstract class Sync extends AbstractQueuedSynchronizer {
                  private static final long serialVersionUID = -5179523762034025860L;

                  /**
                   * Performs {@link Lock#lock}. The main reason for subclassing
                   * is to allow fast path for nonfair version.
                   */
                  abstract void lock();

                  /**
                   * Performs non-fair tryLock.  tryAcquire is
                   * implemented in subclasses, but both need nonfair
                   * try for trylock method.
                   */
                  final boolean nonfairTryAcquire(int acquires) {
                      final Thread current = Thread.currentThread();
                      int c = getState();
                      if (c == 0) {
                          if (compareAndSetState(0, acquires)) {
                              setExclusiveOwnerThread(current);
                              return true;
                          }
                      }
                      else if (current == getExclusiveOwnerThread()) {
                          int nextc = c + acquires;
                          if (nextc < 0) // overflow
                              throw new Error("Maximum lock count exceeded");
                          setState(nextc);
                          return true;
                      }
                      return false;
                  }

                  protected final boolean tryRelease(int releases) {
                      int c = getState() - releases;
                      if (Thread.currentThread() != getExclusiveOwnerThread())
                          throw new IllegalMonitorStateException();
                      boolean free = false;
                      if (c == 0) {
                          free = true;
                          setExclusiveOwnerThread(null);
                      }
                      setState(c);
                      return free;
                  }

                  protected final boolean isHeldExclusively() {
                      // While we must in general read state before owner,
                      // we don't need to do so to check if current thread is owner
                      return getExclusiveOwnerThread() == Thread.currentThread();
                  }

                  final ConditionObject newCondition() {
                      return new ConditionObject();
                  }

                  // Methods relayed from outer class

                  final Thread getOwner() {
                      return getState() == 0 ? null : getExclusiveOwnerThread();
                  }

                  final int getHoldCount() {
                      return isHeldExclusively() ? getState() : 0;
                  }

                  final boolean isLocked() {
                      return getState() != 0;
                  }

                  /**
                   * Reconstitutes this lock instance from a stream.
                   * @param s the stream
                   */
                  private void readObject(java.io.ObjectInputStream s)
                      throws java.io.IOException, ClassNotFoundException {
                      s.defaultReadObject();
                      setState(0); // reset to unlocked state
                  }
              }
          非公平規(guī)則下nonfairTryAcquire,獲取當前鎖的state,通過CAS原子操作設置為1,并將當前線程設置為獨占線程,如果當前線程已經(jīng)拿了鎖,則state增加1
          公平鎖中 有如下判斷:
          if (isFirst(current) &&//判斷頭元素
                              compareAndSetState(0, acquires)) {
                              setExclusiveOwnerThread(current);
                              return true;
                          }
          在獲取鎖步驟:
          1.調(diào)用tryAcquire來獲取,如果失敗,則進入2
          2.調(diào)用addWaiter,以獨占模式將node放到tail位置
          3.調(diào)用acquireQueued方法,此方法阻塞,直到node的pre為head,并成功獲取鎖定,也可能存在阻塞并打斷情況
          釋放鎖的步驟:
          1.放棄排他鎖持有權(quán)
          2.unpark 節(jié)點的下一個blocked節(jié)點

          公平鎖與非公平鎖:從代碼上看,非公平鎖是讓當前線程優(yōu)先獨占,而公平鎖則是讓等待時間最長的線程優(yōu)先,非公平的可能讓其他線程沒機會執(zhí)行,而公平的則可以讓等待時間最長的先執(zhí)行,但是性能上會差點

          posted @ 2010-11-09 15:30 羔羊| 編輯 收藏

          linkedhashmap看看

          linkedhashmap繼承自hashmap,他的底層維護的一個鏈表,    private transient Entry<K,V> header 來記錄元素的插入順序和訪問順序;
          hashmap的構(gòu)造函數(shù)中調(diào)用init()方法,而linkedhashmap中重寫了init(),將head元素初始化
             void init() {
                  header = new Entry<K,V>(-1, null, null, null);
                  header.before = header.after = header;
              }

          private final boolean accessOrder這個屬性表示是否要根據(jù)訪問順序改變線性結(jié)構(gòu)
          在linkedhashmap中改寫了hashmap的get()方法,增加了 e.recordAccess(this),這個方法主要是根據(jù)accessOrder的值判斷是否需要實現(xiàn)LRU,
           void recordAccess(HashMap<K,V> m) {
                      LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
                      if (lm.accessOrder) {
                          lm.modCount++;
                          remove();
                          addBefore(lm.header);
                      }
                  }

          addBefore這個方法是把剛訪問的元素放到head的前面
           private void addBefore(Entry<K,V> existingEntry) {
                      after  = existingEntry;
                      before = existingEntry.before;
                      before.after = this;
                      after.before = this;
                  }
          put方法繼承自hashmap,hashmap預留了 e.recordAccess(this)這個方法:
               public V put(K key, V value) {
                  if (key == null)
                      return putForNullKey(value);
                  int hash = hash(key.hashCode());
                  int i = indexFor(hash, table.length);
                  for (Entry<K,V> e = table[i]; e != null; e = e.next) {
                      Object k;
                      if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                          V oldValue = e.value;
                          e.value = value;
                          e.recordAccess(this);
                          return oldValue;
                      }
                  }

                  modCount++;
                  addEntry(hash, key, value, i);
                  return null;
              }

          并通過重寫 addEntry(hash, key, value, i)這個方法,實現(xiàn)LRU中的刪除動作:
              void addEntry(int hash, K key, V value, int bucketIndex) {
                  createEntry(hash, key, value, bucketIndex);

                  // Remove eldest entry if instructed, else grow capacity if appropriate
                  Entry<K,V> eldest = header.after;//找到最老的元素,這個在addBefore里確定,初次賦值是當只有一個head時候,你插入一個元素
                  if (removeEldestEntry(eldest)) {//這個是受保護的方法,需要自己制定刪除策略,比如size() > 最大容量,可自己實現(xiàn),默認為false,也就是不開啟
                      removeEntryForKey(eldest.key);
                  } else {
                      if (size >= threshold)
                          resize(2 * table.length);
                  }
              }
          自己重寫這個方法,指定刪除策略:
           protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
                  return false;
              }
          因此,可用linkedhashmap 構(gòu)建一個基于LRU算法的緩存。


          package com.google.study.cache;

          import java.util.LinkedHashMap;
          import java.util.concurrent.locks.ReentrantLock;

          public class SimpleCache<K, V> extends LinkedHashMap<K, V> {

          private int maxCapacity;
          private ReentrantLock lock = new ReentrantLock();

          public SimpleCache(int maxCapacity, float load_factory) {
          super(maxCapacity, load_factory, true);
          this.maxCapacity = maxCapacity;
          }

          public int getMaxCapacity() {
          return maxCapacity;
          }

          public void setMaxCapacity(int maxCapacity) {
          this.maxCapacity = maxCapacity;
          }

          @Override
          protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
          // TODO Auto-generated method stub
          return super.removeEldestEntry(eldest);
          }

          public V get(Object key) {
          lock.lock();
          try {
          return super.get(key);
          } finally {
          lock.unlock();
          }

          }

          public V put(K k, V v) {
          lock.lock();
          try {
          return super.put(k, v);
          } finally {
          lock.unlock();
          }
          }

          @Override
          public void clear() {
          lock.lock();
          try {
          super.clear();
          } finally {
          lock.unlock();
          }
          }

          @Override
          public int size() {

          lock.lock();
          try {
          return super.size();
          } finally {
          lock.unlock();
          }
          }

          }



          posted @ 2010-11-08 23:14 羔羊| 編輯 收藏

          主站蜘蛛池模板: 沅陵县| 常山县| 文山县| 汉源县| 丹凤县| 名山县| 泰来县| 化德县| 新田县| 贡嘎县| 余姚市| 东阿县| 吕梁市| 十堰市| 怀安县| 建湖县| 罗田县| 岑巩县| 福海县| 呼伦贝尔市| 吉隆县| 玉龙| 寿阳县| 淳安县| 东丽区| 安新县| 山西省| 杂多县| 三台县| 彭泽县| 苗栗市| 清丰县| 定远县| 石泉县| 博爱县| 永靖县| 宁津县| 屏边| 无棣县| 革吉县| 河西区|