午夜亚洲精品,99久久免费精品国产72精品九九 ,国产亚洲欧洲http://www.aygfsteel.com/leekiang/category/21757.htmlMDA/MDD/TDD/DDD/DDDDDDDzh-cnThu, 28 Sep 2017 20:29:58 GMTThu, 28 Sep 2017 20:29:58 GMT60java8國際化直接支持的語言列表http://www.aygfsteel.com/leekiang/archive/2017/09/27/432836.htmlleekiangleekiangWed, 27 Sep 2017 12:17:00 GMThttp://www.aygfsteel.com/leekiang/archive/2017/09/27/432836.htmlhttp://www.aygfsteel.com/leekiang/comments/432836.htmlhttp://www.aygfsteel.com/leekiang/archive/2017/09/27/432836.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/432836.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/432836.html
System.out.println("availableLocales :"+  Locale.getAvailableLocales().length);

Locale[] arr=Locale.getAvailableLocales();
Arrays.sort(arr, new Comparator<Locale>() {
@Override
public int compare(Locale o1, Locale o2) {
return o1.getLanguage().compareTo(o2.getLanguage());
}
});

for(Locale l:arr){
System.out.println("語言:"+ l.getLanguage()+" 名稱:"+l.getDisplayLanguage()
+(StringUtils.isEmpty(l.getDisplayCountry())?"":(" 國家:"+ l.getDisplayCountry())) + " "+l.toString());
}
輸出如下
availableLocales :160
語言: 名稱:
語言:ar 名稱:阿拉伯文 國家:阿拉伯聯合酋長國 ar_AE
語言:ar 名稱:阿拉伯文 國家:約旦 ar_JO
語言:ar 名稱:阿拉伯文 國家:敘利亞 ar_SY
語言:ar 名稱:阿拉伯文 國家:巴林 ar_BH
語言:ar 名稱:阿拉伯文 國家:沙特阿拉伯 ar_SA
語言:ar 名稱:阿拉伯文 國家:也門 ar_YE
語言:ar 名稱:阿拉伯文 國家:埃及 ar_EG
語言:ar 名稱:阿拉伯文 國家:蘇丹 ar_SD
語言:ar 名稱:阿拉伯文 國家:突尼斯 ar_TN
語言:ar 名稱:阿拉伯文 國家:伊拉克 ar_IQ
語言:ar 名稱:阿拉伯文 國家:摩洛哥 ar_MA
語言:ar 名稱:阿拉伯文 國家:卡塔爾 ar_QA
語言:ar 名稱:阿拉伯文 國家:阿曼 ar_OM
語言:ar 名稱:阿拉伯文 ar
語言:ar 名稱:阿拉伯文 國家:科威特 ar_KW
語言:ar 名稱:阿拉伯文 國家:利比亞 ar_LY
語言:ar 名稱:阿拉伯文 國家:阿爾及利亞 ar_DZ
語言:ar 名稱:阿拉伯文 國家:黎巴嫩 ar_LB
語言:be 名稱:白俄羅斯文 be
語言:be 名稱:白俄羅斯文 國家:白俄羅斯 be_BY
語言:bg 名稱:保加利亞文 bg
語言:bg 名稱:保加利亞文 國家:保加利亞 bg_BG
語言:ca 名稱:加泰羅尼亞文 國家:西班牙 ca_ES
語言:ca 名稱:加泰羅尼亞文 ca
語言:cs 名稱:捷克文 cs
語言:cs 名稱:捷克文 國家:捷克共和國 cs_CZ
語言:da 名稱:丹麥文 國家:丹麥 da_DK
語言:da 名稱:丹麥文 da
語言:de 名稱:德文 de
語言:de 名稱:德文 國家:瑞士 de_CH
語言:de 名稱:德文 國家:奧地利 de_AT
語言:de 名稱:德文 國家:盧森堡 de_LU
語言:de 名稱:德文 國家:德國 de_DE
語言:de 名稱:德文 國家:希臘 de_GR
語言:el 名稱:希臘文 el
語言:el 名稱:希臘文 國家:塞浦路斯 el_CY
語言:el 名稱:希臘文 國家:希臘 el_GR
語言:en 名稱:英文 國家:美國 en_US
語言:en 名稱:英文 國家:新加坡 en_SG
語言:en 名稱:英文 國家:馬耳他 en_MT
語言:en 名稱:英文 en
語言:en 名稱:英文 國家:菲律賓 en_PH
語言:en 名稱:英文 國家:新西蘭 en_NZ
語言:en 名稱:英文 國家:南非 en_ZA
語言:en 名稱:英文 國家:澳大利亞 en_AU
語言:en 名稱:英文 國家:愛爾蘭 en_IE
語言:en 名稱:英文 國家:加拿大 en_CA
語言:en 名稱:英文 國家:印度 en_IN
語言:en 名稱:英文 國家:英國 en_GB
語言:es 名稱:西班牙文 國家:巴拿馬 es_PA
語言:es 名稱:西班牙文 國家:委內瑞拉 es_VE
語言:es 名稱:西班牙文 國家:波多黎哥 es_PR
語言:es 名稱:西班牙文 國家:玻利維亞 es_BO
語言:es 名稱:西班牙文 國家:阿根廷 es_AR
語言:es 名稱:西班牙文 國家:薩爾瓦多 es_SV
語言:es 名稱:西班牙文 es
語言:es 名稱:西班牙文 國家:西班牙 es_ES
語言:es 名稱:西班牙文 國家:哥倫比亞 es_CO
語言:es 名稱:西班牙文 國家:巴拉圭 es_PY
語言:es 名稱:西班牙文 國家:厄瓜多爾 es_EC
語言:es 名稱:西班牙文 國家:美國 es_US
語言:es 名稱:西班牙文 國家:危地馬拉 es_GT
語言:es 名稱:西班牙文 國家:墨西哥 es_MX
語言:es 名稱:西班牙文 國家:洪都拉斯 es_HN
語言:es 名稱:西班牙文 國家:智利 es_CL
語言:es 名稱:西班牙文 國家:多米尼加共和國 es_DO
語言:es 名稱:西班牙文 國家:古巴 es_CU
語言:es 名稱:西班牙文 國家:烏拉圭 es_UY
語言:es 名稱:西班牙文 國家:哥斯達黎加 es_CR
語言:es 名稱:西班牙文 國家:尼加拉瓜 es_NI
語言:es 名稱:西班牙文 國家:秘魯 es_PE
語言:et 名稱:愛沙尼亞文 et
語言:et 名稱:愛沙尼亞文 國家:愛沙尼亞 et_EE
語言:fi 名稱:芬蘭文 國家:芬蘭 fi_FI
語言:fi 名稱:芬蘭文 fi
語言:fr 名稱:法文 國家:比利時 fr_BE
語言:fr 名稱:法文 國家:瑞士 fr_CH
語言:fr 名稱:法文 fr
語言:fr 名稱:法文 國家:盧森堡 fr_LU
語言:fr 名稱:法文 國家:法國 fr_FR
語言:fr 名稱:法文 國家:加拿大 fr_CA
語言:ga 名稱:愛爾蘭文 ga
語言:ga 名稱:愛爾蘭文 國家:愛爾蘭 ga_IE
語言:hi 名稱:印地文 國家:印度 hi_IN
語言:hi 名稱:印地文 hi
語言:hr 名稱:克羅地亞文 國家:克羅地亞 hr_HR
語言:hr 名稱:克羅地亞文 hr
語言:hu 名稱:匈牙利文 hu
語言:hu 名稱:匈牙利文 國家:匈牙利 hu_HU
語言:in 名稱:印度尼西亞文 in
語言:in 名稱:印度尼西亞文 國家:印度尼西亞 in_ID
語言:is 名稱:冰島文 國家:冰島 is_IS
語言:is 名稱:冰島文 is
語言:it 名稱:意大利文 it
語言:it 名稱:意大利文 國家:瑞士 it_CH
語言:it 名稱:意大利文 國家:意大利 it_IT
語言:iw 名稱:希伯來文 國家:以色列 iw_IL
語言:iw 名稱:希伯來文 iw
語言:ja 名稱:日文 國家:日本 ja_JP_JP_#u-ca-japanese
語言:ja 名稱:日文 ja
語言:ja 名稱:日文 國家:日本 ja_JP
語言:ko 名稱:朝鮮文 ko
語言:ko 名稱:朝鮮文 國家:韓國 ko_KR
語言:lt 名稱:立陶宛文 lt
語言:lt 名稱:立陶宛文 國家:立陶宛 lt_LT
語言:lv 名稱:拉托維亞文(列托) lv
語言:lv 名稱:拉托維亞文(列托) 國家:拉脫維亞 lv_LV
語言:mk 名稱:馬其頓文 mk
語言:mk 名稱:馬其頓文 國家:馬其頓王國 mk_MK
語言:ms 名稱:馬來文 國家:馬來西亞 ms_MY
語言:ms 名稱:馬來文 ms
語言:mt 名稱:馬耳他文 國家:馬耳他 mt_MT
語言:mt 名稱:馬耳他文 mt
語言:nl 名稱:荷蘭文 nl
語言:nl 名稱:荷蘭文 國家:荷蘭 nl_NL
語言:nl 名稱:荷蘭文 國家:比利時 nl_BE
語言:no 名稱:挪威文 國家:挪威 no_NO_NY
語言:no 名稱:挪威文 國家:挪威 no_NO
語言:no 名稱:挪威文 no
語言:pl 名稱:波蘭文 國家:波蘭 pl_PL
語言:pl 名稱:波蘭文 pl
語言:pt 名稱:葡萄牙文 pt
語言:pt 名稱:葡萄牙文 國家:巴西 pt_BR
語言:pt 名稱:葡萄牙文 國家:葡萄牙 pt_PT
語言:ro 名稱:羅馬尼亞文 國家:羅馬尼亞 ro_RO
語言:ro 名稱:羅馬尼亞文 ro
語言:ru 名稱:俄文 國家:俄羅斯 ru_RU
語言:ru 名稱:俄文 ru
語言:sk 名稱:斯洛伐克文 sk
語言:sk 名稱:斯洛伐克文 國家:斯洛伐克 sk_SK
語言:sl 名稱:斯洛文尼亞文 sl
語言:sl 名稱:斯洛文尼亞文 國家:斯洛文尼亞 sl_SI
語言:sq 名稱:阿爾巴尼亞文 sq
語言:sq 名稱:阿爾巴尼亞文 國家:阿爾巴尼亞 sq_AL
語言:sr 名稱:塞爾維亞文 國家:黑山 sr_ME
語言:sr 名稱:塞爾維亞文 國家:波斯尼亞和黑山共和國 sr_BA_#Latn
語言:sr 名稱:塞爾維亞文 國家:塞爾維亞及黑山 sr_CS
語言:sr 名稱:塞爾維亞文 國家:波斯尼亞和黑山共和國 sr_BA
語言:sr 名稱:塞爾維亞文 國家:黑山 sr_ME_#Latn
語言:sr 名稱:塞爾維亞文 sr__#Latn
語言:sr 名稱:塞爾維亞文 國家:塞爾維亞 sr_RS
語言:sr 名稱:塞爾維亞文 sr
語言:sr 名稱:塞爾維亞文 國家:塞爾維亞 sr_RS_#Latn
語言:sv 名稱:瑞典文 國家:瑞典 sv_SE
語言:sv 名稱:瑞典文 sv
語言:th 名稱:泰文 國家:泰國 th_TH
語言:th 名稱:泰文 th
語言:th 名稱:泰文 國家:泰國 th_TH_TH_#u-nu-thai
語言:tr 名稱:土耳其文 tr
語言:tr 名稱:土耳其文 國家:土耳其 tr_TR
語言:uk 名稱:烏克蘭文 uk
語言:uk 名稱:烏克蘭文 國家:烏克蘭 uk_UA
語言:vi 名稱:越南文 國家:越南 vi_VN
語言:vi 名稱:越南文 vi
語言:zh 名稱:中文 國家:臺灣地區 zh_TW
語言:zh 名稱:中文 國家:香港 zh_HK
語言:zh 名稱:中文 國家:新加坡 zh_SG
語言:zh 名稱:中文 國家:中國 zh_CN
語言:zh 名稱:中文 zh


