반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

Cores and Threads



안드로이드 어플리케이션을 빠르고 효율적으로 실행시키기 위해 dual-core chips 와 quad-core processor 들이 개발 되었고 안드로이드 디바이스에 적용되었습니다. 이런 multicore architecture들의 장점을 활용하기 위해 thread scheduler 같은 안드로이드 모듈에 관련된 기술이 만들어 졌습니다.  이 thread scheduler가 하는 일은 서로 다른 core들 사이에서 어플리케이션이 분할 되서 할당되어 그 성능을 최대치로 활용하는 겁니다.





어플리케이션을 효과적으로 운영하기 위해서는 메모리 관리도 중요한데요. garbage collectgor 를 가동하는 것은 메모리 recycling 의 아주 핵심적인 부분 입니다. 그리고 한가지 더 언급하자면 어플리케이션의 최적화 입니다. 바로 백그라운드 쓰레드에 의해서 서로 interactive 하지 않은 태스크를 갖는 겁니다. 쓰레드는 어플리케이션의 멀티 태스킹기능을 가능하도록 해 줍니다.



요 며칠간 multicore processor architecture를 활용하는 것과 메모리 관리에 있어서의 garbage의 역할 그리고 쓰레드와 AsyncTask 클래스를 사용해서 백그라운드로 어플리케이션의 task 들을 수행해 퍼포먼스를 개선시키는 것과 관련해서 다뤄 보겠습니다. 



Multicore Processor Architectures 의 활용 이해하기


당연히 멀티태스킹이 싱글 태스킹 보다 더 나은 겁니다. 싱글 태스킹에서는 한 task 가 작업을 수행할 때 다른 task들은 작업하는 task 가 수행을 끝낼때까지 stop 해 있어야 합니다. 반면에 멀티태스킹은 한가지 task 를 동시에 더 진행할 수 있습니다. 이 multi tasking 을 수행하도록 하기 위해 multicore processor architecture 가 사용됩니다. 안드로이드 3.0 이상의 버전에서 바로 이 single processor architecture나 multicore processor architecture를 활용할 수 있는 기능이 제공 되었습니다.



Multiple core들은 어플리케이션의 작업을 서로 다른 core에서 동시에 수행하도록 나눠 줌으로서 퍼포먼스 향상을 가져 옵니다. 이 multicore processor 는 thread scheduler에 의해 효율적으로 사용할 수 있습니다. multicore mobile processor의 잇점은 모든 core들에  소프트웨어의 task들이 할당되고 schedule 될 때 진정한 의미가 있는 것입니다. 만약 scheduling 이 제대로 작동하지 않으면 오히려 그 어플리케이션의 퍼포먼스는 안 좋아 질 수 있습니다.



많은 안드로이드 기계들이 dual-core chip들이나 quad-core processor 기능들을 가지고 있습니다. 이 dual- 그리고 quas-core 전화기를 최적화시키기 위해 몇가지 변화가 있었습니다. 그리고 그 중에 thread scheduler 는 이 새로운 quad-core 와 dual-core chip들에 대해 최고의 퍼포먼스를 보여줄 수 있도록 개선 됐습니다.


반응형


반응형

---> http://goo.gl/4VEaNI


Why this is important

A Letter of Plea to the Conscientious People of the World to bring about Truth, Justice and Democracy in the Republic of Korea (South Korea)

Neo-McCarthyism in South Korea!


Do you know what’s happening in South Korea?


Do you know how and who became the president of South Korea in 2012?

I implore you to read this urgent letter of plea and distribute it widely to your friends and network members.

Democracy is steadfastly dying in South Korea. As Watergate was to the USA, the National Intelligence Services (NIS a.k.a. KCIA) illegally intervened in the 2012, presidential election. The egregious outcome, a cruel and ruthless dictator, Geun-hye Park, daughter of the late dictator Chung-hee Park, assumed office. An aftermath of this stolen election, Korean “Neo-McCarthyism” is actively erupting. All in opposition of the current regime is deemed a communist and pro North Korea. Scholars, politicians, and even ordinary citizens who express diverse views are severely persecuted. Civil Rights in South Korea are virtually gone. The “Yoo-shin,” the repressive and autocratic laws written into the Constitution and enforced during Chung-hee Park’s military dictatorship between 1960 and 1979, are in full force.

