001package com.streamconverter.context; 002 003/** 004 * ThreadLocalでExecutionContextを保持するホルダークラス 005 * 006 * <p>このクラスは、現在のスレッドに関連付けられたExecutionContextを管理します。 ログ出力時にLogback 007 * TurboFilterがこのホルダーから値を取得してMDCに設定します。 008 * 009 * <p><b>使用例:</b> 010 * 011 * <pre>{@code 012 * ExecutionContext context = ExecutionContext.create(); 013 * ExecutionContextHolder.set(context); 014 * try { 015 * // ログ出力時に自動的にMDCに値が設定される 016 * log.info("Processing..."); 017 * } finally { 018 * ExecutionContextHolder.clear(); 019 * } 020 * }</pre> 021 * 022 * <p><b>スレッドセーフ性:</b> ThreadLocalを使用しているため、スレッドごとに独立したコンテキストが管理されます。 023 */ 024public class ExecutionContextHolder { 025 026 private static final ThreadLocal<ExecutionContext> holder = new ThreadLocal<>(); 027 028 /** 029 * 現在のスレッドにExecutionContextを設定します 030 * 031 * @param context 設定するExecutionContext 032 */ 033 public static void set(ExecutionContext context) { 034 holder.set(context); 035 } 036 037 /** 038 * 現在のスレッドのExecutionContextを取得します 039 * 040 * @return 現在のスレッドのExecutionContext、設定されていない場合はnull 041 */ 042 public static ExecutionContext get() { 043 return holder.get(); 044 } 045 046 /** 047 * 現在のスレッドのExecutionContextをクリアします 048 * 049 * <p>メモリリークを防ぐため、スレッドの処理完了時に必ず呼び出してください。 050 */ 051 public static void clear() { 052 holder.remove(); 053 } 054 055 /** Private constructor to prevent instantiation. */ 056 private ExecutionContextHolder() { 057 // Utility class - no instantiation allowed 058 } 059}