leekiang 2017-09-27 20:17 發表評論
]]>
如何用 Java 獲取系統 IP?http://www.aygfsteel.com/leekiang/archive/2015/03/02/423120.htmlleekiangleekiangSun, 01 Mar 2015 22:29:00 GMThttp://www.aygfsteel.com/leekiang/archive/2015/03/02/423120.htmlhttp://www.aygfsteel.com/leekiang/comments/423120.htmlhttp://www.aygfsteel.com/leekiang/archive/2015/03/02/423120.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/423120.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/423120.html
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Pattern;

public class GetIP {
public static void main(String[] args) {
System.out.println(GetIP.getLocalAddress0().getHostAddress());
}
public static InetAddress getLocalAddress0() {
??????? InetAddress localAddress = null;
??????? try {
??????????? localAddress = InetAddress.getLocalHost();
??????????? if (isValidAddress(localAddress)) {
??????????????? return localAddress;
??????????? }
??????? } catch (Throwable e) {
??????????? System.out.println("Failed to retriving ip address, " + e.getMessage());
??????? }
??????? try {
??????????? Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
??????????? if (interfaces != null) {
??????????????? while (interfaces.hasMoreElements()) {
??????????????????? try {
??????????????????????? NetworkInterface network = interfaces.nextElement();
??????????????????????? Enumeration<InetAddress> addresses = network.getInetAddresses();
??????????????????????? if (addresses != null) {
??????????????????????????? while (addresses.hasMoreElements()) {
??????????????????????????????? try {
??????????????????????????????????? InetAddress address = addresses.nextElement();
??????????????????????????????????? if (isValidAddress(address)) {
??????????????????????????????????????? return address;
??????????????????????????????????? }
??????????????????????????????? } catch (Throwable e) {
??????????????????????????????????? System.out.println("Failed to retriving ip address, " + e.getMessage());
??????????????????????????????? }
??????????????????????????? }
??????????????????????? }
??????????????????? } catch (Throwable e) {
??????????????????????? System.out.println("Failed to retriving ip address, " + e.getMessage());
??????????????????? }
??????????????? }
??????????? }
??????? } catch (Throwable e) {
??????????? System.out.println("Failed to retriving ip address, " + e.getMessage());
??????? }
??????? System.out.println("Could not get local host ip address, will use 127.0.0.1 instead.");
??????? return localAddress;
??? }
??? private static boolean isValidAddress(InetAddress address) {
??????? if (address == null || address.isLoopbackAddress())
??????????? return false;
??????? String name = address.getHostAddress();
??????? return (name != null
??????????????? && ! ANYHOST.equals(name)
??????????????? && ! LOCALHOST.equals(name)
??????????????? && IP_PATTERN.matcher(name).matches());
??? }
?? ?
??? public static final String LOCALHOST = "127.0.0.1";

??? public static final String ANYHOST = "0.0.0.0";
?? ?
??? private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
}



leekiang 2015-03-02 06:29 發表評論
]]>
CountDownLatch和CyclicBarrier的區別http://www.aygfsteel.com/leekiang/archive/2015/03/02/423119.htmlleekiangleekiangSun, 01 Mar 2015 22:28:00 GMThttp://www.aygfsteel.com/leekiang/archive/2015/03/02/423119.htmlhttp://www.aygfsteel.com/leekiang/comments/423119.htmlhttp://www.aygfsteel.com/leekiang/archive/2015/03/02/423119.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/423119.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/423119.htmlCyclicBarrier? : N個線程相互等待,任何一個線程完成之前,所有的線程都必須等待。
這樣應該就清楚一點了,對于CountDownLatch來說,重點是那個“一個線程”, 是它在等待, 而另外那N的線程在把“某個事情”做完之后可以繼續等待,可以終止。而對于CyclicBarrier來說,重點是那N個線程,他們之間任何一個沒有完成,所有的線程都必須等待。

CyclicBarrier 在釋放等待線程后可以重用,所以稱它為循環的 barrier。它 還支持一個可選的 Runnable 命令,在一組線程中的最后一個線程到達之后(但在釋放所有線程之前),該命令只在每個屏障點運行一次。若在繼續所有參與線程之前更新共享狀態,此屏障操作很有用。



public class Test {
??? public static void main(String[] args) {
??????? new Test().test1();
??? }
?? ?
??? public void test1() {
??????? CyclicBarrier cyclicBarrier = new CyclicBarrier(4, new Runnable() {
??????????? @Override
??????????? public void run() {
??????????????? System.out.println("所有玩家進入第二關!");
??????????? }
??????? });

??????? for (int i = 0; i < 4; i++) {
??????????? new Thread(new Player(i, cyclicBarrier)).start();
??????? }
??? }

??? class Player implements Runnable {
??????? private CyclicBarrier cyclicBarrier;
??????? private int id;

??????? public Player(int id, CyclicBarrier cyclicBarrier) {
??????????? this.cyclicBarrier = cyclicBarrier;
??????????? this.id = id;
??????? }

??????? @Override
??????? public void run() {
??????????? try {
??????????????? System.out.println("玩家" + id + "正在玩第一關...");
??????????????? cyclicBarrier.await();
??????????????? System.out.println("玩家" + id + "進入第二關...");
??????????? } catch (InterruptedException e) {
??????????????? e.printStackTrace();
??????????? } catch (BrokenBarrierException e) {
??????????????? e.printStackTrace();
??????????? }
??????? }
??? }
}

leekiang 2015-03-02 06:28 發表評論
]]>
java調用shellhttp://www.aygfsteel.com/leekiang/archive/2015/03/01/423104.htmlleekiangleekiangSat, 28 Feb 2015 16:29:00 GMThttp://www.aygfsteel.com/leekiang/archive/2015/03/01/423104.htmlhttp://www.aygfsteel.com/leekiang/comments/423104.htmlhttp://www.aygfsteel.com/leekiang/archive/2015/03/01/423104.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/423104.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/423104.htmlString str[] = { "/bin/sh", "-c", "echo '1' >> test.log" };
try {
??? run.exec(str);
} catch (IOException e) {
}


使用Jsch執行Shell腳本 [http://blog.csdn.net/basecn/article/details/6080741]
純Java通過SSH執行Linux命令的方法及代碼 [http://ilexes.blog.51cto.com/705330/531352]
Java調用 Shell的ftp命令 [http://blog.sina.com.cn/s/blog_59ca2c2a0100e9vn.html]

leekiang 2015-03-01 00:29 發表評論
]]>
jvm內存分析筆記http://www.aygfsteel.com/leekiang/archive/2015/02/17/422968.htmlleekiangleekiangMon, 16 Feb 2015 22:51:00 GMThttp://www.aygfsteel.com/leekiang/archive/2015/02/17/422968.htmlhttp://www.aygfsteel.com/leekiang/comments/422968.htmlhttp://www.aygfsteel.com/leekiang/archive/2015/02/17/422968.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/422968.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/422968.html1. java.lang.OutOfMemoryError: GC overhead limit exceeded原因
?? <http://blog.csdn.net/taijianyu/article/details/6606792>
?? <http://www.sunnybtoc.com/page/M0/S746/746195.html>
? ?
2. 用jhat分析·jmap -dump:format=b,file=mem.dat PID·命令導出來的文件時報錯
?? java.io.IOException: Unrecognized magic number
?? <https://forums.oracle.com/forums/thread.jspa?threadID=1542284> 沒找到原因
? ?
3. 命令
?? 1. jmap
?jmap -dump:live,format=b,file=heap.dmp PID 把本機的java內存映像導出到heap.dmp中
?jmap pid #打印內存使用的摘要信息
????? jmap –heap pid #java heap信息
????? jmap -histo:live pid #統計對象count ,live表示在使用
????? jmap -histo pid >mem.txt #打印比較簡單的各個有多少個對象占了多少內存的信息,一般重定向的文件
????? jmap -dump:format=b,file=mem.dat PID #將內存使用的詳細情況輸出到mem.dat 文件
?? 2. jhat 用來分析jmap導出的文件
????? 用jhat命令可以參看 jhat -port 7000 mem.dat
????? 然后使用:http://127.0.0.1:7000/ 查看類相關信息
?? 3. jstat
????? jstat -gcutil? PID
????? 例子:

??? S0????? S1???? E????? O????? P???? YGC???? YGCT??? FGC??? FGCT???? GCT
??? 11.63?? 0.00?? 56.46? 66.92? 98.49 162??? 0.248??? 6????? 0.331??? 0.579

??? S0? — Heap上的 Survivor space 0 區已使用空間的百分比
??? S1? — Heap上的 Survivor space 1 區已使用空間的百分比
??? E?? — Heap上的 Eden space 區已使用空間的百分比
??? O?? — Heap上的 Old space 區已使用空間的百分比
??? P?? — Perm space 區已使用空間的百分比
??? YGC — 從應用程序啟動到采樣時發生 Young GC 的次數
??? YGCT– 從應用程序啟動到采樣時 Young GC 所用的時間(單位秒)
??? FGC — 從應用程序啟動到采樣時發生 Full GC 的次數
??? FGCT– 從應用程序啟動到采樣時 Full GC 所用的時間(單位秒)
??? GCT — 從應用程序啟動到采樣時用于垃圾回收的總時間(單位秒)


###參考
1. [JMAP、jstat命令詳解](http://bbs.chinaunix.net/thread-3644198-1-1.html)
2. [J2SE6中使用jhat來分析內存堆](http://hi.baidu.com/tister/item/9444a3125796cf433a176eb9)


###jvm的內存回收過程是這樣的
對象在Eden Space創建,當Eden Space滿了的時候,gc就把所有在Eden Space中的對象掃描一次,
把所有有效的對象復制到第一個Survivor Space,同時把無效的對象所占用的空間釋放。
當Eden Space再次變滿了的時候,就啟動移動程序把Eden Space中有效的對象復制到第二個Survivor Space,
同時,也將第一個Survivor Space中的有效對象復制到第二個Survivor Space。如果填充到第二個Survivor Space
中的有效對象被第一個Survivor Space或Eden Space中的對象引用,那么這些對象就是長期存在的,
此時這些對象將被復制到Permanent Generation。



leekiang 2015-02-17 06:51 發表評論
]]>
java 應用監控http://www.aygfsteel.com/leekiang/archive/2015/02/17/422967.htmlleekiangleekiangMon, 16 Feb 2015 22:35:00 GMThttp://www.aygfsteel.com/leekiang/archive/2015/02/17/422967.htmlhttp://www.aygfsteel.com/leekiang/comments/422967.htmlhttp://www.aygfsteel.com/leekiang/archive/2015/02/17/422967.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/422967.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/422967.html
jwebap 監控org.apache.commons.dbcp.BasicDataSource時不知效果如何
JAMon

hyperic hq
probe?? http://www.lambdaprobe.org/downloads/1.7/probe.1.7b.zip

項目自動化之道—如何建構、部署、監控JAVA應用.pdf


http://chain.blog.163.com/blog/static/140848523201171623521235/? java使用java.lang.management監視和管理Java虛擬機

String processName = java.lang.management.ManagementFactory
.getRuntimeMXBean().getName();
System.out.println(processName.split("@")[0]);//進程ID

http://chain.blog.163.com/blog/static/1408485232011716111013282/ java通過調用命令獲取linux CPU、內存、磁盤信息

leekiang 2015-02-17 06:35 發表評論
]]>
Error: no `server' JVM at `C:\Program Files\Java\jre6\bin\server\jvm.dllhttp://www.aygfsteel.com/leekiang/archive/2013/02/17/395354.htmlleekiangleekiangSun, 17 Feb 2013 10:19:00 GMThttp://www.aygfsteel.com/leekiang/archive/2013/02/17/395354.htmlhttp://www.aygfsteel.com/leekiang/comments/395354.htmlhttp://www.aygfsteel.com/leekiang/archive/2013/02/17/395354.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/395354.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/395354.html