A brief background on the establishment of the NIS

During the dictatorial regime of Chung-hee Park the NIS was formed in order to discern, capture, and prosecute political dissidents. Those nonconformists were labeled communists or pro North Korean activists and were brutally tortured and killed by the NIS.

Background information on the presidential election of 2012

Covert and unlawful activities were being actively conducted by the ruling Saenuri Party prior to the presidential election of 2012. The National Intelligence Services was blatantly breaking the constitutional and electoral laws of South Korea. Undercover agents created hundreds of thousands of user names on the internet and posted comments in favor of the presidential candidate, Guen-hye Park, and denouncing opposing candidates including Jae-in Moon. The NIS not only used their agents hired by private taxpayers, it also paid North Korean defectors and South Korean citizens for this character defaming campaign resulting in the destruction of vital evidence which would prove all allegations against the NIS. Consequently, constitutional law scholars have declared this illicit intervention an “electoral Coup d’etat.” To demand accountability from the Park Regime a multitude of nationals have taken to the streets holding continuous candlelight vigils.

Unfortunately, most South Korean mass media are only reporting on views of the ruling Saenuri Party. The ultra right-wing conservative groups are condemning the vigils as an “electoral disobedience.” To make matters worse, the Geun-hye Park government is trying to evade the legitimacy of this political crisis by re-launching the Neo-McCarthyism executed and enforced by her late father, Chung-hee Park. The Park administration has embarked upon a “witch hunt” against lawmaker Seok-ki Lee of the Unified Progressive Party. Freedom of expression and ideology and the principle of presumption of innocence until proven guilty are being mercilessly demolished.

