posts - 51, comments - 17, trackbacks - 0, articles - 9
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          2007年6月27日

          引子 Web 2.0,在過去的一年里也許還是一個新的名詞,曾幾何時它像網上核武一樣爆發了,并以不可阻擋之勢燃燒了整個互聯網,其熱度不壓于當年的超女,又曾幾何時它悄悄地走進了我們的生活,從陌生走向了熟悉,從概念走向了應用。今天,Web 2.0構成了我們網絡生活不可缺少的一部分,今天,你Web 2.0了嗎?

          什么是Web2.0?
          如果你是一只老網蟲但還不知道什么是Web2.0,趕緊去跳海吧,不怕死的就去跳(記得帶個救生圈,出事了我不負責哈!),怕死的還不趕緊補補課,免得被人看穿了讓人笑話。如果你是個善于表現自己的人,多學點東西吧,學了Web 2.0你可以不分對象地大談特談地講述你的Web 2.0觀點, 嘿嘿,想象一下別人對你崇拜的表情吧。

          Web2.0是以 Flickr、Craigslist、Linkedin、Tribes、Ryze、 Friendster、Del.icio.us、43Things.com等網站為代表,以Blog、TAG、SNS、RSS、wiki等應用為核心,依據六度分隔、xml、ajax等新理論和技術實現的互聯網新一代模式。

           1. 什么是Wiki

            WIKI的來源

            WIKI概念的發明人是Ward Cunningham,該詞來源于夏威夷語的“wee kee wee kee”,原本是“快點快點” (quick)的意思。

            Wiki--一種多人協作的寫作工具。Wiki站點可以有多人(甚至任何訪問者)維護,每個人都可以發表自己的意見,或者對共同的主題進行擴展或者探討。

            Wiki指一種超文本系統。這種超文本系統支持面向社群的協作式寫作,同時也包括一組支持這種寫作的輔助工具。有人認為,Wiki系統屬于一種人類知識網格系統,我們可以在Web的基礎上對Wiki文本進行瀏覽、創建、更改,而且創建、更改、發布的代價遠比HTML文本小;同時Wiki系統還支持面向社群的協作式寫作,為協作式寫作提供必要幫助;最后,Wiki的寫作者自然構成了一個社群,Wiki系統為這個社群提供簡單的交流工具。與其它超文本系統相比,Wiki有使用方便及開放的特點,所以Wiki系統可以幫助我們在一個社群內共享某領域的知識。

                WIKI可以做什么

            WIKI最適合做百科全書、知識庫、整理某一個領域的知識等知識型站點,幾個分在不同地區的人利用wiki協同工作共同寫一本書等等。Wiki技術已經被較好的用在百科全書、手冊/FAQ編寫、專題知識庫方面。

            Wiki的特點

            使用方便

            維護快捷:快速創建、存取、更改超文本頁面(這也是為什幺叫作“wiki wiki”的原因)。

            格式簡單:用簡單的格式標記來取代 HTML 的復雜格式標記。(類似所見即所得的風格)

            鏈接方便:通過簡單標記,直接以關鍵字名來建立鏈接(頁面、外部連接、圖像等)。

            命名平易:關鍵字名就是頁面名稱,并且被置于一個單層、平直的名空間中。

            有組織

            自組織的:同頁面的內容一樣,整個超文本的組織結構也是可以修改、演化的。

            可匯聚的:系統內多個內容重復的頁面可以被匯聚于其中的某個,相應的鏈接結構也隨之改變。

            可增長

            可增長:頁面的鏈接目標可以尚未存在,通過點擊鏈接,我們可以創建這些頁面,從而使系統得到增長。

            修訂歷史:記錄頁面的修訂歷史,頁面的各個版本都可以被獲取。

            開放性

            開放的:社群的成員可以任意創建、修改、刪除頁面。

            可觀察:系統內頁面的變動可以被訪問者觀察到。

          2.

            什么是RSS

            RSS是站點用來和其他站點之間共享內容的一種簡易方式(也叫聚合內容)的技術。最初源自瀏覽器“新聞頻道”的技術,現在通常被用于新聞和其他按順序排列的網站,例如Blog。

            RSS可以干什么?

            1、訂閱BLOG(BLOG上,你可以訂閱你工作中所需的技術文章;也可以訂閱與你有共同愛好的作者的日志,總之,BLOG上你對什么感興趣你就可以訂什么)

            2、訂閱新聞(無論是奇聞怪事、明星消息、體壇風云,只要你想知道的,都可以訂閱)

            如何使用RSS

            ·下載和安裝一個RSS新聞閱讀器

            ·從網站提供的聚合新聞目錄列表中訂閱您感興趣的新聞欄目的內容

            ·訂閱后您將會及時獲得所訂閱新聞頻道的最新內容

            RSS的幾個縮寫來源

            1、Really Simple Syndication(真正簡易的聚合)

            2、Rich Site Summary(豐富的站點摘要)

            3、RDF Site Summary(RDF站點摘要)

            RSS新聞特點

            對網民而言:對網站而言:

            1.沒有廣告或者圖片來影響標題或者文章概要的閱讀。

            2.RSS閱讀器自動更新你定制的網站內容,保持新聞的及時性。

            3.用戶可以加入多個定制的RSS提要,從多個來源搜集新聞整合到單個數據流中。 1.擴大了網站內容的傳播面,也增加了網站訪問量,因為訪問者調閱的RSS文件和瀏覽的網頁,都是從網站服務器上下載的。

            2.RSS文件的網址是固定不變的,網站可以隨時改變其中的內容。RSS內容一旦更新,瀏覽者看到的內容也隨即更新了


          3.什么是Tag?

            Tag(標簽)是一種更為靈活、有趣的分類方式,您可以為每篇日志、每個帖子或者每張圖片等添加一個或多個Tag(標簽),你可以看到網站上所有和您使用了相同Tag的內容,由此和他人產生更多的聯系。Tag體現了群體的力量,使得內容之間的相關性和用戶之間的交互性大大增強。

            比如,你在一篇日志上添加了“讀書”和“Tag”兩個標簽,就能通過這兩個tag看到和你有相同興趣的其他日志。同樣,如果你給自己的網絡書簽貼上不同標簽,那么,在下一次去尋找時,會輕易找到自己想要的信息。

            那么,如果我貼了Tag,能產生什么效果呢?首先,信息將會條理化。其次,當你積累了一定數量的Tag之后,你會發現自己最關心的話題。GOOGLE的"我的搜索歷史"功能就是采用了標簽,你的每次搜索關鍵詞都可以成為tag,之后,你會了解自己這一天在關心什么。

            當然,你也可以看到有哪些人和自己使用了一樣的Tag(標簽),進而找到和您志趣相投的人。

            2、Tag究竟有哪些不同?

            Tag不是關鍵詞,因為,一個機器就沒有辦法提取一張照片的關鍵字,但人可以給它設定一個或多個Tag。而Tag真正不同的地方在于,你可以隨意用任何詞來標記一件事物,只要方便你找到它。因此,這一標志是活躍的、無序的、個人化、相當自我的一種標記方式。

            當我可以為我自己的言論作出自己想要的標志,而不是別人給予我的分類,那么,我將說些什么呢?我又會通過這種標志找到什么樣的人什么樣的文章、圖片呢?Tag創造了一個新的無序但充滿生機的網絡聯合體,通過這個聯合,人們找到和自己最接近的內容。

            3、如何使用Tag?

            現在很多網站都使用了Tag模式,只要使用者自身打開了界限,隨心所欲地給自己注釋標簽,不被舊有思維局限住,就對了。簡單地說,Tag是一種隨心所欲的標簽,當我讀一篇文章或者看一張圖片的時候想什么就寫什么,不受原有分類的束縛,怎么想就怎么使用。

          posted @ 2007-08-07 20:46 chenweicai 閱讀(282) | 評論 (0)編輯 收藏

          Abraham Lincoln

          Delivered on the 19th Day of November, 1863

          Cemetery Hill, Gettysburg, Pennsylvania

          Fourscore and seven years ago, our fathers brought forth upon this continent a new Nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now, we are engaged in a great Civil War,testing whether that Nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war. We have come to dedicate a portion of that field as a final resting-place for those who gave their lives that Nation might live. It is altogether fitting and proper that we should do this.

          But, in a larger sense, we cannot dedicate, we cannot consecrate, we cannot hallow this ground. The brave men, living and dead, who struggled here, have consecrated it far above our power to add or detract. The world will little note nor long remember what we say here, but it can never forget what they did here. It is for us, the living, rather to be dedicated to the great task remaining before us; that from these honored dead, we take increased devotion to that cause for which they gave the last full measure of devotion; that this Nation, under GOD, shall have a new birth of freedom; and that government of the People by the People and for the People shall not perish from the earth.

          葛底斯堡演說

          亞伯拉罕·林肯,1963年11月19日

          87年前,我們的先輩們在這個大陸上創立了一個新國家,它孕育于自由之中,奉行一切人生來平等的原則?,F在我們正從事一場偉大的內戰,以考驗這個國家,或者任何一個孕育于自由和奉行上述原則的國家是否能夠長久存在下去。我們在這場戰爭中的一個偉大戰場上集會。烈士們為使這個國家能夠生存下去而獻出了自己的生命,我們來到這里,是要把這個戰場的一部分奉獻給他們作為最后安息之所。我們這樣做是完全應該而且是非常恰當的。

          但是,從更廣泛的意義上來說,這塊土地我們不能夠奉獻,不能夠圣化,不能夠神化。那些曾在這里戰斗過的勇士們,活著的和去世的,已經把這塊土地圣化了,這遠不是我們微薄的力量所能增減的。我們今天在這里所說的話,全世界不大會注意,也不會長久地記住,但勇士們在這里所做過的事,全世界卻永遠不會忘記。毋寧說,倒是我們這些還活著的人,應該在這里把自己奉獻于勇士們已經如此崇高地向前推進但尚未完成的事業。倒是我們應該在這里把自己奉獻于仍然留在我們面前的偉大任務??我們要從這些光榮的死者身上汲取更多的獻身精神,來完成他們已經完全徹底為之獻身的事業;我們要在這里下定最大的決心,不讓這些死者白白犧牲;我們要使國家在上帝福佑下得到自由的新生,要使這個民有、民治、民享的政府永世長存。

          posted @ 2007-06-30 11:23 chenweicai 閱讀(302) | 評論 (0)編輯 收藏

          Inaugural Address of John F. Kennedy  肯尼迪總統就職演說
          January 20, 1961

          Vice President Johnson, Mr. Speaker, Mr. Chief Justice, President Eisenhower, Vice President Nixon, President Truman, Reverend Clergy, fellow citizens:

          We observe today not a victory of party but a celebration of freedom, symbolizing an end as well as a beginning, signifying renewal as well as change. For I have sworn before you and Almighty God the same solemn oath our forebears prescribed nearly a century and three-quarters ago.

          我們今天所看到的,并非是某一黨派的勝利,而是自由的慶典。它象征著結束,亦象征著開始;意味著更新,亦意味著變化。因為我已在你們及萬能的上帝面前,依著我們先輩175年前寫下的誓言宣誓。

          The world is very different now. For man holds in his mortal hands the power to abolish all forms of human poverty and all forms of human life. And yet the same revolutionary beliefs for which our forebears fought are still at issue around the globe -- the belief that the rights of man come not from the generosity of the state but from the hand of God.

          世界已然今非昔比,因為人類手中已經掌握了巨大的力量,既可以用來消除各種形式的貧困,亦可用以毀滅人類社會。然而,我們先輩曾為之戰斗的那些革命性的信念還依然在世界上受人爭議——那就是,每個人享有的各項權利決非來自國家政權的慷慨賜予,而是出自上帝之手。

          We dare not forget today that we are the heirs of that first revolution. Let the word go forth from this time and place, to friend and foe alike, that the torch has been passed to a new generation of Americans -- born in this century, tempered by war, disciplined by a hard and bitter peace, proud of our ancient heritage -- and unwilling to witness or permit the slow undoing of those human rights to which this nation has always been committed, and to which we are committed today at home and around the world.

          今天,我們不敢有忘,我們乃是那第一次革命的后裔。此時,讓這個聲音從這里同時向我們的朋友和敵人傳達:火炬現已傳遞到新一代美國人手中——他們生于本世紀,既經受過戰火的錘煉,又經歷過艱難嚴峻的和平歲月的考驗。他們深為我們古老的遺產所自豪——決不愿目睹或聽任諸項人權受到無形的侵蝕,這些權利不僅為這個國家始終信守不渝,亦是我們正在國內和世界上誓死捍衛的東西。

          Let every nation know, whether it wishes us well or ill, that we shall pay any price, bear any burden, meet any hardship, support any friend, oppose any foe to assure the survival and the success of liberty.

          讓每一個國家都知道,無論它們對我們抱有善意還是惡意,我們都準備付出任何代價、承受任何重任、迎戰任何艱險、支持任何朋友、反對任何敵人,以使自由得以維系和勝利。

          This much we pledge -- and more.

          這是我們矢志不移的承諾,且遠不止此!

          To those old allies whose cultural and spiritual origins we share, we pledge the loyalty of faithful friends. United there is little we cannot do in a host of cooperative ventures. Divided there is little we can do, for we dare not meet a powerful challenge at odds and split asunder.

          對于那些與我們共享同一文化和精神源頭的老朋友,我們許以朋友的忠誠。在許許多多的合作事業中,我們會盡己所能以促進我們的團結,而決不故意制造分裂,因為我們不敢輕易面對由分歧或體系崩潰而導致的巨大挑戰。

          To those new states whom we welcome to the ranks of the free, we pledge our word that one form of colonial control shall not have passed away merely to be replaced by a far more iron tyranny. We shall not always expect to find them supporting our view. But we shall always hope to find them strongly supporting their own freedom -- and to remember that, in the past, those who foolishly sought power by riding the back of the tiger ended up inside.

          對于那些新成立的國家,我們歡迎它們加入自由陣營,并在此許以忠告:某種形式的殖民控制決不會僅僅因為被另一種更為殘酷的霸權所取代就消聲匿跡。我們不會期待他們始終支持我們的觀點,但我們希望他們能始終堅定地維護他們自己的自由——并且牢記,在過去,那些愚蠢地騎上獨~裁的虎背以謀求權力的人最終都以葬身虎腹而告終。

          To those people in the huts and villages of half the globe struggling to break the bonds of mass misery, we pledge our best efforts to help them help themselves, for whatever period is required -- not because the communists may be doing it, not because we seek their votes, but because it is right.

          對于那些寄居于大半個地球上的草舍村落、為著掙脫無盡苦難的枷鎖而奮斗的人民,我們承諾將盡我們最大的努力,以使他們獲得自助的能力。因為這是時代對我們提出的要求——不是因為共~產~黨人可能如此行事、不是因為我們需要他們的選票,僅僅是因為這樣做是正當的。

          If a free society cannot help the many who are poor, it cannot save the few who are rich.

          如果一個自由的社會不能幫助貧窮的多數,它就不能拯救那富裕的少數。

          To our sister republics south of our border, we offer a special pledge: to convert our good words into good deeds, in a new alliance for progress, to assist free men and free governments in casting off the chains of poverty. But this peaceful revolution of hope cannot become the prey of hostile powers. Let all our neighbors know that we shall join with them to oppose aggression or subversion anywhere in the Americas.

          對于我們的南部鄰邦共和國,我們許以特殊的承諾:將我們的良言轉為善行,在為了進步而結成的新盟邦里,幫助自由的人民和自由的政府擺脫貧困。但這一希翼中的和平革命不能成為敵對勢力的犧牲品,讓我們所有的鄰邦都知道,我們將與他們一道,反對發生在美洲任何地區的侵略和顛覆。

          And let every other power know that this hemisphere intends to remain the master of its own house.

          讓所有其他勢力都知道,這一半球的人民致力于維護他們作為自己家園主人的地位。

          To that world assembly of sovereign states, the United Nations, our last best hope in an age where the instruments of war have far outpaced the instruments of peace, we renew our pledge of support -- to prevent it from becoming merely a forum for invective, to strengthen its shield of the new and the weak, and to enlarge the area in which its writ may run.

          對于那個主權國家的世界性會議組織——聯合國,我們最后一次良好祝愿是發生在戰爭機器遠遠超過和平機器的時代。為了防止它淪為僅僅用來謾罵攻訐的論壇,為了加強它對新成立國家及弱小國家的保障功能、為了擴展其權力涵蓋的領域,我們現在重申對它的支持承諾。

          Finally, to those nations who would make themselves our adversary, we offer not a pledge but a request: that both sides begin anew the quest for peace -- before the dark powers of destruction unleashed by science engulf all humanity in planned or accidental self-destruction.

          最后,對于那些主動站到我們敵對面的國家,我們提出的不是許諾,而是懇求:在被科學釋放出的、黑暗的破壞力量以有計劃的或偶然性的自我毀滅方式吞噬全人類之前,懇求雙方再一次地開始謀求和平的努力。

          We dare not tempt them with weakness. For only when our arms are sufficient beyond doubt can we be certain beyond doubt that they will never be employed. But neither can two great and powerful groups of nations take comfort from our present course -- both sides overburdened by the cost of modern weapons, both rightly alarmed by the steady spread of the deadly atom, yet both racing to alter that uncertain balance of terror that stays the hand of mankind's final war. So let us begin anew -- remembering on both sides that civility is not a sign of weakness, and sincerity is always subject to proof.

          我們不敢以軟弱誘惑它們,因為只有當我們的軍備充足到確切無疑的程度時,我們才能確切無疑地肯定它們永遠不會被投入使用。但這兩個強大的國家集團都無法從彼此當前的做法中得到安慰——雙方都背負了過高的現代武器系統的成本、雙方都理所當然地對致死性原子武器的持續擴散感到驚恐不安,但雙方都競相改變不確定的恐怖均衡,這種均衡恰恰抑制了人類最后攤牌的沖動。

          Let us never negotiate out of fear. But let us never fear to negotiate.

          讓我們永遠不要因為懼怕而談判,讓我們永遠不要懼怕談判。

          Let both sides explore what problems unite us instead of belaboring those problems which divide us.

          讓雙方探尋那些能將我們團結在一起的因素,而不是那些刻意挑出那些分裂我們的因素。

          Let both sides, for the first time, formulate serious and precise proposals for the inspection and control of arms, and bring the absolute power to destroy other nations under the absolute control of all nations.

          讓雙方首先提出認真細致的方案來核查及控制軍備,并將毀滅其他國家的絕對力量置于所有國家的絕對控制之下。

          Let both sides seek to invoke the wonders of science instead of its terrors. Together let us explore the stars, conquer the deserts, eradicate disease, tap the ocean depths, and encourage the arts and commerce.

          讓雙方努力去激發科學的奇跡,而非科學的恐怖。讓我們一同探索星空、征服沙漠、消除疾病、開發海洋深處,鼓勵藝術和商業。

          Let both sides unite to heed, in all corners of the earth, the command of Isaiah -- to "undo the heavy burdens... [and] let the oppressed go free."

          讓雙方在世界每一個角落,都共同信守《圣經.以賽亞書》中的教誨——“卸下重負……讓被壓迫者自由。”

          And if a beachhead of cooperation may push back the jungle of suspicion, let both sides join in creating a new endeavor -- not a new balance of power, but a new world of law -- where the strong are just, and the weak secure, and the peace preserved.

          如果合作的灘頭堡能夠遏制重重猜疑,讓雙方攜手進行新的努力——不是為了建立新的勢力均衡,而是為了建立新的規則體系——以使強者正義,弱者安全,和平維系。

          All this will not be finished in the first one hundred days. Nor will it be finished in the first one thousand days; nor in the life of this Administration; nor even perhaps in our lifetime on this planet. But let us begin.

          所有這些工作將不會在從現在起的一百天、一千天內完成,也不會在本屆行政分支任期內完成,甚至可能不會在我們的有生之年完成,但是,請讓我們現在開始工作。

          In your hands, my fellow citizens, more than mine, will rest the final success or failure of our course. Since this country was founded, each generation of Americans has been summoned to give testimony to its national loyalty. The graves of young Americans who answered the call to service surround the globe.

          我的同胞們,我們事業的最終成敗將掌握在你們的手中而不僅僅是我的手中。從這個國家被創建那天起,每一代美國人都被召喚去證實自己對國家的忠誠。那些響應號召獻身國家的年輕美國人的安息之所遍布全球。

          Now the trumpet summons us again -- not as a call to bear arms, though arms we need -- not as a call to battle, though embattled we are -- but a call to bear the burden of a long twilight struggle, year in and year out, rejoicing in hope, patient in tribulation, a struggle against the common enemies of man: tyranny, poverty, disease, and war itself.

          現在,召喚的號角又一次吹響——不是號召我們扛起武器,雖然武器是我們所需要的——也不是號召我們去參加戰斗,雖然我們準備戰斗——而是號召我們年復一年地去進行一場漫長而未分勝負的搏斗,在希望中歡樂,而患難中忍耐,以反對人類共同的敵人:暴政、貧困、疾病以及戰爭本身。

          Can we forge against these enemies a grand and global alliance, North and South, East and West, that can assure a more fruitful life for all mankind? Will you join in that historic effort?

          為了反對這些敵人,我們能夠將南方與北方、東方與西方團結起來,熔鑄成一個偉大的和全球性的聯盟,以確保全人類得享更為成果累累的生活嗎?你們愿意參與這項歷史性的努力嗎?

          In the long history of the world, only a few generations have been granted the role of defending freedom in its hour of maximum danger. I do not shrink from this responsibility -- I welcome it. I do not believe that any of us would exchange places with any other people or any other generation. The energy, the faith, the devotion which we bring to this endeavor will light our country and all who serve it. And the glow from that fire can truly light the world.

          在世界歷史的長河里,只有少數幾代人被賦予了在自由面臨最大危機時捍衛自由的使命,我不會畏縮于這一責任——我歡迎它!我也不相信我們中的任何人會愿意與其他國家的人民或其他世代的人民易地而處。我們在這場努力中所傾注的精力、信念和奉獻將照耀我們的國家以及所有為之獻身的人,火焰所放射出的光芒必將普照全世界。

          And so, my fellow Americans, ask not what your country can do for you; ask what you can do for your country.

          所以,我的美國同胞們,不要問你的國家為你做了什么,而應問你能為你的國家做些什么。

          My fellow citizens of the world, ask not what America will do for you, but what together we can do for the freedom of man.

          我的世界同胞們,不要問美國將為你做些什么,而應問我們應該一起為了全人類的自由做些什么。

          Finally, whether you are citizens of America or citizens of the world, ask of us here the same high standards of strength and sacrifice which we ask of you. With a good conscience our only sure reward, with history the final judge of our deeds, let us go forth to lead the land we love, asking His blessing and His help, but knowing that here on earth God's work must truly be our own.

          最后,無論是美國公民還是世界其他國家的公民,請用我們要求于你們的關于力量和犧牲的高標準來要求我們,本著我們唯一可以指望有所回報的善意良知,依著能最終裁決我們功業的歷史,讓我們著手領導我們所熱愛的國家,在祈求神的賜福和神的幫助的同時,也能深切體認,在這片土地上,神的工作必定也是我們自己所應承擔的使命。

          posted @ 2007-06-30 11:18 chenweicai 閱讀(612) | 評論 (0)編輯 收藏

          摘要:

          雖然session機制在web應用程序中被采用已經很長時間了,但是仍然有很多人不清楚session機制的本質,以至不能正確的應用這一技術。本文將詳細討論session的工作機制并且對在Java web application中應用session機制時常見的問題作出解答。
           
          一、術語session
          在我的經驗里,session這個詞被濫用的程度大概僅次于transaction,更加有趣的是transaction與session在某些語境下的含義是相同的。

          session,中文經常翻譯為會話,其本來的含義是指有始有終的一系列動作/消息,比如打電話時從拿起電話撥號到掛斷電話這中間的一系列過程可以稱之為一個 session。有時候我們可以看到這樣的話“在一個瀏覽器會話期間,...”,這里的會話一詞用的就是其本義,是指從一個瀏覽器窗口打開到關閉這個期間 ①。最混亂的是“用戶(客戶端)在一次會話期間”這樣一句話,它可能指用戶的一系列動作(一般情況下是同某個具體目的相關的一系列動作,比如從登錄到選購商品到結賬登出這樣一個網上購物的過程,有時候也被稱為一個transaction),然而有時候也可能僅僅是指一次連接,也有可能是指含義①,其中的差別只能靠上下文來推斷②。

          然而當session一詞與網絡協議相關聯時,它又往往隱含了“面向連接”和/或“保持狀態”這樣兩個含義, “面向連接”指的是在通信雙方在通信之前要先建立一個通信的渠道,比如打電話,直到對方接了電話通信才能開始,與此相對的是寫信,在你把信發出去的時候你并不能確認對方的地址是否正確,通信渠道不一定能建立,但對發信人來說,通信已經開始了。“保持狀態”則是指通信的一方能夠把一系列的消息關聯起來,使得消息之間可以互相依賴,比如一個服務員能夠認出再次光臨的老顧客并且記得上次這個顧客還欠店里一塊錢。這一類的例子有“一個TCP session”或者 “一個POP3 session”③。

          而到了web服務器蓬勃發展的時代,session在web開發語境下的語義又有了新的擴展,它的含義是指一類用來在客戶端與服務器之間保持狀態的解決方案④。有時候session也用來指這種解決方案的存儲結構,如“把xxx保存在session 里”⑤。由于各種用于web開發的語言在一定程度上都提供了對這種解決方案的支持,所以在某種特定語言的語境下,session也被用來指代該語言的解決方案,比如經常把Java里提供的javax.servlet.http.HttpSession簡稱為session⑥。

          鑒于這種混亂已不可改變,本文中session一詞的運用也會根據上下文有不同的含義,請大家注意分辨。
          在本文中,使用中文“瀏覽器會話期間”來表達含義①,使用“session機制”來表達含義④,使用“session”表達含義⑤,使用具體的“HttpSession”來表達含義⑥

          二、HTTP協議與狀態保持
          HTTP 協議本身是無狀態的,這與HTTP協議本來的目的是相符的,客戶端只需要簡單的向服務器請求下載某些文件,無論是客戶端還是服務器都沒有必要紀錄彼此過去的行為,每一次請求之間都是獨立的,好比一個顧客和一個自動售貨機或者一個普通的(非會員制)大賣場之間的關系一樣。

          然而聰明(或者貪心?)的人們很快發現如果能夠提供一些按需生成的動態信息會使web變得更加有用,就像給有線電視加上點播功能一樣。這種需求一方面迫使HTML逐步添加了表單、腳本、DOM等客戶端行為,另一方面在服務器端則出現了CGI規范以響應客戶端的動態請求,作為傳輸載體的HTTP協議也添加了文件上載、 cookie這些特性。其中cookie的作用就是為了解決HTTP協議無狀態的缺陷所作出的努力。至于后來出現的session機制則是又一種在客戶端與服務器之間保持狀態的解決方案。

          讓我們用幾個例子來描述一下cookie和session機制之間的區別與聯系。筆者曾經常去的一家咖啡店有喝5杯咖啡免費贈一杯咖啡的優惠,然而一次性消費5杯咖啡的機會微乎其微,這時就需要某種方式來紀錄某位顧客的消費數量。想象一下其實也無外乎下面的幾種方案:
          1、該店的店員很厲害,能記住每位顧客的消費數量,只要顧客一走進咖啡店,店員就知道該怎么對待了。這種做法就是協議本身支持狀態。
          2、發給顧客一張卡片,上面記錄著消費的數量,一般還有個有效期限。每次消費時,如果顧客出示這張卡片,則此次消費就會與以前或以后的消費相聯系起來。這種做法就是在客戶端保持狀態。
          3、發給顧客一張會員卡,除了卡號之外什么信息也不紀錄,每次消費時,如果顧客出示該卡片,則店員在店里的紀錄本上找到這個卡號對應的紀錄添加一些消費信息。這種做法就是在服務器端保持狀態。

          由于HTTP協議是無狀態的,而出于種種考慮也不希望使之成為有狀態的,因此,后面兩種方案就成為現實的選擇。具體來說cookie機制采用的是在客戶端保持狀態的方案,而session機制采用的是在服務器端保持狀態的方案。同時我們也看到,由于采用服務器端保持狀態的方案在客戶端也需要保存一個標識,所以session機制可能需要借助于cookie機制來達到保存標識的目的,但實際上它還有其他選擇。

          三、理解cookie機制
          cookie機制的基本原理就如上面的例子一樣簡單,但是還有幾個問題需要解決:“會員卡”如何分發;“會員卡”的內容;以及客戶如何使用“會員卡”。

          正統的cookie分發是通過擴展HTTP協議來實現的,服務器通過在HTTP的響應頭中加上一行特殊的指示以提示瀏覽器按照指示生成相應的cookie。然而純粹的客戶端腳本如JavaScript或者VBScript也可以生成cookie。

          而cookie 的使用是由瀏覽器按照一定的原則在后臺自動發送給服務器的。瀏覽器檢查所有存儲的cookie,如果某個cookie所聲明的作用范圍大于等于將要請求的資源所在的位置,則把該cookie附在請求資源的HTTP請求頭上發送給服務器。意思是麥當勞的會員卡只能在麥當勞的店里出示,如果某家分店還發行了自己的會員卡,那么進這家店的時候除了要出示麥當勞的會員卡,還要出示這家店的會員卡。

          cookie的內容主要包括:名字,值,過期時間,路徑和域。
          其中域可以指定某一個域比如.google.com,相當于總店招牌,比如寶潔公司,也可以指定一個域下的具體某臺機器比如www.google.com或者froogle.google.com,可以用飄柔來做比。
          路徑就是跟在域名后面的URL路徑,比如/或者/foo等等,可以用某飄柔專柜做比。
          路徑與域合在一起就構成了cookie的作用范圍。
          如果不設置過期時間,則表示這個cookie的生命期為瀏覽器會話期間,只要關閉瀏覽器窗口,cookie就消失了。這種生命期為瀏覽器會話期的 cookie被稱為會話cookie。會話cookie一般不存儲在硬盤上而是保存在內存里,當然這種行為并不是規范規定的。如果設置了過期時間,瀏覽器就會把cookie保存到硬盤上,關閉后再次打開瀏覽器,這些cookie仍然有效直到超過設定的過期時間。

          存儲在硬盤上的cookie 可以在不同的瀏覽器進程間共享,比如兩個IE窗口。而對于保存在內存里的cookie,不同的瀏覽器有不同的處理方式。對于IE,在一個打開的窗口上按 Ctrl-N(或者從文件菜單)打開的窗口可以與原窗口共享,而使用其他方式新開的IE進程則不能共享已經打開的窗口的內存cookie;對于 Mozilla Firefox0.8,所有的進程和標簽頁都可以共享同樣的cookie。一般來說是用javascript的window.open打開的窗口會與原窗口共享內存cookie。瀏覽器對于會話cookie的這種只認cookie不認人的處理方式經常給采用session機制的web應用程序開發者造成很大的困擾。

          下面就是一個goolge設置cookie的響應頭的例子
          HTTP/1.1 302 Found
          Location: http://www.google.com/intl/zh-CN/
          Set-Cookie: PREF=ID=0565f77e132de138:NW=1:TM=1098082649:LM=1098082649:S=KaeaCFPo49RiA_d8; expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com
          Content-Type: text/html


          image
          這是使用HTTPLook這個HTTP Sniffer軟件來俘獲的HTTP通訊紀錄的一部分

          image
          瀏覽器在再次訪問goolge的資源時自動向外發送cookie

          image
          用Firefox可以很容易的觀察現有的cookie的值
          使用HTTPLook配合Firefox可以很容易的理解cookie的工作原理。

          image
          IE也可以設置在接受cookie前詢問

          四、理解session機制

          session機制是一種服務器端的機制,服務器使用一種類似于散列表的結構(也可能就是使用散列表)來保存信息。

          當程序需要為某個客戶端的請求創建一個session的時候,服務器首先檢查這個客戶端的請求里是否已包含了一個session標識 - 稱為 session id,如果已包含一個session id則說明以前已經為此客戶端創建過session,服務器就按照session id把這個 session檢索出來使用(如果檢索不到,可能會新建一個),如果客戶端請求不包含session id,則為此客戶端創建一個session并且生成一個與此session相關聯的session id,session id的值應該是一個既不會重復,又不容易被找到規律以仿造的字符串,這個 session id將被在本次響應中返回給客戶端保存。

          保存這個session id的方式可以采用cookie,這樣在交互過程中瀏覽器可以自動的按照規則把這個標識發揮給服務器。一般這個cookie的名字都是類似于SEEESIONID,而。比如weblogic對于web應用程序生成的cookie,JSESSIONID= ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764,它的名字就是 JSESSIONID。

          由于cookie可以被人為的禁止,必須有其他機制以便在cookie被禁止時仍然能夠把session id傳遞回服務器。經常被使用的一種技術叫做URL重寫,就是把session id直接附加在URL路徑的后面,附加方式也有兩種,一種是作為URL路徑的附加信息,表現形式為http://...../xxx;jsessionid= ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764
          另一種是作為查詢字符串附加在URL后面,表現形式為http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764
          這兩種方式對于用戶來說是沒有區別的,只是服務器在解析的時候處理的方式不同,采用第一種方式也有利于把session id的信息和正常程序參數區分開來。
          為了在整個交互過程中始終保持狀態,就必須在每個客戶端可能請求的路徑后面都包含這個session id。

          另一種技術叫做表單隱藏字段。就是服務器會自動修改表單,添加一個隱藏字段,以便在表單提交時能夠把session id傳遞回服務器。比如下面的表單
          <form name="testform" action="/xxx">
          <input type="text">
          </form>


          在被傳遞給客戶端之前將被改寫成
          <form name="testform" action="/xxx">
          <input type="hidden" name="jsessionid" value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764">
          <input type="text">
          </form>


          這種技術現在已較少應用,筆者接觸過的很古老的iPlanet6(SunONE應用服務器的前身)就使用了這種技術。
          實際上這種技術可以簡單的用對action應用URL重寫來代替。

          在談論session機制的時候,常常聽到這樣一種誤解“只要關閉瀏覽器,session就消失了”。其實可以想象一下會員卡的例子,除非顧客主動對店家提出銷卡,否則店家絕對不會輕易刪除顧客的資料。對session來說也是一樣的,除非程序通知服務器刪除一個session,否則服務器會一直保留,程序一般都是在用戶做log off的時候發個指令去刪除session。然而瀏覽器從來不會主動在關閉之前通知服務器它將要關閉,因此服務器根本不會有機會知道瀏覽器已經關閉,之所以會有這種錯覺,是大部分session機制都使用會話cookie來保存session id,而關閉瀏覽器后這個 session id就消失了,再次連接服務器時也就無法找到原來的session。如果服務器設置的cookie被保存到硬盤上,或者使用某種手段改寫瀏覽器發出的HTTP請求頭,把原來的session id發送給服務器,則再次打開瀏覽器仍然能夠找到原來的session。

          恰恰是由于關閉瀏覽器不會導致session被刪除,迫使服務器為seesion設置了一個失效時間,當距離客戶端上一次使用session的時間超過這個失效時間時,服務器就可以認為客戶端已經停止了活動,才會把session刪除以節省存儲空間。

          五、理解javax.servlet.http.HttpSession
          HttpSession是Java平臺對session機制的實現規范,因為它僅僅是個接口,具體到每個web應用服務器的提供商,除了對規范支持之外,仍然會有一些規范里沒有規定的細微差異。這里我們以BEA的Weblogic Server8.1作為例子來演示。

          首先,Weblogic Server提供了一系列的參數來控制它的HttpSession的實現,包括使用cookie的開關選項,使用URL重寫的開關選項,session持久化的設置,session失效時間的設置,以及針對cookie的各種設置,比如設置cookie的名字、路徑、域, cookie的生存時間等。

          一般情況下,session都是存儲在內存里,當服務器進程被停止或者重啟的時候,內存里的session也會被清空,如果設置了session的持久化特性,服務器就會把session保存到硬盤上,當服務器進程重新啟動或這些信息將能夠被再次使用, Weblogic Server支持的持久性方式包括文件、數據庫、客戶端cookie保存和復制。

          復制嚴格說來不算持久化保存,因為session實際上還是保存在內存里,不過同樣的信息被復制到各個cluster內的服務器進程中,這樣即使某個服務器進程停止工作也仍然可以從其他進程中取得session。

          cookie生存時間的設置則會影響瀏覽器生成的cookie是否是一個會話cookie。默認是使用會話cookie。有興趣的可以用它來試驗我們在第四節里提到的那個誤解。

          cookie的路徑對于web應用程序來說是一個非常重要的選項,Weblogic Server對這個選項的默認處理方式使得它與其他服務器有明顯的區別。后面我們會專題討論。

          關于session的設置參考[5] http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1036869

          六、HttpSession常見問題
          (在本小節中session的含義為⑤和⑥的混合)

          1、session在何時被創建
          一個常見的誤解是以為session在有客戶端訪問時就被創建,然而事實是直到某server端程序調用 HttpServletRequest.getSession(true)這樣的語句時才被創建,注意如果JSP沒有顯示的使用 <% @page session="false"%> 關閉session,則JSP文件在編譯成Servlet時將會自動加上這樣一條語句 HttpSession session = HttpServletRequest.getSession(true);這也是JSP中隱含的 session對象的來歷。

          由于session會消耗內存資源,因此,如果不打算使用session,應該在所有的JSP中關閉它。

          2、session何時被刪除
          綜合前面的討論,session在下列情況下被刪除a.程序調用HttpSession.invalidate();或b.距離上一次收到客戶端發送的session id時間間隔超過了session的超時設置;或c.服務器進程被停止(非持久session)

          3、如何做到在瀏覽器關閉時刪除session
          嚴格的講,做不到這一點。可以做一點努力的辦法是在所有的客戶端頁面里使用javascript代碼window.oncolose來監視瀏覽器的關閉動作,然后向服務器發送一個請求來刪除session。但是對于瀏覽器崩潰或者強行殺死進程這些非常規手段仍然無能為力。

          4、有個HttpSessionListener是怎么回事
          你可以創建這樣的listener去監控session的創建和銷毀事件,使得在發生這樣的事件時你可以做一些相應的工作。注意是session的創建和銷毀動作觸發listener,而不是相反。類似的與HttpSession有關的listener還有 HttpSessionBindingListener,HttpSessionActivationListener和 HttpSessionAttributeListener。

          5、存放在session中的對象必須是可序列化的嗎
          不是必需的。要求對象可序列化只是為了session能夠在集群中被復制或者能夠持久保存或者在必要時server能夠暫時把session交換出內存。在 Weblogic Server的session中放置一個不可序列化的對象在控制臺上會收到一個警告。我所用過的某個iPlanet版本如果 session中有不可序列化的對象,在session銷毀時會有一個Exception,很奇怪。

          6、如何才能正確的應付客戶端禁止cookie的可能性
          對所有的URL使用URL重寫,包括超鏈接,form的action,和重定向的URL,具體做法參見[6]
          http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770

          7、開兩個瀏覽器窗口訪問應用程序會使用同一個session還是不同的session
          參見第三小節對cookie的討論,對session來說是只認id不認人,因此不同的瀏覽器,不同的窗口打開方式以及不同的cookie存儲方式都會對這個問題的答案有影響。

          8、如何防止用戶打開兩個瀏覽器窗口操作導致的session混亂
          這個問題與防止表單多次提交是類似的,可以通過設置客戶端的令牌來解決。就是在服務器每次生成一個不同的id返回給客戶端,同時保存在session里,客戶端提交表單時必須把這個id也返回服務器,程序首先比較返回的id與保存在session里的值是否一致,如果不一致則說明本次操作已經被提交過了??梢詤⒖础禞2EE核心模式》關于表示層模式的部分。需要注意的是對于使用javascript window.open打開的窗口,一般不設置這個id,或者使用單獨的id,以防主窗口無法操作,建議不要再window.open打開的窗口里做修改操作,這樣就可以不用設置。

          9、為什么在Weblogic Server中改變session的值后要重新調用一次session.setValue
          做這個動作主要是為了在集群環境中提示Weblogic Server session中的值發生了改變,需要向其他服務器進程復制新的session值。

          10、為什么session不見了
          排除session正常失效的因素之外,服務器本身的可能性應該是微乎其微的,雖然筆者在iPlanet6SP1加若干補丁的Solaris版本上倒也遇到過;瀏覽器插件的可能性次之,筆者也遇到過3721插件造成的問題;理論上防火墻或者代理服務器在cookie處理上也有可能會出現問題。
          出現這一問題的大部分原因都是程序的錯誤,最常見的就是在一個應用程序中去訪問另外一個應用程序。我們在下一節討論這個問題。

          七、跨應用程序的session共享

          常常有這樣的情況,一個大項目被分割成若干小項目開發,為了能夠互不干擾,要求每個小項目作為一個單獨的web應用程序開發,可是到了最后突然發現某幾個小項目之間需要共享一些信息,或者想使用session來實現SSO(single sign on),在session中保存login的用戶信息,最自然的要求是應用程序間能夠訪問彼此的session。

          然而按照Servlet規范,session的作用范圍應該僅僅限于當前應用程序下,不同的應用程序之間是不能夠互相訪問對方的session的。各個應用服務器從實際效果上都遵守了這一規范,但是實現的細節卻可能各有不同,因此解決跨應用程序session共享的方法也各不相同。

          首先來看一下Tomcat是如何實現web應用程序之間session的隔離的,從 Tomcat設置的cookie路徑來看,它對不同的應用程序設置的cookie路徑是不同的,這樣不同的應用程序所用的session id是不同的,因此即使在同一個瀏覽器窗口里訪問不同的應用程序,發送給服務器的session id也可以是不同的。

          image
          image

          根據這個特性,我們可以推測Tomcat中session的內存結構大致如下。
          image

          筆者以前用過的iPlanet也采用的是同樣的方式,估計SunONE與iPlanet之間不會有太大的差別。對于這種方式的服務器,解決的思路很簡單,實際實行起來也不難。要么讓所有的應用程序共享一個session id,要么讓應用程序能夠獲得其他應用程序的session id。

          iPlanet中有一種很簡單的方法來實現共享一個session id,那就是把各個應用程序的cookie路徑都設為/(實際上應該是/NASApp,對于應用程序來講它的作用相當于根)。
          <session-info>
          <path>/NASApp</path>
          </session-info>


          需要注意的是,操作共享的session應該遵循一些編程約定,比如在session attribute名字的前面加上應用程序的前綴,使得 setAttribute("name", "neo")變成setAttribute("app1.name", "neo"),以防止命名空間沖突,導致互相覆蓋。

          在Tomcat中則沒有這么方便的選擇。在Tomcat版本3上,我們還可以有一些手段來共享session。對于版本4以上的Tomcat,目前筆者尚未發現簡單的辦法。只能借助于第三方的力量,比如使用文件、數據庫、JMS或者客戶端cookie,URL參數或者隱藏字段等手段。

          我們再看一下Weblogic Server是如何處理session的。
          image
          image

          從截屏畫面上可以看到Weblogic Server對所有的應用程序設置的cookie的路徑都是/,這是不是意味著在Weblogic Server中默認的就可以共享session了呢?然而一個小實驗即可證明即使不同的應用程序使用的是同一個session,各個應用程序仍然只能訪問自己所設置的那些屬性。這說明Weblogic Server中的session的內存結構可能如下
          image

          對于這樣一種結構,在 session機制本身上來解決session共享的問題應該是不可能的了。除了借助于第三方的力量,比如使用文件、數據庫、JMS或者客戶端 cookie,URL參數或者隱藏字段等手段,還有一種較為方便的做法,就是把一個應用程序的session放到ServletContext中,這樣另外一個應用程序就可以從ServletContext中取得前一個應用程序的引用。示例代碼如下,

          應用程序A
          context.setAttribute("appA", session);
          


          應用程序B
          contextA = context.getContext("/appA");
          HttpSession sessionA = (HttpSession)contextA.getAttribute("appA");


          值得注意的是這種用法不可移植,因為根據ServletContext的JavaDoc,應用服務器可以處于安全的原因對于context.getContext("/appA");返回空值,以上做法在Weblogic Server 8.1中通過。

          那么Weblogic Server為什么要把所有的應用程序的cookie路徑都設為/呢?原來是為了SSO,凡是共享這個session的應用程序都可以共享認證的信息。一個簡單的實驗就可以證明這一點,修改首先登錄的那個應用程序的描述符weblogic.xml,把cookie路徑修改為/appA 訪問另外一個應用程序會重新要求登錄,即使是反過來,先訪問cookie路徑為/的應用程序,再訪問修改過路徑的這個,雖然不再提示登錄,但是登錄的用戶信息也會丟失。注意做這個實驗時認證方式應該使用FORM,因為瀏覽器和web服務器對basic認證方式有其他的處理方式,第二次請求的認證不是通過 session來實現的。具體請參看[7] secion 14.8 Authorization,你可以修改所附的示例程序來做這些試驗。

          八、總結
          session機制本身并不復雜,然而其實現和配置上的靈活性卻使得具體情況復雜多變。這也要求我們不能把僅僅某一次的經驗或者某一個瀏覽器,服務器的經驗當作普遍適用的經驗,而是始終需要具體情況具體分析。
          摘要:雖然session機制在web應用程序中被采用已經很長時間了,但是仍然有很多人不清楚session機制的本質,以至不能正確的應用這一技術。本文將詳細討論session的工作機制并且對在Java web application中應用session機制時常見的問題作出解答。

          posted @ 2007-06-27 22:36 chenweicai 閱讀(265) | 評論 (0)編輯 收藏

          counting 1 bits C implementations

          (idea) by bis (1.5 mon) (print)   ?   Thu Oct 18 2001 at 4:34:42

          Here are C implementations of all the methods for counting 1 bits mentioned in that node. (Go read that first, if you haven't already.) All of the statistical information is purely anecdotal, but for what it's worth, it's based on my testing the code on a Pentium 3 and a Celeron 2, using the cl compiler of Microsoft Visual C++, and on a Sun Ultra 5, using gcc and Sun's own cc. For testing 64-bit code, I used __int64 on the Intel machines, and long long on the Sparc. It's worth noting that while Sun's compiler outputs faster executables than gcc, it doesn't change the relative performance of the different methods.

          Table Lookup

          Use a pre-built lookup table of all the 1-bit counts for every possibly byte, then index into that for each byte that comprises the word. This is the fastest method (slightly) for 32 bits on both Intel and Sparc, and (even more slightly) the fastest for 64 bits on Sparc, falling to second fastest on 64 bits on Intel. Changing the lookup table from anything but unsigned or int makes it a little slower (what with the extra casting and byte-loading the compiler is forced to add.)
          unsigned numbits_lookup_table[256] = {
                          0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2,
                          3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3,
                          3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3,
                          4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4,
                          3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5,
                          6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4,
                          4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5,
                          6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5,
                          3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3,
                          4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6,
                          6, 7, 6, 7, 7, 8
                          };
                          unsigned numbits_lookup(unsigned i)
                          {
                          unsigned n;
                          n = numbits_lookup_table[i & 0xff];
                          n += numbits_lookup_table[i>>8  & 0xff];
                          n += numbits_lookup_table[i>>16 & 0xff];
                          n += numbits_lookup_table[i>>24 & 0xff];
                          return n;
                          }
                          

           

          Counters

          If you want a full explanation of how this works, read my writeup at counting 1 bits, but suffice it to say that you are essentially partitioning the word into groups, and combining the groups by adding them together in pairs until you are left with only one group, which is the answer. (performance notes in the next section.)
          unsigned numbits(unsigned int i)
                          {
                          unsigned int const MASK1  = 0x55555555;
                          unsigned int const MASK2  = 0x33333333;
                          unsigned int const MASK4  = 0x0f0f0f0f;
                          unsigned int const MASK8  = 0x00ff00ff;
                          unsigned int const MASK16 = 0x0000ffff;
                          i = (i&MASK1 ) + (i>>1 &MASK1 );
                          i = (i&MASK2 ) + (i>>2 &MASK2 );
                          i = (i&MASK4 ) + (i>>4 &MASK4 );
                          i = (i&MASK8 ) + (i>>8 &MASK8 );
                          i = (i&MASK16) + (i>>16&MASK16);
                          return i;
                          }
                          

           

          Optimized Counters

          call pointed out in counting 1 bits that you could optimize the Counters method further if you pay attention to which bits you care about and which you don't, which allows you to skip applying some of the masks.

           

          Some symbols that I'll use to represent what's going on:

          • 0: bits we know are zero from the previous step
          • o: bits we know are zero due to masking
          • -: bits we know are zero due to shifting
          • X: bits that might be 1 and we care about their values
          • x: bits that might be 1 but we don't care about their values

           

          So a 0 plus a 0 is still a 0, obviously; the tricky ones are the others, but they're not even so bad. 0 plus X is X, since if the X is a 0 or a 1, added to 0 it will pass through unchanged. However, X plus X is XX, because the sum can range from 0 (0+0), to 10 (1+1). The same holds true with xs, once those show up.

          Step 1:

                  oXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoX
                          +       -XoXoXoXoXoXoXoXoXoXoXoXoXoXoXoX
                          XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                          
          Step 2:
                  ooXXooXXooXXooXXooXXooXXooXXooXX
                          +       --XXooXXooXXooXXooXXooXXooXXooXX
                          0XXX0XXX0XXX0XXX0XXX0XXX0XXX0XXX
                          
          Step 3:
                  oooo0XXXoooo0XXXoooo0XXXoooo0XXX
                          +       ----0XXXoooo0XXXoooo0XXXoooo0XXX
                          0000XXXX0000XXXX0000XXXX0000XXXX
                          
          Step 4:
                  oooooooo0000XXXXoooooooo0000XXXX
                          +       --------0000XXXXoooooooo0000XXXX
                          00000000000XXXXX00000000000XXXXX
                          
          Step 5:
                  oooooooooooooooo00000000000XXXXX
                          +       ----------------00000000000XXXXX
                          00000000000000000000000000XXXXXX
                          
          You'll notice that the higher the step, the more known zeros (0) there are. call's suggestion was to change step 5 to this:

          Step 5:
                  ooooooooooooxxxx00000000000XXXXX
                          +       ----------------00000000000XXXXX
                          000000000000xxxx0000000000XXXXXX
                          (mask)  ooooooooooooooooooooooooooXXXXXX
                          
          (where "(mask)" means "after adding, apply a mask".)

           

          However, you can go back even further and apply the same technique - all the way to step 3, in fact. The best I can think to optimize this changes the last three steps into the following: Step 3:

                  0xxx0XXX0xxx0XXX0xxx0XXX0xxx0XXX
                          +       ----0XXX0xxx0XXX0xxx0XXX0xxx0XXX
                          0xxxXXXX0xxxXXXX0xxxXXXX0xxxXXXX
                          (mask)  0000XXXX0000XXXX0000XXXX0000XXXX
                          
          Step 4:
                  0000xxxx0000XXXX0000xxxx0000XXXX
                          +       --------0000XXXX0000xxxx0000XXXX
                          0000xxxx000XXXXX000xxxxx000XXXXX
                          
          Step 5:
                  0000xxxx000xxxxx000xxxxx000XXXXX
                          +       ----------------000xxxxx000XXXXX
                          0000xxxx000xxxxx00xxxxxx00XXXXXX
                          (mask)  ooooooooooooooooooooooooooXXXXXX
                          
          Anyway, that's all very lovely, but here's the C to do it:
          unsigned numbits(unsigned int i)
                          {
                          unsigned int const MASK1  = 0x55555555;
                          unsigned int const MASK2  = 0x33333333;
                          unsigned int const MASK4  = 0x0f0f0f0f;
                          unsigned int const MASK6 = 0x0000003f;
                          unsigned int const w = (v & MASK1) + ((v >> 1) & MASK1);
                          unsigned int const x = (w & MASK2) + ((w >> 2) & MASK2);
                          unsigned int const y = (x + (x >> 4) & MASK4);
                          unsigned int const z = (y + (y >> 8));
                          unsigned int const c = (z + (z >> 16)) & MASK6;
                          return c;
                          }
                          
          The performance on this method is marginally worse than the lookup method in the 32 bit cases, slightly better than lookup on 64 bit Intel, and right about the same on 64 bit Sparc. Of note is the fact that loading one of these bitmasks into a register actually takes two instructions on RISC machines, and a longer-than-32-bit instruction on the Intel, because it's impossible to pack an instruction and 32 bits worth of data into a single 32 bit instruction. See the bottom of jamesc's writeup at MIPS for more details on that...

           

          Mind-bending "best" method (even more optimized counters)

          A slightly-modified version of the code on this page: http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel, which in turn stole the code from the "Software Optimization Guide for AMD AthlonTM 64 and OpteronTM Processors":
          unsigned numbits(unsigned int i)
                          {
                          unsigned int const MASK1 = 0x55555555;
                          unsigned int const MASK2 = 0x33333333;
                          unsigned int const MASK4 = 0x0f0f0f0f;
                          unsigned int const w = v - ((v >> 1) & MASK1);
                          unsigned int const x = (w & MASK2) + ((w >> 2) & MASK2);
                          unsigned int const y = (x + (x >> 4) & MASK4);
                          unsigned int const c = (y * 0x01010101) >> 24;
                          return c;
                          }
                          
          This method is identical to the "Optimized Counters" method, with two tricks applied:
          1. To get rid of an AND in the first line: instead of adding adjacent bits, it subtracts the high bit by itself of a pair of the bits from the pair together, because the results are the same. 00 - 0 = 0, 01 - 0 = 01, 10 - 1 = 01, 11 - 1 = 10
          2. To merge the last two lines into one, it uses a multiply and a shift, which adds the four remaining byte-sized "counters" together in one step.

           

          Subtract 1 and AND

          See counting 1 bits SPOILER for a fuller explanation of this one, but basically the lowest 1-bit gets zeroed out every iteration, so when you run out of 1s to zero, you've iterated to the number of bits in the word. Clever. Unfortunately, not that terribly fast; it's roughly two to three times slower than the lookup and counters methods on both architectures.
          unsigned numbits_subtraction(unsigned i)
                          {
                          unsigned n;
                          for(n=0; i; n++)
                          i &= i-1;
                          return n;
                          }
                          

           

          Straightforwardly Examine Each Bit

          The most easily understandable and slowest method: iterate over all the bits in the word; if the current bit is a 1, then increment the counter, otherwise, do nothing. That's actually done here by looking at the least-significant bit on each iteration, then shifting to the right one, and iterating until there are no more 1 bits in the word. There's a little optimization in the #ifndef here: instead of doing if (i & 1) n++;, which uses a branch instruction, just add the actual value of the least-significant bit to the counter ( n += (i & 1); ), as it will be a 1 when you want to add 1, and 0 when you don't. (We're just twiddling bits anyway, so why not?) This actually makes the processor do more adds, but adding is fast, and branching is slow, on modern processors, so it turns out to be about twice as fast. However, even "twice as fast" is still four to five times slower than the lookup method, again, on all architectures.
          unsigned numbits(unsigned int i)
                          {
                          unsigned n;
                          for(n=0; i; i >>= 1)
                          #ifndef MORE_OPTIMAL
                          if (i & 1) n++;
                          #else
                          n += (i & 1);
                          #endif
                          return n;
                          }
                          
          Now, why does this all matter? It doesn't, really, but it was sure a good way to waste some time, and maybe someone learned some optimizing tricks from it... (Well, I did, actually - so I hope someone else did as well.)

          posted @ 2007-06-27 18:30 chenweicai 閱讀(352) | 評論 (0)編輯 收藏

          主站蜘蛛池模板: 微博| 日照市| 宜章县| 望谟县| 淳安县| 濉溪县| 金秀| 黄平县| 西乌珠穆沁旗| 西吉县| 文化| 泰安市| 池州市| 咸阳市| 贡觉县| 卫辉市| 桓仁| 岳阳县| 祥云县| 阿城市| 博爱县| 东乡族自治县| 南丹县| 玛沁县| 营口市| 株洲县| 那坡县| 珠海市| 水城县| 尼玛县| 策勒县| 平凉市| 南投县| 巴塘县| 潮州市| 集安市| 贞丰县| 聊城市| 前郭尔| 安化县| 海兴县|