leekiang 2013-02-17 18:19 發表評論
]]>
JDK5筆記http://www.aygfsteel.com/leekiang/archive/2011/10/07/360108.htmlleekiangleekiangFri, 07 Oct 2011 07:05:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/10/07/360108.htmlhttp://www.aygfsteel.com/leekiang/comments/360108.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/10/07/360108.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/360108.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/360108.html@SuppressWarnings("unused")
@SuppressWarnings("unchecked")

eclipse支持的SuppressWarning的值如下,其他開發工具略有差異。
  • all to suppress all warnings
  • boxing to suppress warnings relative to boxing/unboxing operations
  • cast to suppress warnings relative to cast operations
  • dep-ann to suppress warnings relative to deprecated annotation
  • deprecation to suppress warnings relative to deprecation
  • fallthrough to suppress warnings relative to missing breaks in switch statements
  • finally to suppress warnings relative to finally block that don't return
  • hiding to suppress warnings relative to locals that hide variable
  • incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
  • nls to suppress warnings relative to non-nls string literals
  • null to suppress warnings relative to null analysis
  • restriction to suppress warnings relative to usage of discouraged or forbidden references
  • serial to suppress warnings relative to missing serialVersionUID field for a serializable class
  • static-access to suppress warnings relative to incorrect static access
  • synthetic-access to suppress warnings relative to unoptimized access from inner classes
  • unchecked to suppress warnings relative to unchecked operations
  • unqualified-field-access to suppress warnings relative to field access unqualified
  • unused to suppress warnings relative to unused code
2,注解
注解是加入到java源代碼中的一些描述性的數據,本身不能執行。可利用反射(當RetentionPolicy=RUNTIME)或文本解析取得注解信息。
@Target,@Retention為元注解。
SuppressWarnings的源碼如下:
@Target({TYPE,?FIELD,?METHOD,?PARAMETER,?CONSTRUCTOR,?LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public?@interface?SuppressWarnings?{
????String[]?value();
}

package?java.lang.annotation;

public?enum?RetentionPolicy?{
????
/**
?????*?Annotations?are?to?be?discarded?by?the?compiler.
?????
*/
????SOURCE,

????
/**
?????*?Annotations?are?to?be?recorded?in?the?class?file?by?the?compiler
?????*?but?need?not?be?retained?by?the?VM?at?run?time.??This?is?the?default
?????*?behavior.
?????
*/
????CLASS,

????
/**
?????*?Annotations?are?to?be?recorded?in?the?class?file?by?the?compiler?and
?????*?retained?by?the?VM?at?run?time,?so?they?may?be?read?reflectively.
?????*
?????*?
@see?java.lang.reflect.AnnotatedElement
?????
*/
????RUNTIME
}


package?java.lang.annotation;
public?enum?ElementType?{
????TYPE,
????FIELD,
????METHOD,
????PARAMETER,
????CONSTRUCTOR,
????LOCAL_VARIABLE,
????ANNOTATION_TYPE,
????PACKAGE
}

3,泛型

????public?<T>?T?testT(List<T>??list){
????????T?t?
=(T)?list;
????????
return?t;
????}

4,自動裝箱(AutoBoxing

關于row type
http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it/
http://www.aygfsteel.com/sevenguin/archive/2011/04/20/348628.html

轉:J2SE5中的最新注釋功能SuppressWarnings
http://wenku.baidu.com/view/9d20440f844769eae009edf2.html
實戰篇:設計自己的Annotation
Supported Values for @SuppressWarnings

leekiang 2011-10-07 15:05 發表評論
]]>
log4jhttp://www.aygfsteel.com/leekiang/archive/2011/09/27/359602.htmlleekiangleekiangTue, 27 Sep 2011 05:54:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/09/27/359602.htmlhttp://www.aygfsteel.com/leekiang/comments/359602.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/09/27/359602.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/359602.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/359602.html報錯:
log4j:ERROR Document root element "log4j:configuration", ?must match DOCTYPE root "null".
解決:
Try adding this to the second line (the line below <?xml ...?>)...
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">



Log4J的數據庫寫入方式就是一個雞肋,沒有使用連接池,也不支持addBatch。
只是把用戶輸出的log現在一個ArrayList中保存,當其數量達到了BufferSize,才啟動寫日志。參看其源代碼(JDBCAppender.java)

可以考慮把org.apache.log4j.jdbc.JDBCAppender換掉。參考

log4j日志異步化大幅提升系統性能
http://wiki.springside.org.cn/display/SpringSide3/Log
springside3.*中log4j和java.util.concurrent的結合使用
把重要的業務日志異步批量寫入數據庫 LOG4J
用log4j把日志異步寫入數據庫中
log4j中再次看ThreadLocal用法

leekiang 2011-09-27 13:54 發表評論
]]>
java基礎(續)http://www.aygfsteel.com/leekiang/archive/2011/09/03/357864.htmlleekiangleekiangFri, 02 Sep 2011 17:14:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/09/03/357864.htmlhttp://www.aygfsteel.com/leekiang/comments/357864.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/09/03/357864.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/357864.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/357864.html Jamon(Java Application Monitor)是一款免費的、高性能的、線程安全的Java程序,它使得開發人員能夠容易地完成對生產環境應用程序的監控。

Java保證讀和寫32位數或者更小的值是原子操作,也就是說可以在一步完成,因而不可能被打斷,因此這樣的讀和寫不需要同步。以下的代碼是線程安全(thread safe)的:

public class Example{
  private int value; // More code here...
  public void set (int x){
   // NOTE: No synchronized keyword
   this.value = x;
  }
}

不過,這個保證僅限于讀和寫,下面的代碼不是線程安全的:

public void increment (){
  // This is effectively two or three instructions:
  // 1) Read current setting of ’value’.
  // 2) Increment that setting.
  // 3) Write the new setting back.
  ++this.value;
}



算法:統計最近一分鐘的請求數量http://www.iteye.com/problems/46542


leekiang 2011-09-03 01:14 發表評論
]]>
java知識點http://www.aygfsteel.com/leekiang/archive/2011/03/13/346174.htmlleekiangleekiangSun, 13 Mar 2011 15:38:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/03/13/346174.htmlhttp://www.aygfsteel.com/leekiang/comments/346174.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/03/13/346174.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/346174.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/346174.htmldouble d =?1?/?4;System.out.println(d);//輸出為0

2,??? public static void main(String[] args) {
??? ??? StringBuffer a = new StringBuffer("a");
??? ??? StringBuffer b = new StringBuffer("b");
??? ??? append(a, b);
??? ??? System.out.println(a.toString() + "," + b.toString());//輸出為"ab,a"
??? }

??? public static void append(StringBuffer a, StringBuffer b) {
??? ??? a.append(b);
??? ??? b = a;
??? }
?? 解釋:由于java方法傳值是值傳遞,所以方法里面的a,b雖然和方法外的a,b指向的對象一樣,但是這兩個引用在棧中的位置不一樣。
過程大概是首先在棧中復制引用a為a',b為b',并令a'指向a所指的在堆中的StringBuffer對象,b'指向b所指的在堆中的StringBuffer對象。
因此方法中的b=a只是起到了b'=a'的作用,并沒有影響方法外b的指向。
??????? 其實public static void append(StringBuffer a, StringBuffer b)中的變量a,b只是main方法中的變量a,b的引用地址副本,也就是說相當于append中的a與main中的a是指向同一個地址,append中 的b與main中的b是指向同一個地址,所以a.append(b)操作影響到了main方法中的a,但是append方法中的b=a;操作只是改變了 append方法的中b的指向,并沒有改變main方法中b的指向。
??????? java是按值傳遞,對象類型的話,分為棧上的引用和堆上的對象,棧上的引用被復制一份,如果操作堆上的對象則對象改變,但是如果操作引用則不改變
??????? java方法的參數傳遞有兩種規則:(1)按值傳遞(by value) ,八種基本數據類型和String? (2)按址傳遞(by address) ,除String以外的所有復合數據類型,包括數組、類和接口

3,如果使用switch,那么每一個case和default里都要加break

Java容易搞錯的知識點


