LocalDatastoreServiceのThreadを止める方法
JUnitで実行する分には問題は起こらないのですが、通常のJavaアプリケーションとしてGAEの実行環境を使い、LocalのDatastoreを操作したい場合、アプリケーションが終了しない問題に遭遇します。
原因は、com.google.appengine.api.datastore.dev.LocalDatastoreServiceが並列処理を行っており、非deamonスレッドを作っているのですが、こいつの後始末が出来ないのが原因です。ソースコードがないので詳細の実装は不明ですが、shutdownHookっぽいフィールドはあるので、System.exitすれば後始末してくれるのではないかとは思います。しかし、System.exitはちょっと負けた気分です。
というわけで、後始末用のコードを書いてみました。
public void setUp() throws Exception { LocalDatastoreServiceTestConfig config = new LocalDatastoreServiceTestConfig(); config.setBackingStoreLocation(path_to_storage_file); config.setNoIndexAutoGen(true); // 必要に応じて設定を追加 helper = new LocalServiceTestHelper(config); helper.setEnvAppId(APP_ID); helper.setEnvVersionId(VERSION); helper.setUp(); } public void tearDown() throws Exception { // LocalDatastoreService LocalRpcService lds = LocalServiceTestHelper.getLocalService(LocalDatastoreService.PACKAGE); Field schedulerField = lds.getClass().getDeclaredField("scheduler"); schedulerField.setAccessible(true); ((ScheduledThreadPoolExecutor) schedulerField.get(lds)).shutdown(); helper.tearDown(); }
当然ですが、開発環境限定のお話です。例外処理は適当にしてください。