顯示具有 Java SE 7 標籤的文章。 顯示所有文章
顯示具有 Java SE 7 標籤的文章。 顯示所有文章

2012年10月12日 星期五

Java SE 7 - Thread - ForkJoinPool 2013-02-23修正

將工作從一個切割成多個,而每個產生的工作又可以再切割成多個工作並行處理,例如:

A工作分成A1及A2,A1及A2又分成A11、A12及A21、A22,這時A、A1及A2會一直等待,當A11及A12都完成工作,將結果傳給A1後,A1就停止等待,將結果進行處理並傳回給A,而A21及A22也都完成工作,將結果傳給A2後,A2就停止等待,並將結果處理並傳回給A,最後A都收到A1及A2的結果後,將最後結果整合並傳回最終結果。

每個工作會分配Thread來執行,如果不需要工作在執行完成後傳回結果,可以使用RecursiveAction,如果需要在工作重後傳回結果,則可以使用RecursiveTask。

例如:以下是將MapReduce計算某一篇文章出現的字母次數的範例進行重寫:

 /*
 * Powered By Samuel - 林靖傑2013/02/23
 * 轉貼請說明出處!
 *
 * */
public class WordCountFork {
   
 public static void main(String[] args) {
     ForkJoinPool mainPool = new ForkJoinPool();
     //取出文字檔內容
     String Content = "";
     char[] TextData = new char[1024];
     int length = -1;

     try (Reader input = new BufferedReader(new FileReader("WordFile.txt"));
            Writer SW = new StringWriter()){
            while ((length = input.read(TextData)) != -1){
                      SW.write(TextData, 0, length);
            }
            Content = SW.toString();
     } catch (FileNotFoundException e) {
             e.printStackTrace();
     } catch (IOException e) {
             e.printStackTrace();
     }

     //Step 1: 執行
     int[] WordAry = mainPool.invoke(new LineAnaylze(Content));

     //取出結果
     for (int i = 0 ; i < WordAry.length; i ++){
            String Alphabet = Character.toString ((char) (65 + i));
            System.out.println(
                Alphabet + ":" + String.valueOf(WordAry[i]));
     }
  }
}

//Step 2: 建立RecursiveTask來傳回Task結果
//如果不需帶入值, 可以使用RecursiveAction
class LineAnaylze extends RecursiveTask<int[]> {
    private String Content = "";
    public LineAnaylze(String content){
             Content = content;
    }

    @Override
    protected int[] compute() {
         //Step 2: 如果字數大於50, 則各切割成一半成小工作執行
         if (Content.length() > 50){
              int half = Content.length() / 2;
              //先建立Task, 每一個工作都是一個Task, 所以會一直分化執行
              LineAnaylze half1 = new LineAnaylze(Content.substring(0, (half - 1)));
              LineAnaylze half2 = new LineAnaylze(Content.substring(half));
              //讓ForkJoinPool分配Thread執行Task
              half1.fork();
              half2.fork();
              //等待兩個工作完成
              int[] WordPair1 = half1.join();
              int[] WordPair2 = half2.join();

              //將兩個Task結果整合傳回
              for (int i = 0; i < WordPair1.length; i ++){
                     WordPair1[i] = WordPair1[i] + WordPair2[i];
              }
               return WordPair1;
         } else {
              //不足50個字直接執行後傳回
              return countWord(Content);
         }
    }

    //計算字數函式
    private int[] countWord(String line){
          int[] WordAry = new int[26];
          for (int i = 0 ;i < line.length(); i ++){
                 String Alphabet = String.valueOf(line.charAt(i)).toUpperCase().trim();
                 if (!Alphabet.equals("")){
                      int WordCount = 0;
                      int Ascii = (int)Alphabet.charAt(0);
                      if (Ascii >= 65 && Ascii <= 90){
                           WordCount = WordAry[Ascii - 65];
                           WordAry[Ascii - 65] = ++WordCount;
                      }
                 }
          }

          return WordAry;
    }
}

轉貼請註明出處,最好直接使用聯結轉貼!Thanks~
作者: Samuel
日期:2013/02/23

2012年10月9日 星期二

Java SE 7 - Exception - Suppressed 架構觀念

有時在catch或finally區段裡會再進行try…catch…相關動作,以確保所執行的程式碼如果再發生例外時應該做的對應處理。如下:

try{
    throw new Exception("Ex 1");
} catch (Exception ex){
    try{
       Do Something….
       throw new Exception("Ex 2");
    } catch (Exception ex2){
       Do Something…
    }
    throw ex;
}

或
try{
    throw new Exception("Ex 1");
} catch (Exception ex){
    Do Something….
    throw ex;
} finally {
    try{
       Do Something….
       throw new Exception("Ex 2");
    } catch (Exception ex2){
       Do Something…
    }
}

通常上述範例只會呈現Ex 1訊息如下
Exception in thread "main" java.lang.Exception: Ex 1
    ……


如果要完整呈現Ex 2的錯誤則必須直接列出:
try{
    throw new Exception("Ex 1");
} catch (Exception ex){
    try{
       Do Something….
       throw new Exception("Ex 2");
    } catch (Exception ex2){
       ex2.printStackTrace();
    }
    throw ex;
}

但會呈現兩則訊息
java.lang.Exception: Ex 2
    ......
Exception in thread "main" java.lang.Exception: Ex 1
    ......

如果連Ex 2都拋出
try{
    throw new Exception("Ex 1");
} catch (Exception ex){
    Do Something….
    throw ex;
} finally {
    try{
       Do Something….
       throw new Exception("Ex 2");
    } catch (Exception ex2){
       throw ex2;
    }
}
則只會呈現ex2
Exception in thread "main" java.lang.Exception: Ex 2
      …...