leekiang 2011-03-13 23:38 發表評論
]]>
Java字符串http://www.aygfsteel.com/leekiang/archive/2011/03/13/346148.htmlleekiangleekiangSun, 13 Mar 2011 09:16:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/03/13/346148.htmlhttp://www.aygfsteel.com/leekiang/comments/346148.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/03/13/346148.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/346148.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/346148.htmlString s2="a"+"b";
System.out.println(s1==s2);//true

String s1 = "abc";
String s2 = "ab";
String s3 = s2 + "c";
System.out.println((s1 == s3));//false

String s1 = "abc";
final String s2 = "ab";
String s3 = s2 + "c";
System.out.println((s1 == s3));//true


參考:
理解Java常量池
Java String對象的經典問題(new String())
Java堆.棧和常量池 筆記
java編譯器對string常量表達式的處理和優化
Java 程序內存分析



leekiang 2011-03-13 17:16 發表評論
]]>
關于OSGIhttp://www.aygfsteel.com/leekiang/archive/2011/03/05/345755.htmlleekiangleekiangFri, 04 Mar 2011 16:12:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/03/05/345755.htmlhttp://www.aygfsteel.com/leekiang/comments/345755.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/03/05/345755.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/345755.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/345755.html1,OSGi,Java模塊化框架的另類進化 http://developer.51cto.com/art/201003/190584.htm
2,獨家專訪林昊:一步一步了解Java模塊化 http://developer.51cto.com/art/201001/181503.htm


leekiang 2011-03-05 00:12 發表評論
]]>
java類的加載http://www.aygfsteel.com/leekiang/archive/2011/02/24/345090.htmlleekiangleekiangThu, 24 Feb 2011 09:58:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/02/24/345090.htmlhttp://www.aygfsteel.com/leekiang/comments/345090.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/02/24/345090.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/345090.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/345090.htmlsun.misc.Launcher$AppClassLoader@19821f
這個加載器是系統類加載器。ClassLoader.getSystemResourceAsStream("com/config.xml")使用的就是系統類加載器定位資源的。


??? //JDK1.6,java.lang.ClassLoader的loadClass(String?name,?boolean?resolve)方法的源碼
protected?synchronized?Class<?>?loadClass(String?name,?boolean?resolve)
????
throws?ClassNotFoundException
????{
????
//?First,?check?if?the?class?has?already?been?loaded
????Class?c?=?findLoadedClass(name);
????
if?(c?==?null)?{
????????
try?{
????????
if?(parent?!=?null)?{
?????????? //
如果parent不為null,則調用parent的loadClass進行加載?
????????????c?=?parent.loadClass(name,?false);
????????}?
else?{
?????????? //
parent為null,則調用BootstrapClassLoader進行加載
????????????c?=?findBootstrapClassOrNull(name);
????????}
????????}?
catch?(ClassNotFoundException?e)?{
????????????????
//?ClassNotFoundException?thrown?if?class?not?found
????????????????
//?from?the?non-null?parent?class?loader
???????? }
???????
if?(c?==?null)?{
????????????
//?If?still?not?found,?then?invoke?findClass?in?order to?find?the?class.
??????????? //
如果仍然無法加載成功,則調用自身的findClass進行加載
????????????c?=?findClass(name);
????????}
????}
????
if?(resolve)?{
????????resolveClass(c);
????}
????
return?c;
????}

java中共有三種類型的類加載器:
??? 1、引導(bootstrap)類加載器(用來加載java API類),例如加載java.lang.String類
??? 2、擴展類加載器(就是sun.misc.Launcher$ExtClassLoader,用來加載jre\lib\ext目錄下的jar包)
??? 3、系統類加載器(就是sun.misc.Launcher$AppClassLoader,主要用來加載CLASSPATH設置目錄中的Class)

創建一個URLClassLoader,發現其父加載器(parent,注意不是父類)的類型為sun.misc.Launcher$AppClassLoader,而sun.misc.Launcher$AppClassLoader和sun.misc.Launcher$ExtClassLoader的父類都是URLClassLoader。AppClassLoader的父加載器是ExtClassLoader,ExtClassLoader的父加載器為null,即bootstrap類加載器。

類加載有個雙親委托模式,
AppClassLoader的父加載器是ExtClassLoader ,ExtClassLoader 的父加載器是bootstrap classloader,bootstrap 是C++寫的類加載器,會負責加載java核心類庫,就是jre/lib/rt.jar
ExtClassLoader會加載擴展類庫,就是jre/lib/ext下的庫。

雙親委托模式就是子加載器會先委托父加載器加載,父加載器加載不了子加載器才加載,
這樣做避免了重復加載,也加強了java的安全了,防止了惡意加載器去加載核心庫。

String?name?=?"com.domain.Account";
????????????
????????????URL?url1?
=?new?URL("file:/D:/workspace/test/bin/");
????????????ClassLoader?cl?
=?new?URLClassLoader(new?URL[]?{?url1?});
????????????Class?c1?
=?cl.loadClass(name);
????????????
????????????URL?url2?
=?new?URL("file:/D:/workspace/test/bin");
????????????ClassLoader?cl2?
=?new?URLClassLoader(new?URL[]?{?url2?});
????????????Class?c2?
=?cl2.loadClass(name);
????????????
????????????System.out.println(c1
==c2);//返回true,原因是都是用系統類加載器AppClassLoader加載的

注意:
1,在類A中使用Class.forName加載類B,那么加載類A的類加載器將會用于加載類B,這樣兩個類的類加載器是同一個。
2,Class.forName("")和classLoader.load("")的區別主要是前者會做初始化,后者不會。見jdk注釋:A?call?to?forName("X")?causes?the?class?named?X?to?be?initialized.? 自己分別用兩種方式裝載一個帶靜態代碼的類就知道了。jdbc需要通過Class.forName("")的方式來裝載JDBC驅動程序(例如 Class.forName("com.mysql.jdbc.Driver"),之所以用Class.forName而沒有用 ClassLoader.load(),就是因為需要JVM完成Driver的初始化工作,而不僅僅是裝載),然后通過一個統一的工廠類 Java.sql.DriverManager來取得數據庫連接,并執行各種操作。Class.forName("")不僅load?class而且還保證resolve這個class,包括常量池解析,類初始化。。。這樣JDBC驅動使用這個方法,才能保證類里的靜態方法執行,一般驅動類的靜態方法會向DriverManager注冊自己,如果用classloader.load("")就不一定會resolve這個class,也就不能保證注冊驅動類!
看了com.mysql.jdbc.Driver類的源碼,靜態代碼就一句:java.sql.DriverManager.registerDriver(new com.mysql.jdbc.Driver())
3,

參考
1)java系統類加載器AppClassLoader之淺談 http://blog.sina.com.cn/s/blog_4db6a3f101000do1.html
2)java類加載原理分析 http://gongmingwind.javaeye.com/blog/338366
3)解讀ClassLoader http://www.javaeye.com/topic/83978
4)http://xyiyy.javaeye.com/blog/362107

Retrotranslator是一個Java字節碼轉換工具。它能夠把用JDK5.0編譯的Java Class轉換成可運行在JVM1.4

leekiang 2011-02-24 17:58 發表評論
]]>
深入java虛擬機筆記http://www.aygfsteel.com/leekiang/archive/2011/01/29/343749.htmlleekiangleekiangSat, 29 Jan 2011 13:36:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/01/29/343749.htmlhttp://www.aygfsteel.com/leekiang/comments/343749.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/01/29/343749.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/343749.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/343749.html2,java虛擬機是一臺抽象的計算機,主要任務是裝載class文件并且執行其中的字節碼。不同的java虛擬機,其執行引擎的實現可能不一樣。分為軟件實現和硬件實現(內嵌在芯片),軟件實現有以下幾種:(1)每次都會解釋字節碼(2)即時編譯,即編譯成本低機器代碼,緩存起來可以重用(3)自適應優化器
3,每一個類被裝載的時候,java虛擬機都監視這個類,看它到底是被啟動(bootstrap)類裝載器還是被用戶定義類裝載器裝載。當被裝載的類引用了另外一個類時,虛擬機就會使用裝載第一個類的類裝載器裝載被引用的類。由于java虛擬機采用這種方式進行類的加載,所以被裝載的類默認情況下只能看到被同一個類裝載器裝載的類。通過這種方法,java的體系結構允許在一個java應用程序中建立多個命名空間。運行時的java程序中的每一個類裝載器都有它自己的命名空間。
例子:瀏覽器上的java虛擬機為不同的網絡地址創建不同的用戶定義類裝載器,用來裝載不同來源的class文件,這種不同網址的applet就不會相互影響。
問題:1)自己寫的類如果調用了java的api,那么類裝載器是一個什么樣的情況。同一個類可能被不同的類裝載器裝載?
????? 2)看一下tomcat的類裝載器的實現
?? ?? 3)java的虛擬機與ruby和python的有何區別?
?? ?? 4)有沒有一種打包工具,把java代碼打包成不需要java虛擬機的本地可執行代碼
?? ?? 5)java的動態連接和動態擴展指的是什么?
4,java語言的特殊之處是程序既被編譯又被解釋。首先,編譯器將程序編譯為一種稱之為java字節碼(bytecode)的與平臺無關的中間語言。解釋器分析并運行每條java字節碼指令。編譯只發生一次;而解釋在每次執行程序時都會執行(通常是如此,具體實現可能不一樣)。



12,聲明一個對象時不會運行類的靜態區塊,在以下情況下會運行靜態區塊:
??? 1)new一個對象時;
??? 2)調用靜態方法時;
??? 3)Class.forName("類名")


參考
1,http://xyiyy.javaeye.com/blog/362092
2,http://xyiyy.javaeye.com/blog/362107


leekiang 2011-01-29 21:36 發表評論
]]>
值和引用http://www.aygfsteel.com/leekiang/archive/2011/01/02/342144.htmlleekiangleekiangSat, 01 Jan 2011 17:32:00 GMThttp://www.aygfsteel.com/leekiang/archive/2011/01/02/342144.htmlhttp://www.aygfsteel.com/leekiang/comments/342144.htmlhttp://www.aygfsteel.com/leekiang/archive/2011/01/02/342144.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/342144.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/342144.html??????? Integer?v1?=?100;
????????Integer?v2?
=?100;
????????System.out.println(v1?
==?v2);?//?輸出:true
????????
????????Integer?w1?
=?200;
????????Integer?w2?
=?200;
????????System.out.println(w1?
==?w2);?//?輸出:false