If you see unfairness and injustice in the situation of South Korea, please go to (http://goo.gl/4VEaNI) to sign and forward this message to as many people as possible via emails and SNS. We would also greatly appreciate your efforts to draw public attention to this issue through submission to journals, for example, in collaboration with other civil activists.


September, 2013
Alliance of Conscientious People of the World



An Appeal for Democracy and Justice in the Republic of Korea (South Korea)

South Korea has achieved remarkable economic and political accomplishments in recent years. It has been a visible role model for many developing countries. However, these accomplishments have not come without devastating sacrifice.

After the Korean War, South Korea has gone through convulsive political turmoil. As a result of the April 19, 1960, uprising against Seungman Rhee, the Kwangju Massacre in 1980, and the June of 1987, Democratic Movements, many precious young lives were lost. Despite the high human toll, this hard-won democracy in South Korea is steadfastly dying at the hand of the unlawful electoral intervention by the National Intelligence Services, (NIS, a.k.a. KCIA) the renewal of Neo-McCarthyism and political witch hunts.

Geopolitically, the Korean Peninsula is at a critical juncture. Its domestic stability will become an important factor in determining world peace. Thus, at this hour, we express a deep concern over the current political situations in South Korea. The autocratic dictatorial regime of Chung-hee Park has returned by way of his daughter, Geun-hye Park, who was illicitly elected into presidential office through the intervention of the NSI.

To demand the return of peace, justice, and democracy in the Korean Peninsula and ultimately for world peace, we hereby request the following:

1. The Guen-hye Park administration cease the reinstatement of the Chung-hee Park dictatorship and the Yoo-shin. The Park regime must acknowledge the brutal and illegal deployment of Neo-McCarthyism and immediately abolish all witch hunting politics.


2. Legal prosecution of all those who intervened in the 2012, presidential election and a total dismantling of the NIS.


3. A full and comprehensive return to democracy in Korea guaranteeing the inalienable rights of freedom of expression, academic advancement, and ideology. We demand the complete eradication of censorship.


4. The return of the complete and authoritative rights of the prosecutor’s office.

Once again, peace and democracy on the Korean Peninsula will ultimately lead to a world peace. We vehemently urge the Park administration to execute all of the above-mentioned demands. We urge global citizens to join hands with this consorted effort to bring about peace and justice, not only on the Korean Peninsula but to the entire world.

Thank you.

September, 2013
Alliance of Conscientious People of the World


---> http://goo.gl/4VEaNI 





이 글은 한국의 자랑스러운 민주화의 역사가 다시 예전 독재세력에 의해 짓밟히고 있는 한국의 상황을 세계 양심인들과 공동으로 저항하기 위해 인터넷 상에서 서명을 받기 위한 글 입니다.

제 블로그에는 제 주위의 외국인들에게 대한민국의 민주주의 위기에 대해 알리고 그들의 이해와 참여를 권유하기 위해 올렸습니다.


링크를 클릭하면 한국어로 된 글도 보실 수 있습니다.


천주교 정의구현 사제단이 23일 오후 7시 30분 서울 광장에서 '국정원 해체와 민주주의 회복을 위한 전국시국기도회' 를 연다고 합니다.


신부님들은 "최근의 청문회에서 보았듯이 정부와 여당은 진실규명을 위한 노력들을 방해하고 조롱하였으며 명백하게 드러난 사실마저 또 다른 거짓말로 얼버무리는 억지를 부렸다. 남북정상대화록의 본의를 왜곡하여 선거에 도용한 일이나 국정원이 이를 무단공개한 일 등은 여론조작을 위한 댓글공작과 함께 반드시 처벌을 받아야 할 중범죄들" 이라고 하셨습니다.


또한 "아예 고질이 되어버린 거짓의 암세포를 말끔히 치유하지 않는 한 우리 사회는 그 어떤 희망도 가질 수 없다. 우리가 국정원이 저질렀고 경찰청이 덮어버린 공작들을 중대한 범죄로 규정하고 진상규명을 촉구하는 것은 바로 이런 까닭" 이라며 "거짓에 의한, 거짓을 위한 통치가 이토록 순조로워진 것은 악을 방관한 우리 모두의 책임이기도 하다. 이승만 독재와 박정희 군사독재에 맞서 싸우던 저항의 정신으로 거짓축출과 민주주의 회복 운동에 함께 해주기를 바란다" 라고 얘기하셨습니다.


관련 기사 ->

15개 가톨릭교구 사제·수도자·평신도 "국정원 해체" 외친다



죽어가는 민주주의를 보고만 있을 수 없습니다.

추석 이후 민주주의를 살리기 위한 거대한 불꽃이 한국에서 다시 활활 타 올랐으면 좋겠습니다.

전 세계인도 우리의 진실을 위한 저항을 지켜보고 응원해 줄 겁니다.

반응형


반응형

오늘은 Android Tablet Developer's Cook Book에 나오는 JSON 관련 예제를 공부할 겁니다.


Chapter 15에 나오는 예제인데요. ConsumeJSONWebserviceApp 이라는 프로젝트 입니다.


일단 SampleJSON.php 라는 파일이 아래 경로에 있습니다.


http://www.gosolkit.com/SampleJSON.php


이 php가 만들어낸 json 데이터는 아래와 같습니다.


[{"state":"Alabama","capital":"Montgomery","latitude":"32.361538","longitude":"-86.279118"},{"state":"Alaska","capital":"Juneau","latitude":"58.301935","longitude":"-134.419740"},{"state":"Arizona","capital":"Phoenix","latitude":"33.448457","longitude":"112.073844"},{"state":"California","capital":"Secramento","latitude":"36.448457","longitude":"112.073844"},{"state":"Gangwon","capital":"Chunchon","latitude":"33.448457","longitude":"112.073844"},{"state":"Rhode Island","capital":"Providence","latitude":"33.448457","longitude":"112.073844"},{"state":"New Jersey","capital":"Trenton","latitude":"33.448457","longitude":"112.073844"}]

위 URL은 책에 있는 URL이랑은 다릅니다.

제 개인 URL 을 사용했구요. json 데이터도 안에 그 내용을 조금 더 추가했습니다.


원격에 있는 php로 생성한 JSON 파일을 받아와서 안드로이드 앱에서 사용하는 예제 입니다.


우선 첫번째로 layout xml 파일을 보죠.


activity_consume_jsonwebservice_app.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"> 
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/state_name"
            android:hint="Enter State Name" 
                android:textSize="@dimen/text_size"   />
    <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/submit_btn"
            android:text="Submit"
                android:textSize="@dimen/text_size" />
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/response"
                android:textSize="@dimen/text_size" />
</LinearLayout>


LinearLayout으로 감쌌고 orientation은 vertical 입니다.

그 안에 EditText와 Button 그리고 TextView 이렇게 세개의 view 가 있습니다.



EditText에 주 이름을 넣고 Submit 버튼을 누르면 그 아래 TextView에 원격에서 받은 JSON 데이터를 파싱해서 뿌려 줄 건가 봅니다.


그러면 이제 자바 파일을 보죠.


ConsumeJSONWebserviceAppActivity.java


public class ConsumeJSONWebserviceAppActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consume_jsonwebservice_app);
        Button submitButton = (Button)this.findViewById(R.id.submit_btn);
        submitButton.setOnClickListener(new Button.OnClickListener(){
             public void onClick(View v)  { 
                    new ReadJSONFeed().execute("http://www.gosolkit.com/SampleJSON.php");               
             }
        });
    }
     
    private class ReadJSONFeed extends AsyncTask<String, String, String> {
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... urls) {
       HttpClient httpclient = new DefaultHttpClient();
       StringBuilder builder = new StringBuilder();
            HttpPost httppost = new HttpPost(urls[0]);
           try {
           HttpResponse response = httpclient.execute(httppost);
        StatusLine statusLine = response.getStatusLine();
       int statusCode = statusLine.getStatusCode();
       if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }     
    return builder.toString();
        }

        protected void onPostExecute(String result) {
            String state="";
            String stateInfo="";
            EditText stateName = (EditText) findViewById(R.id.state_name);
            String searchState=stateName.getText().toString();
            try{
             JSONArray countriesArray = new JSONArray(result);       
                   for (int i =0 ; i<countriesArray.length();i++) {
                       JSONObject jObject = countriesArray.getJSONObject(i);
                      state = jObject.getString("state");
                      if(searchState.equalsIgnoreCase(state))
                      {
                          stateInfo+="Capital: "+jObject.getString("capital")+"\n";
                          stateInfo+="Latitude: "+jObject.getString("latitude")+"\n";
                          stateInfo+="Longitude: "+jObject.getString("longitude")+"\n";
                      }
                   }
            }
             catch (JSONException e) {
                 e.printStackTrace();
                 }
            TextView resp = (TextView) findViewById(R.id.response);
            if(stateInfo.trim().length() >0 )
             resp.setText(stateInfo);   
            else
                resp.setText("Sorry no match found");
        }
    }
}



