2012年12月14日金曜日

ExecutorService の使い方

ここで説明するのは、おそらくもっとも安全にマルチスレッドプログラムを書く方法です。

さらに同様の方法で簡単に拡張することで、複数のスレッドを効率よく使うスレッドプール (Thread Pool) を利用できますので、 ぜひ覚えておきたい方法です。

その方法とは、 ExecutorService を利用することです。

ExecutorService では、Java のマルチスレッド・プログラミングの基本 でみたように Thread オブジェクトをそのまま生では使いません。 プログラムの処理を小さなタスクに分割して、そのタスクを Executor によって実行すると考えます。

タスクの状態

Executor によって処理されるタスクの状態は次の四つです。

ExecutorService - タスクの状態

  1. created (作成された)
    サブミットされていない状態のタスクは created ステートです。
  2. submitted (サブミットされた)
    submit または execute メソッドでタスクをサブミットします。サブミットされても処理が開始しない場合は、通常ブロッキングキューに入ります。 FIFO で処理されます。

    submit された以降、メモリが割り当てられない等何らかの理由で処理がアボートする場合は、 RejectedExecutionException が発生します。

  3. started (処理が開始した)
  4. complted (完了した)

この状態は不可逆で、 created から completed へと順番に変わります。

スレッドプールを容易に使える ExecutorService

さて、スレッドプール (Thread Pool) について簡単に説明します。

スレッドプール

スレッドプールは通常 Web サーバーやデータベースサーバーなど、複数のタスクを同時に素早く処理しなければならない状況で利用されます。

複数のスレッドをあらかじめ作成して待機させておき、タスクが来たら待っているスレッドにタスクを割り当てて処理を開始させる仕組みをスレッドプールと言います。処理すべきタスクが到着してからモタモタとスレッドを起動するのではなく、スレッドをあらかじめ起動しておき、タスクが割り当てられたらすぐに処理を開始出来るようにする、ということです。

ゼロからこうした仕組みを実装するとなると、少々面倒くさいのですが、 Java では ExecutorService というものがあり、スレッドプールをあなたのプログラムで簡単に利用できます。

ExecutorService のコードサンプル

では、実際にスレッドプールを用いてタスクの処理を行う簡単な例を示します。

package com.keicode.java.test;    import java.util.concurrent.ExecutorService;  import java.util.concurrent.Executors;    public class ThreadTest4 {      public static void main(String[] args) {            System.out.println("Entering main");            ExecutorService exec = Executors.newFixedThreadPool(3);            try {        for(int i=0;i<10; i++){          exec.execute(new Runnable(){            public void run() {              try {                Thread.sleep(1 * 1000);                System.out.println("Hello! - "                   + Thread.currentThread().getId());              } catch (InterruptedException e) {                e.printStackTrace();              }            }          });        }                System.out.println("Sleeping..."           + Thread.currentThread().getId());        Thread.sleep(15 * 1000);              } catch(InterruptedException e) {        e.printStackTrace();      }        System.out.println("Exit main");          }    }  

実行結果は次のようになりました。

Entering main  Sleeping...1  Hello! - 8  Hello! - 10  Hello! - 9  Hello! - 10  Hello! - 8  Hello! - 9  Hello! - 10  Hello! - 9  Hello! - 8  Hello! - 10  Exit main  

ここではスレッドプール内に 3 つのスレッドを作成して、そこに 10 個のタスクを投げています。それぞれのタスクは、1 秒待ってから Hello! というメッセージとスレッド ID を出力します。

出力結果から、 ID が 8, 9, 10 という 3 つのスレッドがスレッドプール内で実行されたことがわかりますね。

java.util.concurrent.Executors.newFixedThreadPool というメソッドで、固定数のスレッドを持つスレッドプールを利用する ExecutorService を取得します。

ExecutorService の execute メソッドを呼ぶことで、タスクは submitted 状態になります。

ここでは一度に 10 個のタスクの実行 (execute) を要求していますが、スレッドが 3 個起動されています。このためまず 3 個のタスクが started になり、 残りの 7 個は submitted ステートのままキューの中で待ちます。

開始したタスクが終了したら、キューの中のタスクがスレッドに割り当てられて started 状態になります。

2012年12月12日水曜日

How to pirate Windows 8 Metro apps, bypass in-app purchases, and more

The principal engineer for Nokia's WP7 and WP8 devices has demonstrated, in rather frank detail, how to pirate Windows 8 Metro apps, how to bypass in-app purchases, and how to remove in-game ads. These hacks aren't exactly easy, but more worryingly they're not exactly hard either.

On his blog (Google cache), Justin Angel shows that turning a trial version of a Metro app into the full version — i.e. pirating an app — is scarily simple. It's just a matter of downloading a free, open-source tool, and then using it to change a Metro app's XML attribute from "Trial" to "Full." Likewise, a quick change to a XAML file can remove an app's ads.

Pirating a Windows 8 Metro app: Turning a Trial version into a Full version

Bypassing in-app purchases is a little trickier, involving some reverse engineering of some DLLs and and decryption of database files, but Angel still makes it look fairly easy. Angel gives himself one million credits in Soulcraft, an RPG game — something that would cost you over a thousand dollars, if you performed a legitimate in-app purchase. Angel also demonstrates a way to bypass in-app purchases in WinJS (Metro/JavaScript) apps, by injecting scripts into IE10 (the rendering engine for WinJS apps).

Pirating a Windows 8 Metro/WinJS app: Checking out the JavaScript source

Ultimately, all of these hacks represent ways of getting stuff for free. This is obviously bad news for developers, who probably don't realize that by allowing trial downloads they are opening themselves up to piracy. In-app ads and purchases are massive revenue streams for developers, and yet we now see that it's very easy to circumvent both.

You can protect these files with encryption — and indeed, some of them are — but that's no good if you have access to the code that performs the encryption. As Angel says, "We have the algorithm used for encryption, we have the hash key and we have the encrypted data. Once we have all of those it's pretty simple to decrypt anything." Angel notes that there are some security mechanisms in place that stopped him from directly editing app DLL and JS files, but, as we can see, that didn't stop him from pirating apps or bypassing in-app purchases.

It's easy to blame Microsoft for this, but really this is an issue that is intrinsic to all installed applications. The fact is, Windows 8 Metro apps are stored on your hard drive — and this means that you have access to the code and data. In general, every installed application is vulnerable to these kinds of attacks. Hex editors, save game editors, bypassing Adobe's 30-day trials by replacing DLL files, pirating Windows 8 apps — these are all just different incarnations of the same attack vectors.

The only real solution is to provide some kind of server-side sanity checking: You hack the software from Trial to Full — but when you log in, the server knows that you haven't bought the software, and so it reverts you back to Trial mode. You give yourself one million credits — but the server checks your purchase history, knows that you cheated, and so resets your credits back to zero. The problem with this route, of course, is that it requires you to be online — and you know how we feel about always-on DRM. Plus, it's very easy to disable server-side checks with a little Hosts file hacking.

In short, Windows 8 Metro apps have been hacked, and it's now just a matter of time until some enterprising developer creates a one-button tool that pirates trial apps, unlocks every in-app purchase, and removes in-app ads. There are certainly changes that Microsoft could make to shore up the security of Metro apps, but it would only delay the inevitable. Really, this is just a natural part of Windows 8′s evolution.