????????Integer?s1?
=?new?Integer(100);
????????Integer?s2?
=?new?Integer(100);
????????System.out.println(s1?
==?s2);?//?輸出:false
????????
????????String?str1
="test";
????????String?str2
="test";
????????System.out.println(str1
==str2);//?輸出:true
????????
????????String?nstr1
=new?String("aa");
????????String?nstr2
=new?String("aa");
????????System.out.println(nstr1
==nstr2);?//?輸出:false
原因:當給Integer變量直接賦整數值時,如果這個數值位于[-128,127]內,JVMJava Virtual Machine)就直接使用cache中緩存的Integer對象,否則,JVM會重新創建一個Integer對象。

參考:
http://www.cnblogs.com/bitfan/archive/2010/10/24/1859687.html


leekiang 2011-01-02 01:32 發表評論
]]>
java的statichttp://www.aygfsteel.com/leekiang/archive/2010/12/30/341941.htmlleekiangleekiangWed, 29 Dec 2010 17:20:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/12/30/341941.htmlhttp://www.aygfsteel.com/leekiang/comments/341941.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/12/30/341941.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/341941.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/341941.html Static 的意義與實作方式

?

Class(static) field :共用一塊記憶體
class(static) method
:共用一塊記憶體
instance(
static) field :隨著每個 instance 各有一塊記憶體
instance (
static) method :共用一塊記憶體
??? instance method
為什么不是隨著每個 instance 占有一塊記憶體,反倒是共用一塊記憶體?其實,讓每個 instance method 如同 instance field 一樣,隨著每個 instance 占有一塊記憶體,這么做當然是可以的,只是 Java 編譯器和 JVM 都不這么做,因為太浪費記憶體空間了。一個 field 少則占用一個 byte ,多則占用數百 Byte ,但是 method 少則數個 byte ,多則數百 Kilo Byte Mehtod 耗費的記憶體是 field 的數百倍,甚至數千倍,當然是能共用就盡量共用,比較不會消耗記憶體。既然 JVM 讓一個 class 的所有 instance 共用相同的 instance method ,下面兩行程式碼在 instanceMethod() 內部時,如何區分是 instance1 instance2
instance1.instanceMethod();
instance2.instanceMethod();
因為編譯器會幫我們在把 instance1 instance2 個別傳入 instanceMethod() 中當作第一個參數。也就是說,任何 instance method 參數的實際個數都會比表面上多一個,這個多出來的參數是由 Java 編譯器幫我們加上去的,用來代表對應的 instance 。此參數的變數名稱為 this ,也是 Java 的一個關鍵字( keyword )。
???
當調用某個 instance method 或使用某個 instance field 時,你必須在前面加上該 instance 的名稱,如果該 instance method/field 相關的 instance 和當時程式碼所在的 instance method instance 指的是同一個 instance 時,該 instance 的名稱就是 this ,這種情況下,你也可以選擇不在前面加上「 this. 」。
???
然而,在某些狀況下,非得在前面加上「 this. 」不可。例如,當 method 中的參數或區域變數和 instance field 名稱完全相同時,如果不在前面冠上「 this. 」,那么指的是參數或區域變數;如果在前面冠上「 this. 」,那么指的才是 instance field

轉自http://www.aygfsteel.com/guoyongfei/archive/2009/02/06/253571.html


leekiang 2010-12-30 01:20 發表評論
]]>
線程安全類http://www.aygfsteel.com/leekiang/archive/2010/11/15/338086.htmlleekiangleekiangMon, 15 Nov 2010 05:53:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/11/15/338086.htmlhttp://www.aygfsteel.com/leekiang/comments/338086.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/11/15/338086.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/338086.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/338086.html當一個類已經很好的同步以保護它的數據時,這個類就稱為“線程安全的”。 即使是線程安全類,也應該特別小心,因為操作的線程是間仍然不一定安全。

import?java.util.Collections;
import?java.util.LinkedList;
import?java.util.List;

public?class?TestThread?{
????
public?static?void?main(String[]?args)?{
????????
final?NameList?nl?=?new?NameList();
????????nl.add(
"aaa");
????????
class?NameDropper?extends?Thread?{
????????????
public?void?run()?{
????????????????String?name?
=?nl.removeFirst();
????????????????System.out.println(name);
????????????}
????????}
????????Thread?t1?
=?new?NameDropper();
????????Thread?t2?
=?new?NameDropper();
????????t1.start();
????????t2.start();
????}
}

class?NameList?{
????
private?List?nameList?=?Collections.synchronizedList(new?LinkedList());

????
public?void?add(String?name)?{
????????nameList.add(name);
????}
????
public?String?removeFirst()?{//removeFirst方法必須同步
????????if?(nameList.size()?>?0)?{
????????????
try?{
????????????????Thread.sleep(
100);
????????????}?
catch?(InterruptedException?e)?{
????????????????e.printStackTrace();
????????????}
????????????
return?(String)?nameList.remove(0);
????????}?
else?{
????????????
return?null;
????????}
????}
}



http://lavasoft.blog.51cto.com/62575/99155


leekiang 2010-11-15 13:53 發表評論
]]>
java處理浮點數http://www.aygfsteel.com/leekiang/archive/2010/07/27/327244.htmlleekiangleekiangTue, 27 Jul 2010 10:22:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/07/27/327244.htmlhttp://www.aygfsteel.com/leekiang/comments/327244.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/07/27/327244.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/327244.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/327244.html?? ???? assertEquals(new BigDecimal("3.50"),new BigDecimal("3.5"));//不相等
?? ?}

?System.out.println(0.030*100);//輸出3.0
?System.out.println(0.031*100);//輸出3.1
?System.out.println(0.032*100);//輸出3.2
?System.out.println(0.033*100);//輸出3.3000000000000003
?System.out.println(0.034*100);//輸出3.4000000000000004
?System.out.println(0.035*100);//輸出3.5000000000000004
?System.out.println(0.036*100);//輸出3.5999999999999996
?System.out.println(0.037*100);//輸出3.6999999999999997
?System.out.println(0.038*100);//輸出3.8
?System.out.println(0.039*100);//輸出3.9
?
?BigDecimal b2 = new BigDecimal(0.236);
?System.out.println(b2);//輸出0.2359999999999999875655021241982467472553253173828125
?
?描述:
?當我們使用一些"特殊的數字"進行運算時,或者調用BigDecimal中new BigDecimal(double val)進行構造的時候,將得到意想不到的結果。
?原因:
?Java中,浮點類型是依據IEEE754標準的。IEEE754定義了32位和64位雙精度兩種浮點二進制小數標準。采用二進制表示double,float等浮點數是不準確的。
同時BigDecimal的API聲明,建議使用new BigDecimal(String val)進行構造,使用new BigDecimal(double val)進行構造的時候,將得到意想不到的結果(The results of this constructor can be somewhat unpredictable)。

解決辦法:
1,通過String結合BigDecimal來轉換。
String val = "0.236";
//使用new BigDecimal(String val)進行構造
BigDecimal a = new BigDecimal(""+val);
BigDecimal b = new BigDecimal(""+100);
//小數的位數與構造參數的位數一致
System.out.println(a.multiply(b));//輸出23.600

2,使用DecimalFormat來確定小數點后位數
double val = 0.236*100;
//保留小數點后兩位,若保留三位為"#.000"
DecimalFormat df = new DecimalFormat("#.00");
String str = df.format(val);
System.out.println(Double.valueOf(str));//輸出23.6

感謝
http://www.aygfsteel.com/kalman03/archive/2010/10/25/336121.html


leekiang 2010-07-27 18:22 發表評論
]]>
分頁http://www.aygfsteel.com/leekiang/archive/2010/06/29/324817.htmlleekiangleekiangTue, 29 Jun 2010 11:19:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/06/29/324817.htmlhttp://www.aygfsteel.com/leekiang/comments/324817.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/06/29/324817.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/324817.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/324817.htmlhttp://www.javaeye.com/topic/121756
http://www.javaeye.com/topic/57909
http://www.javaeye.com/topic/400225
http://www.aygfsteel.com/weijy/archive/2008/09/27/231449.html
http://blog.sina.com.cn/s/blog_537a7ce301008o4y.html
http://lengyue-dick.javaeye.com/blog/247347
http://qdjinxin.javaeye.com/blog/674082

leekiang 2010-06-29 19:19 發表評論
]]>
log筆記http://www.aygfsteel.com/leekiang/archive/2010/05/27/322025.htmlleekiangleekiangThu, 27 May 2010 06:14:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/05/27/322025.htmlhttp://www.aygfsteel.com/leekiang/comments/322025.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/05/27/322025.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/322025.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/322025.html在使用log4j,common-log這樣的log框架時,發現很多代碼中這樣寫
if ? (log.isDebugEnabled()) ? {
? ? ? ? ? log.debug( "xxxx ");
}

我很奇怪,為什么要與log.isDebugEnabled()?既然log.debug()在沒有指定輸出級別為DEBUG時不會有輸出,為什么還要在 前面加一個isDebugEnabled()的判斷?
答:
為了效率,如果上述那個代碼那么簡單是沒有必要的
但是如果這樣
if ? (log.isDebugEnabled()) ? {
? ? ? ? ? log.debug(buildFullString());
}
如果這個buildFullString效率不太高,那么如果直接寫log.debug(buildFullString());的話
雖然它不會打印語句,但是buildFullString還是被執行了,這樣就白費了功夫
所以加上isDebugEnabled就可以避免執行buildFullString了
這個方法一般用在認為buildFullString這個函數效率不太高的情況下

http://topic.csdn.net/u/20070119/16/e9cf879c-697b-482a-9d55-21bfb7a16216.html


leekiang 2010-05-27 14:14 發表評論
]]>
JVM筆記http://www.aygfsteel.com/leekiang/archive/2010/05/26/321947.htmlleekiangleekiangWed, 26 May 2010 10:51:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/05/26/321947.htmlhttp://www.aygfsteel.com/leekiang/comments/321947.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/05/26/321947.html#Feedback1http://www.aygfsteel.com/leekiang/comments/commentRss/321947.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/321947.html在新版本的java里面,同步比gc慢
所以以前很多framework里面都有pool的設定,現在都取消了
現在只有一些數據庫連接等IO資源做pool以外,基本的數據class已經都不作pool了
pool 一般用在創建很大消費的對象時才用的。 比如 connection, tapestry的page。 像new HashMap這樣的 是沒有必要的。


leekiang 2010-05-26 18:51 發表評論
]]>
正則表達式筆記http://www.aygfsteel.com/leekiang/archive/2010/04/21/318955.htmlleekiangleekiangWed, 21 Apr 2010 04:30:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/04/21/318955.htmlhttp://www.aygfsteel.com/leekiang/comments/318955.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/04/21/318955.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/318955.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/318955.html?? ??? ?Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
?? ??? ?Matcher mt = pattern.matcher(str);
?? ??? ?while (mt.find()) {
?? ??? ?String s=mt.group();
?? ??? ?}
?? ???? String regex2 = ">.*?</a>";// 標題部分
?? ???? String regex3 = "imgs/[([0-9])]+.(jpg|gif|png|bmp)";//取圖片