그렇게 복잡한거 같지는 않죠?


먼저 onCreate()를 보죠.

activity_consume_jsonwebservice_app.xml 을 Layout 으로 사용한다고 세팅했습니다.

바로 위에서 본 xml 입니다.


그리고 버튼에 대한 객체를 만들고 이 버튼에 onClickListener를 달았습니다.

이 버튼을 클릭하면 ReadJSONFeed() 라는 클래스를 호출하네요. 그리고 excute() 라는 메소드에 아까 소개했던 원격 URL 을 pass 합니다.


그러면 ReadJSONFeed() 클래스를 보겠습니다.

이 클래스는 AsyncTask 를 상속합니다.

여기를 보시면 해당 API를 보실 수 있습니다.


UI thread를 쉽게 사용할 수 있게 해 준다고 하네요. background 로 실행되게 해서 그 결과를 UI thread에 publish 하는 군요. 따로 thread나 handler들을 작성하지 않아도 된다고 하네요.

이 AsyncTask는 짧은 기간 동안 수행할 작업에 사용됩니다. 만약 긴 기간동안 수행할 작업을 쓰레드로 사용하시려면 Executor, ThreadPoolExecutor and FutureTask 같은 java.util.concurrent pacakge 를 사용 하셔야 합니다.

이 asynchronous task(비동기 작업)은 Params, Progress and Result 이렇게 3가지가 있고 4개의 step들이 있습니다.

onPreExecute, doInBackground, onProgressUpdate and onPostExecute


그러면 계속 ReadJSONFeed 클래스를 보겠습니다.