SE 7多出了Exception Suppressed抑制功能,讓我們先看寫法與結果:
try{
    throw new Exception("Ex 1");
} catch (Exception ex){
    try{
       throw new Exception("Ex 2");
    } catch (Exception ex2){
       ex.addSuppressed(ex2);
    }
    throw ex;
}
或
Exception outex = null;
try{
   throw new Exception("Ex 1");
} catch (Exception ex){
   outex = ex;
   throw ex;
} finally {
   try{
      throw new Exception("Ex 2");
   } catch (Exception ex2){
      outex.addSuppressed(ex2);
   }
}
這個時候Ex 2會被包在Ex 1裡呈現,可以讓我們很清楚的知道錯誤的結構與內容:
Exception in thread "main" java.lang.Exception: Ex 1
    ......
    Suppressed: java.lang.Exception: Ex 2
        ......
        ... 1 more

這樣的寫法在實作java.lang.AutoCloseable Inteface的類別中,Java編譯器會將其轉成這樣的寫法:

public static void main(String[] args) throws Exception {
    test();
}
static class ResourceA implements AutoCloseable {
    public void read() throws Exception{
        throw new Exception("ResourceA read exception");
    }
    @Override
    public void close() throws Exception {
        throw new Exception("ResourceA close exception");
    }
};
public static void test() throws Exception{
    try (ResourceA a = new ResourceA()) {
       a.read();
    } catch (Exception e) {
       throw e;
    }
}

呈現訊息如下:
Exception in thread "main" java.lang.Exception: ResourceA read exception
    ......
    Suppressed: java.lang.Exception: ResourceA close exception
        ......
        ... 1 more
待續...

轉貼請註明出處,最好直接使用聯結轉貼!Thanks~
作者: Samuel
日期:2012/10/06


Java SE 7 - Exception - try with resources 自動嘗試

在SE 7之前如果要確保資源的正確關閉,通常都會將資源關閉寫在finally如下:

public static String readFile(String name) throws FileNotFoundException {
     StringBuilder builder = new StringBuilder();
     Scanner scanner = null;
     try {
         scanner = new Scanner(new FileInputStream(name));
         while (scanner.hasNext()) {
             builder.append(scanner.nextLine());
             builder.append('\n');
         }
     } catch(FileNotFoundException ex) {
         ex.printStackTrace();
         throw ex;
     } finally {
         if(scanner != null) {
             scanner.close();
         }
     }
     return builder.toString();
}

在SE7後,只要有實作java.lang.AutoCloseable Inteface就可以使用以下寫法:

public static String readFile(String name) throws FileNotFoundException {
    StringBuilder builder = new StringBuilder();
    try(Scanner scanner = new Scanner(new FileInputStream(name))) {
        while (scanner.hasNext()) {
            builder.append(scanner.nextLine());
            builder.append('\n');
        }
    } catch(FileNotFoundException ex) {
        ex.printStackTrace();
        throw ex;
    }
    return builder.toString();
}

不管是否是正常執行還是異常中斷,java都會呼叫介面所定義的close方法。try裡面也可以使用多個物件,以分號區隔,越後面的物件會越早被關閉資源。

以下為java.lang.AutoCloseable Inteface所需實作的規範
http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html

上述範例中的Scanner在SE 7也是有實作java.lang.AutoCloseable Inteface
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html


轉貼請註明出處,最好直接使用聯結轉貼!Thanks~
作者: Samuel
日期:2012/10/06

Java SE 7 - Exception - More-Precise-Rethrow

如果為此時有兩個Checked Exception,則必須分別Catch這兩個Check Exception,如下:

try {      
    if (filename.equals("")){
        throw new FileNotFoundException();
    } else {
       throw new EOFException();
    }   
} catch (EOFException ex) {
    System.out.println("End of file reached.");
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
}

        在SE 7以前如果要使用以下語法會錯,但是SE 7後可以直接使用父類別Catch即可,但是這樣的寫法還是適用在:Catch後都是使用同樣的動作處理Exception。

try {      
     if (filename.equals("")){
         throw new FileNotFoundException();
     } else {
         throw new EOFException();
     }   
} catch (IOException ex) {
     System.out.println("End of file reached.");
}

轉貼請註明出處,最好直接使用聯結轉貼!Thanks~
作者: Samuel
日期:2012/10/06

Java SE 7 - Exception - Multi-Catch 多重捕捉

        如果程式中有使用Checked Exception(受檢例外),則必須使用Try…Catch..進行包圍或者Throws該Exception,若想要特別判斷Unchecked Exception(非受檢例外)時也會進行這樣的動作如下:


try{
   do someting...
} catch (FileNotFoundException e){
   e.printStackTrace();
} catch (EOFException e){
   e.printStackTrace();
} catch (IOException e){
   e.printStackTrace();
} catch (Exception e){
   e.printStackTrace();
}


但是這些Exception都是處理同樣的事,SE 7可以將進行Multi-Catch如下:


try{
   do someting...
} catch (FileNotFoundException | EOFException | IOException | Exception e){
   e.printStackTrace();
}

通常在Catch Exception時,會將最上層的Exception放到最下面最後Catch,避免所有問題都在Exception就被Catch,Multi-Catch也是有同樣的情況,只是這時在右邊而非下面,如果為以下寫法語法會錯:


try{
   do someting...
} catch (Exception | IOException | FileNotFoundException | EOFException e){
   e.printStackTrace();
}

轉貼請註明出處,最好直接使用聯結轉貼!Thanks~
作者: Samuel
日期:2012/10/06