輸入例子可產生正則表達式
http://sourceforge.net/projects/quickrex/

在線測試
http://www.fileformat.info/tool/regex.htm



leekiang 2010-04-21 12:30 發表評論
]]>
Adding Socket Timeout to java.net.URLConnection (JDK 1.2)http://www.aygfsteel.com/leekiang/archive/2010/04/14/318278.htmlleekiangleekiangWed, 14 Apr 2010 09:09:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/04/14/318278.htmlhttp://www.aygfsteel.com/leekiang/comments/318278.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/04/14/318278.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/318278.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/318278.htmlAdding Socket Timeout to java.net.URLConnection (JDK 1.2)

found a bug , see "connected = true;" in public void connect() throws IOException {


Note: 05/11/01 Sam Found a patch for borland

As I got the email:

Just writing to inform you theis patch for 1.3 works with the 1.3 shipped with borland JBuilder 4 (not sure which excat version it is)

the only problems I had where that the code was a bit messed up, following are the changes made to it to make it work.

				
public void SetTimeout(int i)
throws SocketException
{
this.timeout = i; // Should be i not -1 <------------ERROR
serverSocket.setSoTimeout(i) ;
}

public boolean parseHTTP(MessageHeader header, ProgressEntry entry)
throws java.io.IOException
{
if( this.timeout != -1 ) {
try {
serverSocket.setSoTimeout(timeout) ; // should be timeout not i <---------------ERROR
} catch( SocketException e ) {
throw new java.io.IOException("unable to set socket timeout!") ;
}
}

return super.parseHTTP(header, entry) ;
}
Sam

Under JDK 1.3, which is HTTP 1.1 compatible, the InterruptedIOException gets caught by the socket I/O routines and ignored. input is read in "chunks". I debugged the existing code under 1.3, the Timeout is getting set properly etc., but the exception gets caught in the underlying I/O routines, which have a single retry if any IOExceptions are thrown. Thanks a lot Sun....

3/22/01: Patch for JDK 1.3 unverified

Patch code for JDK 1.3 from Matt Ho (unverified)

				
----[ snip ]----

import sun.net.www.MessageHeader ;
import sun.net.ProgressEntry ;

.
.
.

private int timeout = -1 ;

public void SetTimeout(int i)
throws SocketException
{
this.timeout = -1 ;
serverSocket.setSoTimeout(i) ;
}

public boolean parseHTTP(MessageHeader header, ProgressEntry entry)
throws java.io.IOException
{
if( this.timeout != -1 ) {
try {
serverSocket.setSoTimeout(i) ;
} catch( SocketException e ) {
throw new java.io.IOException("unable to set socket timeout!") ;
}
}

return super.parseHTTP(header, entry) ;
}

----[ snip ]----

On with the rest of the stuff

The BSD socket API supports a timeout option (the option is SO_TIMEOUT), which is also supported in java.net.socket. Unfortunately, java.net.URLConnection does not expose the underlying socket. So if you have a URL connection that attempts to connect to a dead URL (i.e., the URL is well formed and exists but the site is down), the socket will eventually timeout using the operating system's default timeout (420 seconds on Win NT). The timeout is a very long time, e.g., for spiders or URL checking.

The following files illustrate a technique to introduce a socket timeout to URL connection, based upon the actual java source code itself (see the open source community licensing at JavaSoft).

The Base classes, or URLConnection internals

Java's implementation of networking is protocol independent, as well as object oriented. Therefore the implementation is not as straightfoward as one might imagine.

URLConnection relies upon several internal classes using a client/server model as well as a "factory" design pattern. The client's base class is sun.net.www.http.HttpClient. This class is extended for the purpose of exposing the socket.

The default factory is URLStreamHandlerFactory, which indirectly "handles" the creation of an HTTP client by instantiating a class that is specific to the HTTP protocol: sun.net.www.protocol.http.Handler. The handler actually creates the client.

In practice, the factory is only necessary to mimic java's implementation, but only the Handler is really needed.

Derived Classes

We derive 4 classes so as to preserve the symmetry with the java source code:

HttpURLConnectionTimeout extends sun.net.www.protocol.http.HttpURLConnection
HttpTimeoutHandler extends sun.net.www.protocol.http.Handler
HttpTimeoutFactory implements java.net.URLStreamHandlerFactory
HttpClientTimeout extends sun.net.www.http.HttpClient

On with the source code.


HttpURLConnectionTimeout

// whatever package you want
import sun.net.www.http.HttpClient;
import java.net.*;
import java.io.*;
public class HttpClientTimeout extends HttpClient
{
public HttpClientTimeout(URL url, String proxy, int proxyPort) throws IOException
{
super(url, proxy, proxyPort);
}

public HttpClientTimeout(URL url) throws IOException
{
super(url, null, -1);
}

public void SetTimeout(int i) throws SocketException {
serverSocket.setSoTimeout(i);
}

/* This class has no public constructor for HTTP. This method is used to
* get an HttpClient to the specifed URL. If there's currently an
* active HttpClient to that server/port, you'll get that one.
*
* no longer syncrhonized -- it slows things down too much
* synchronize at a higher level
*/
public static HttpClientTimeout GetNew(URL url)
throws IOException {
/* see if one's already around */
HttpClientTimeout ret = (HttpClientTimeout) kac.get(url);
if (ret == null) {
ret = new HttpClientTimeout (url); // CTOR called openServer()
} else {
ret.url = url;
}
// don't know if we're keeping alive until we parse the headers
// for now, keepingAlive is false
return ret;
}

public void Close() throws IOException
{
serverSocket.close();
}

public Socket GetSocket()
{
return serverSocket;
}


}

HttpTimeoutFactory

import java.net.*;

public class HttpTimeoutFactory implements URLStreamHandlerFactory
{
int fiTimeoutVal;
public HttpTimeoutFactory(int iT) { fiTimeoutVal = iT; }
public URLStreamHandler createURLStreamHandler(String str)
{
return new HttpTimeoutHandler(fiTimeoutVal);
}

}

HttpTimeoutHandler

import java.net.*;
import java.io.IOException;

public class HttpTimeoutHandler extends sun.net.www.protocol.http.Handler
{
int fiTimeoutVal;
HttpURLConnectionTimeout fHUCT;
public HttpTimeoutHandler(int iT) { fiTimeoutVal = iT; }

protected java.net.URLConnection openConnection(URL u) throws IOException {
return fHUCT = new HttpURLConnectionTimeout(u, this, fiTimeoutVal);
}

String GetProxy() { return proxy; } // breaking encapsulation
int GetProxyPort() { return proxyPort; } // breaking encapsulation

public void Close() throws Exception
{
fHUCT.Close();
}

public Socket GetSocket()
{
return fHUCT.GetSocket();
}
}

HttpURLConnectionTimeout

import java.net.*;
import java.io.*;
import sun.net.www.http.HttpClient;

public class HttpURLConnectionTimeout extends sun.net.www.protocol.http.HttpURLConnection
{
int fiTimeoutVal;
HttpTimeoutHandler fHandler;
HttpClientTimeout fClient;
public HttpURLConnectionTimeout(URL u, HttpTimeoutHandler handler, int iTimeout) throws IOException
{
super(u, handler);
fiTimeoutVal = iTimeout;
}

public HttpURLConnectionTimeout(URL u, String host, int port) throws IOException
{
super(u, host, port);
}

public void connect() throws IOException {
if (connected) {
return;
}
try {
if ("http".equals(url.getProtocol()) /* && !failedOnce <- PRIVATE */ ) {
// for safety's sake, as reported by KLGroup
synchronized (url)
{
http = HttpClientTimeout.GetNew(url);
}
fClient = (HttpClientTimeout)http;
((HttpClientTimeout)http).SetTimeout(fiTimeoutVal);
} else {
// make sure to construct new connection if first
// attempt failed
http = new HttpClientTimeout(url, fHandler.GetProxy(), fHandler.GetProxyPort());
}
ps = (PrintStream)http.getOutputStream();
} catch (IOException e) {
throw e; }
// this was missing from the original version
connected = true;
}

/**
* Create a new HttpClient object, bypassing the cache of
* HTTP client objects/connections.
*
* @param url the URL being accessed
*/
protected HttpClient getNewClient (URL url)
throws IOException {
HttpClientTimeout client = new HttpClientTimeout (url, (String)null, -1);
try {
client.SetTimeout(fiTimeoutVal);
} catch (Exception e)
{ System.out.println("Unable to set timeout value"); }
return (HttpClient)client;
}

/**
* opens a stream allowing redirects only to the same host.
*/
public static InputStream openConnectionCheckRedirects(URLConnection c)
throws IOException
{
boolean redir;
int redirects = 0;
InputStream in = null;

do {
if (c instanceof HttpURLConnectionTimeout) {
((HttpURLConnectionTimeout) c).setInstanceFollowRedirects(false);
}

// We want to open the input stream before
// getting headers, because getHeaderField()
// et al swallow IOExceptions.
in = c.getInputStream();
redir = false;

if (c instanceof HttpURLConnectionTimeout) {
HttpURLConnectionTimeout http = (HttpURLConnectionTimeout) c;
int stat = http.getResponseCode();
if (stat >= 300 && stat <= 305 &&
stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
URL base = http.getURL();
String loc = http.getHeaderField("Location");
URL target = null;
if (loc != null) {
target = new URL(base, loc);
}
http.disconnect();
if (target == null
|| !base.getProtocol().equals(target.getProtocol())
|| base.getPort() != target.getPort()
|| !HostsEquals(base, target)
|| redirects >= 5)
{
throw new SecurityException("illegal URL redirect");
}
redir = true;
c = target.openConnection();
redirects++;
}
}
} while (redir);
return in;
}

// Same as java.net.URL.hostsEqual


static boolean HostsEquals(URL u1, URL u2)
{
final String h1 = u1.getHost();
final String h2 = u2.getHost();

if (h1 == null) {
return h2 == null;
} else if (h2 == null) {
return false;
} else if (h1.equalsIgnoreCase(h2)) {
return true;
}
// Have to resolve addresses before comparing, otherwise
// names like tachyon and tachyon.eng would compare different
final boolean result[] = {false};

java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
try {
InetAddress a1 = InetAddress.getByName(h1);
InetAddress a2 = InetAddress.getByName(h2);
result[0] = a1.equals(a2);
} catch(UnknownHostException e) {
} catch(SecurityException e) {
}
return null;
}
});

return result[0];
}

void Close() throws Exception
{
fClient.Close();
}

Socket GetSocket()
{
return fClient.GetSocket();
}
}

Sample Usage #1