첫번째 줄에는 위에 봤든 onPreExecute() 메소드가 있네요. 그 안에는 아무것도 없구요.

그냥 넘어가도 되겠습니다.


그 다음에는 또 위에서 봤던 doInBackground() 메소드가 나옵니다.

이 안에 어떤 로직을 넣으면 Background 로 돌아가게 됩니다.


우선 HTTPClient와 HttpPost, StringBuilder 를 초기화 했습니다.

HttpResponse를 초기화 하면서 httpclient의 execute메소드를 통해 httppost를 pass 해 줍니다.

여기 httppost에는 아까 버튼 눌렀을 때 pass 했던 url이 들어 있습니다.

그러면 response 안에 그 결과값 즉 json 데이터들이 담기겠죠.

그 다음에는 StatusLine을 초기화 하면서 이 response의 line을 get 합니다.

즉 json 내용을 get 하는거죠.

그리고 이 statusLine 의 statusCode를 statusCode라는 변수에 담습니다.

이 statusCode에는 성공했는지 실패 했는지에 대한 정보가 담기겠죠.

다음 if 문에서는 만약에 이 작업이 성공했으면 HttpEntity 를 생성해서 여기에 response의 Entity를 가져 옵니다. 그리고 그 내용을 InputStrean에 담고요.

다음에 BufferedReader를 이용해서 그 내용을 읽습니다.


Java에서 파일 내용을 읽어 들일 때 사용하는 InputStream과 BufferedReader가 여기서도 사용되네요.

그 다음에 line이라는 String을 만들어서 모든 줄을 이 line에 넣습니다.


여기까지가 doInBackground() 메소드가 하는 일입니다.

간단하네요. 원격에 있는 정보를 가져와서 이것을 사람이 읽을 수 있는 정보로 line이라는 String에 담은 겁니다.


그 다음에 실행되는 메소드는 onPostExecute() 입니다.

한번 볼까요?


state, stateInfo 라는 String을 만들었습니다. 주 이름과 그 주에 대한 정보를 담을 변수들 인 것 같습니다.

그리고 layout xml에서 만든 EditText에 대한 변수를 만들었습니다.


그리고 searchState라는 String에 이 stateName의 내용을 담을 겁니다.


다음에 나오는 내용들은 JSON을 파싱하는 로직 입니다.

아까 doInBackGround에서는 line이라는 String에 이 JSON 데이터를 그냥 담았죠.

이것을 파싱해서 사람이 알아볼 수 있도록 화면에 뿌려줄 겁니다.


onPostExecute(String result) 라고 위에 돼 있죠. 여기서는 pass 받은 string을 result 라는 변수이름으로 사용할 겁니다.


보시면 이 result 를 countriesArray라는 JSONArray 에 담습니다.


그 다음 for 문을 돌려서 아까 만들었던 변수들에 해당 내용들을 담습니다.

state에는 주 이름이 그리고 searchState에 있는 내용들은 Capital, Latitude, Longitute 별로 따로 사람이 읽기 좋게 편집해서 stateInfo에 담습니다.


그 다음에는 try catch 문 밖을 보시면 되는데요.


TextView 객체를 만들었죠.

이 text 뷰에 위에 만들었던 stateInfo를 setText() 해서 화면에 표시합니다.


그러면 아래와 같은 화면을 보실 수 있습니다.





여기서의 주요 개념은 AsyncTask 를 이용해서 쉽게 Background 작업을 하도록 한다는 것과

원격의 데이터를 받아 오는 방법 여기서는 HttpClient, StringBuilder, HttpPost, HttpResponse 등이 사용됐습니다. 그리고 이 데이터를 바이너리 형태로 돼 있을 텐데 이것을 InputStream과 BufferedReader를 이용해서 사람이 읽을 수 있는 문자로 파싱하는 방법을 배웠습니다.

그리고 그 파싱된 JSON 타입을 다시 key 값을 이용해서 value를 가져와서 필요에 따라 편집하는 방법도 배웠습니다.


아주 중요한 개념들이 많네요.


안드로이드 앱과 웹 서비스와의 네트워킹도 아주 쉽게 사용할 수 있도록 만들었군요.




반응형