import java.net.*;
public class MainTest
{

public static void main(String args[])
{
int i = 0;
try {
URL theURL = new URL((URL)null, "http://www.snowball.com", new HttpTimeoutHandler(150)); // timeout value in milliseconds

// the next step is optional
theURL.setURLStreamHandlerFactory(new HttpTimeoutFactory(150));


URLConnection theURLconn = theURL.openConnection();
theURLconn.connect();
i = theURLconn.getContentLength();
}
catch (InterruptedIOException e)
{
System.out.println("timeout on socket");
}
System.out.println("Done, Length:" + i);
}
}

Sample Usage #2

		try
{
HttpTimeoutHandler xHTH = new HttpTimeoutHandler(10); // timeout value in milliseconds
URL theURL = new URL((URL)null, "http://www.javasoft.com", xHTH);
HttpURLConnection theUC = theURL.openConnection();
.
.
.
}
catch (InterruptedIOException e)
{
// socket timed out

}

Some remarks: this code is thread safe.

More to come

來源:http://www.logicamente.com/sockets.html

???? http://www.edevs.com/java-programming/15068/


Thanks Felipe!

If I understand information at http://www.logicamente.com/sockets.html correctly there are 2 problems with timeout when using HttpURLConnection in JDK 1.3:

1. HttpURLConnection does not allow changing the default timeout that is in order of few minutes.

2. If actual HTTP stream is chunked then HttpURLConnection ignores even the default timeout and tries to read what it perceives as a continued stream resulting in indefinite read wait.

The patch shown at the above URL, consisting of subclassing of 4 system classes (1 from java.net... and 3 from sun.net.www...), is aimed to resolve problem 1 above but does not help in problem 2.

My main problem is to have timeout when reading chunked stream (system default timeout will be ok to beginning with) and therefore the question is if this bug has been corrected in later versions of JDK? Thanks.

-----

I have seen much chat about this "problem", that is setSoTimeout not available or not working properly.

how about you write your own Timer (resettable) or 1.4 has Timer class

you just reset it anytime you detect network activity and close the Socket if the Timer finishes its cycle?



leekiang 2010-04-14 17:09 發表評論
]]>
HttpURLConnection timeout solutionhttp://www.aygfsteel.com/leekiang/archive/2010/04/14/318274.htmlleekiangleekiangWed, 14 Apr 2010 09:04:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/04/14/318274.htmlhttp://www.aygfsteel.com/leekiang/comments/318274.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/04/14/318274.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/318274.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/318274.htmlFrom: Niels Campbell (niels_campbell_at_lycos.co.uk)
Date: 01/23/04
Date: 23 Jan 2004 09:14:16 -0800
After spending nearly 3 days on this problem to come up with a

solution I think it is only right to post the solution.

I found that you can't set the soTimeout on an HttpURLConnection as
the sockets are encapsulated within the HttpURLConnection
implementation.

I found Mike Reiche solution in which he uses a handler to set a
timeout value. This nearly worked. Looking at the code in the rt.jar I
found that the initial timeout was working, but the call
parseHTTP(...) in HttpClient was then attempting a second connection
which had a time out value of 0(infinite).

I modified the code to override the doConnect() in the NetworkClient
and managed to get a timeout occurring. To be exact two timeouts
occur.

It works on
java version "1.4.0_03"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_03-b04)
Java HotSpot(TM) Client VM (build 1.4.0_03-b04, mixed mode)
and
java version "1.2.2"
Classic VM (build JDK-1.2.2_013, native threads, symcjit)

Anyway here is the code, excuse the formatting.

/* HttpTimeoutURLConnection.java */
import java.net.*;
import java.io.*;
import sun.net.www.http.HttpClient;

// Need to override any function in HttpURLConnection that create a
new HttpClient
// and create a HttpTimeoutClient instead. Those functions are
// connect(), getNewClient(), getProxiedClient()

public class HttpTimeoutURLConnection extends
sun.net.www.protocol.http.HttpURLConnection
{

????public HttpTimeoutURLConnection(URL u, HttpTimeoutHandler handler,
int iSoTimeout)
????????throws IOException
????{
????????super(u, handler);
????????HttpTimeoutClient.setSoTimeout(iSoTimeout);
????}

????public void connect() throws IOException
????{
????????if (connected)
????????{
????????????return;
????????}

????????try
????????{
????????????if ("http".equals(url.getProtocol())) // && !failedOnce <-
PRIVATE
????????????{
????????????????// for safety's sake, as reported by KLGroup
????????????????synchronized (url)
????????????????{
????????????????????http = HttpTimeoutClient.getNew(url);
????????????????}
????????????}
????????????else
????????????{
????????????????if (handler instanceof HttpTimeoutHandler)
????????????????{
????????????????????http = new HttpTimeoutClient(super.url,
((HttpTimeoutHandler)handler).getProxy(),
((HttpTimeoutHandler)handler).getProxyPort());
????????????????}
????????????????else
????????????????{
????????????????????throw new IOException("HttpTimeoutHandler
expected");
????????????????}
????????????}

????????????ps = (PrintStream)http.getOutputStream();
????????}
????????catch (IOException e)
????????{
????????????throw e;
????????}

????????connected = true;
????}

????protected HttpClient getNewClient(URL url)
????????throws IOException
????{
????????HttpTimeoutClient httpTimeoutClient = new HttpTimeoutClient
(url, (String)null, -1);
????????return httpTimeoutClient;
????}

????protected HttpClient getProxiedClient(URL url, String s, int i)
????????throws IOException
????{
????????HttpTimeoutClient httpTimeoutClient = new HttpTimeoutClient
(url, s, i);
????????return httpTimeoutClient;
????}

}

/* HttpTimeoutHandler.java */
import java.net.*;
import java.io.IOException;

public class HttpTimeoutHandler extends
sun.net.www.protocol.http.Handler
{
????private int iSoTimeout=0;

????public HttpTimeoutHandler(int iSoTimeout)
????{
????????// Divide the time out by two because two connection attempts
are made
????????// in HttpClient.parseHTTP()

????????if (iSoTimeout%2!=0)
????????{
????????????iSoTimeout++;
????????}
????????this.iSoTimeout = (iSoTimeout/2);
????}

????protected java.net.URLConnection openConnection(URL u) throws
IOException
????{
????????return new HttpTimeoutURLConnection(u, this, iSoTimeout);
????}

????protected String getProxy()
????{
????????return proxy;
????}

????protected int getProxyPort()
????{
????????return proxyPort;
????}
}

/* HttpTimeoutFactory.java */
import java.net.*;

public class HttpTimeoutFactory implements URLStreamHandlerFactory
{
????private int iSoTimeout=0;

????public HttpTimeoutFactory(int iSoTimeout)
????{
????????this.iSoTimeout = iSoTimeout;
????}

????public URLStreamHandler createURLStreamHandler(String str)
????{
????????return new HttpTimeoutHandler(iSoTimeout);
????}
}

/* HttpTimeoutClient.java */
import sun.net.www.http.HttpClient;
import java.net.*;
import sun.net.*;
import sun.net.www.*;
import java.io.*;

public class HttpTimeoutClient extends HttpClient
{
????private static int iSoTimeout=0;

????public HttpTimeoutClient(URL url, String proxy, int proxyPort)
throws IOException
????{
????????super(url, proxy, proxyPort);
????}

????public HttpTimeoutClient(URL url) throws IOException
????{
????????super(url, null, -1);
????}

????public static HttpTimeoutClient getNew(URL url)
????????throws IOException
????{
????????HttpTimeoutClient httpTimeoutClient = (HttpTimeoutClient)
kac.get(url);

????????if (httpTimeoutClient == null)
????????{
????????????httpTimeoutClient = new HttpTimeoutClient (url); // CTOR
called openServer()
????????}
????????else
????????{
????????????httpTimeoutClient.url = url;
????????}

????????return httpTimeoutClient;
????}

????public static void setSoTimeout(int iNewSoTimeout)
????{
????????iSoTimeout=iNewSoTimeout;
????}

????public static int getSoTimeout()
????{
????????return iSoTimeout;
????}

????// Override doConnect in NetworkClient

????protected Socket doConnect(String s, int i)
????????throws IOException, UnknownHostException, SocketException
????{
????????Socket socket=super.doConnect(s,i);

????????// This is the important bit
????????socket.setSoTimeout(iSoTimeout);
????????return socket;
????}

}

/* Example use */
import java.util.*;
import java.io.*;
import java.net.*;

public class SystemProperty
{
????public static void main(String[] args)
????{
????????String sSoapUrl=" ????????System.out.println("Connecting to [" + sSoapUrl + "]");

????????URLConnection urlConnection = null;
????????URL url=null;

????????try
????????{
????????????url = new URL((URL)null, sSoapUrl, new
HttpTimeoutHandler(10000));
????????????urlConnection = url.openConnection();

????????????// Optional
????????????url.setURLStreamHandlerFactory(new
HttpTimeoutFactory(10000));

????????????System.out.println("Url class
["+urlConnection.getClass().getName()+"]");
????????}
????????catch (MalformedURLException mue)
????????{
????????????System.out.println(">>MalformedURLException<<");
????????????mue.printStackTrace();
????????}
????????catch (IOException ioe)
????????{
????????????System.out.println(">>IOException<<");
????????????ioe.printStackTrace();
????????}

????????HttpURLConnection httpConnection =
(HttpURLConnection)urlConnection;
????????System.out.println("Connected to [" + sSoapUrl + "]");

????????byte[] messageBytes=new byte[10000];
????????for (int i=0; i<10000; i++)
????????{
????????????messageBytes[i]=80;
????????}

????????try
????????{
????????????httpConnection.setRequestProperty("Connection", "Close");
????????????httpConnection.setRequestProperty("Content-Length",
String.valueOf(messageBytes.length));
????????????httpConnection.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
????????????httpConnection.setRequestMethod("POST");
????????????httpConnection.setDoOutput(true);
????????????httpConnection.setDoInput(true);
????????}
????????catch (ProtocolException pe)
????????{
????????????System.out.println(">>ProtocolException<<");
????????????pe.printStackTrace();
????????}

????????OutputStream outputStream=null;

????????try
????????{
????????????System.out.println("Getting output stream");
????????????outputStream =httpConnection.getOutputStream();
????????????System.out.println("Got output stream");

????????????outputStream.write(messageBytes);
????????}
????????catch (IOException ioe)
????????{
????????????System.out.println(">>IOException<<");
????????????ioe.printStackTrace();
????????}

????????try
????????{
????????????System.out.println("Getting input stream");
????????????InputStream is=httpConnection.getInputStream();
????????????System.out.println("Got input stream");

????????????byte[] buf = new byte[1000];
????????????int i;

????????????while((i = is.read(buf)) > 0)
????????????{
????????????????System.out.println(""+new String(buf));
????????????}
????????????is.close();
????????}
????????catch (Exception ie)
????????{
????????????ie.printStackTrace();
????????}

????}
}

Cheers,
Niels

來源:http://coding.derkeiler.com/Archive/Java/comp.lang.java.programmer/2004-01/3271.html
???? http://www.weblogicfans.net/viewthread.php?tid=1101
???? http://forums.sun.com/thread.jspa?threadID=568948
備注:在HttpTimeoutClient類中的第二個構造函數中的:super(url,null,-1)改為super(url, (String)null,-1)即可。


leekiang 2010-04-14 17:04 發表評論
]]>
HttpURLConnection設置網絡超時http://www.aygfsteel.com/leekiang/archive/2010/04/13/318185.htmlleekiangleekiangTue, 13 Apr 2010 11:00:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/04/13/318185.htmlhttp://www.aygfsteel.com/leekiang/comments/318185.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/04/13/318185.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/318185.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/318185.htmlHttpURLConnection對象不能直接構造,需要通過 URL.openConnection()來獲得HttpURLConnection對象,示例代碼如下:
String urlStr= www.ttt.org;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();

?

HttpURLConnection是基于HTTP協議的,其底層通過socket通信實 現。如果不設置超時(timeout),在網絡異常的情況下,可能會導致程序僵死而不繼續往下執行。可以通過以下兩個語句來設置相應的超時:
System.setProperty("sun.net.client.defaultConnectTimeout", 超時毫秒數字符串);
System.setProperty("sun.net.client.defaultReadTimeout", 超時毫秒數字符串);

其中: sun.net.client.defaultConnectTimeout:連接主機的超時時間(單位:毫秒)
sun.net.client.defaultReadTimeout: 從主機讀取數據的超時時間(單位:毫秒)

例如:
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");

JDK 1.5以前的版本,只能通過設置這兩個系統屬性來控制網絡超時。在1.5中,還可以使用HttpURLConnection的父類 URLConnection的以下兩個方法:
setConnectTimeout:設置連接主機超時(單位:毫秒)
setReadTimeout: 設置從主機讀取數據超時(單位:毫秒)

例如:
HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
urlCon.setConnectTimeout(30000);
urlCon.setReadTimeout(30000);

來源:http://www.xd-tech.com.cn/blog/article.asp?id=37

另外可參考java中處理http連接超時的方法

JDK中的URLConnection參數詳解

linux下設置connect連接超時的方法

java socket 用法(一)

Linux,可以修改/proc/sys/net/ipv4/tcp_syn_retries的值,缺省是72,大約5分鐘左右,改小點時間就短些



leekiang 2010-04-13 19:00 發表評論
]]>
java.io.CharConversionException: Not an ISO 8859-1 character: xxhttp://www.aygfsteel.com/leekiang/archive/2010/03/05/314552.htmlleekiangleekiangThu, 04 Mar 2010 17:43:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/03/05/314552.htmlhttp://www.aygfsteel.com/leekiang/comments/314552.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/03/05/314552.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/314552.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/314552.htmlServletOutputStream out = response.getOutputStream();
request.setAttribute("xmlTree", tree);
out.print(tree);

使用的編碼是GBK,在JDK1.5運行拋出異常:

java.io.CharConversionException: Not an ISO 8859-1 character: 樹

at javax.servlet.ServletOutputStream.print(ServletOutputStream.java:88)

問題可能出現在ServletOutputStream上,于是用PrintWriter替換了ServletOutputStream,運行正確,如:

PrintWriter pw = response.getWriter();
pw.print(tree);


參考:

http://hi.baidu.com/icewee/blog/item/24f28d24016f536934a80f11.html




leekiang 2010-03-05 01:43 發表評論
]]>
操作數組http://www.aygfsteel.com/leekiang/archive/2010/01/14/309489.htmlleekiangleekiangThu, 14 Jan 2010 10:43:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/01/14/309489.htmlhttp://www.aygfsteel.com/leekiang/comments/309489.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/01/14/309489.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/309489.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/309489.html??? List list = new ArrayList();
??? ??? list.add("1");
??? ??? list.add("2");
??? ??? int size = list.size();
??? ??? String[] arr = (String[]) list.toArray(new String[size]);
???? 必須帶參數new String[size],否則會報造型異常

2, 數組轉List
??? String[] arr = new String[] {"1", "2"};
??? List list = Arrays.asList(arr);

3,? Arrays.binarySearch(Object[] arr,Object key)
??? public static int binarySearch(int[]?a,int?key)使用二進制搜索算法來搜索指定的 int 型數組,以獲得指定的值。必須在進行此調用之前對數組進行排序(通過上面的 sort 方法)。如果沒有對數組進行排序,則結果是不明確的。如果數組包含多個帶有指定值的元素,則無法保證找到的是哪一個。
??? 也就是說必須先執行Arrays.sort,再執行Arrays.binarySearch

4, commons-lang的ArrayUtils
?? 1)ArrayUtils.contains()方法可以判定數組是否存在指完元素.比Arrays.binarySearch好用(見上文)
???? 當然有兩個比較實用的方法ArrayUtils.lastIndexOf()和ArrayUtils.indexOf()
?? 3)使用ArrayUtils.reverse(arr)方法可以反轉一個數組
?? 4)使用ArrayUtils.toObject(arr)和ArrayUtils.toPrimitive(arr)兩個方法,
???? 即可互相轉換基本類型數組和對象數組
?? 5)ArrayUtils.toString()方法可以輸入數組內容,此方法接受任意一個數組
???? 作為參數并輸出其內容,輸出時所有元素位于大括號,中間逗號隔開。
???? 如new String[] { "1","2","3","fd","3g"}會輸出為字符串"{1,2,3,fd,3g}"
?? 6)// 判斷數組是否為空(null和length=0的時候都為空)
????????ArrayUtils.isEmpty(new?int[0]);//?true
????????ArrayUtils.isEmpty(new?Object[]?{?null?});//?false
?? 7)
// 合并兩個數組
????????ArrayUtils.addAll(new?int[]?{?1,?3,?5?},?new?int[]?{?2,?4?});//?{1,3,5,2,4}
?? 8)// 刪除數組中某個對象(從正序開始搜索,刪除第一個) 注意只刪除一個
????????ArrayUtils.removeElement(new?int[]?{?1,?3,?5?},?3);//?{1,5}






leekiang 2010-01-14 18:43 發表評論
]]>
數學公式解析和計算http://www.aygfsteel.com/leekiang/archive/2010/01/06/308369.htmlleekiangleekiangTue, 05 Jan 2010 16:44:00 GMThttp://www.aygfsteel.com/leekiang/archive/2010/01/06/308369.htmlhttp://www.aygfsteel.com/leekiang/comments/308369.htmlhttp://www.aygfsteel.com/leekiang/archive/2010/01/06/308369.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/308369.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/308369.htmlhttp://www.singularsys.com/jep/
https://sourceforge.net/projects/jep/
http://rabbit8.bokee.com/3936531.html
http://suneca.com/article.asp?id=28

http://www.javaeye.com/topic/58422里辦法多

關于jexl
1,jexl1.1計算分母為0的表達式時,竟然算出來的值為0,被某人說沒有邏輯https://issues.apache.org/jira/browse/JEXL-45
2,jexl2解決了這個問題,但jexl2依賴jdk5
https://issues.apache.org/jira/browse/JEXL-58
handles ArithmeticException (divide by zero)
division by zero ignored only if JexlEngine.isSilent()
JexlEngine?jexl?=?new?JexlEngine();
jexl.setCache(
512);//有何用
jexl.setLenient(false);//什么意思
jexl.setSilent(false);

String?calculate?
=?"(G1?+?G2)/2";
Expression?e?
=jexl.createExpression(calculate);
//?populate?the?context
JexlContext?context?=?new?MapContext();
context.set(
"G1",?"3");
context.set(
"G2",?"5");
Object?res?
=?e.evaluate(context);//silent為false時evaluate方法會拋異常,為true不拋異常但res為null

??? ??? ???
另外,利用oracle計算,如果分母為0會報ORA-01476: divisor is equal to zero


leekiang 2010-01-06 00:44 發表評論
]]>
HttpURLConnection 的使用http://www.aygfsteel.com/leekiang/archive/2009/10/21/299193.htmlleekiangleekiangWed, 21 Oct 2009 06:12:00 GMThttp://www.aygfsteel.com/leekiang/archive/2009/10/21/299193.htmlhttp://www.aygfsteel.com/leekiang/comments/299193.htmlhttp://www.aygfsteel.com/leekiang/archive/2009/10/21/299193.html#Feedback0http://www.aygfsteel.com/leekiang/comments/commentRss/299193.htmlhttp://www.aygfsteel.com/leekiang/services/trackbacks/299193.html?? ??? ?System.setProperty("sun.net.client.defaultReadTime ", "3000");
?? ??? ?
?? ??? ?URL url1=null;
?? ??? ?try {
?? ??? ??? ?url1 = new URL(url);
?? ??? ??? ?HttpURLConnection urlCon = (HttpURLConnection)url1.openConnection();
?? ??? ??? ?System.out.println(urlCon);
?? ??? ??? ? BufferedReader in = null;
?? ??? ???????? try {
?? ??? ?????????? in = new BufferedReader(
?? ??? ???????????? new InputStreamReader(
?? ??? ??????????? ??? ??? ?urlCon.getInputStream()));
?? ??? ?????????? String inputLine;
?? ??? ?????????? while (
?? ??? ???????????? (inputLine = in.readLine()) != null) {
?? ??? ???????????? System.out.println(inputLine);
?? ??? ?????????? }
?? ??? ???????? } catch (IOException e) {
?? ??? ?????????? e.printStackTrace();
?? ??? ???????? }
?? ??? ???????? in.close();
?? ??? ???????? urlCon.disconnect();
?? ??? ?} catch (Exception e1) {
?? ??? ??? ?e1.printStackTrace();
?? ??? ?}

http://tech.techweb.com.cn/archiver/tid-225522.html
http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/HttpURLConnection.html
http://zhuixue.javaeye.com/blog/385793


leekiang 2009-10-21 14:12 發表評論
]]>
主站蜘蛛池模板: 龙胜| 阳东县| 玉林市| 南昌县| 望江县| 灌南县| 隆化县| 来宾市| 鸡东县| 布拖县| 彩票| 阜宁县| 天水市| 广德县| 浏阳市| 石嘴山市| 济南市| 双流县| 元谋县| 陆川县| 巴东县| 常山县| 铜山县| 泰州市| 高碑店市| 阿勒泰市| 内丘县| 沾益县| 聂荣县| 宾阳县| 集贤县| 武胜县| 安庆市| 北川| 祁东县| 运城市| 鲁山县| 遵义县| 大宁县| 休宁县| 仁寿县|