プログラマ38の日記

主にプログラムメモです。

Salesforce: apexのstatic変数と、javaのstatic変数の違いでとまどったこと

私はjavaのプログラムを書くことが多いのですが、javaのstatic変数とapexのstatic変数の違いにとまどいました。

 

javaのstatic変数は、Classで保持する変数で、例えばWebアプリケーションであれば、そのWebアプリケーションの中で1つの値を保持できて、複数のユーザで1つの値を共有できます。

※厳密にはClassloader別ですが、いったんおいておきます。

 

ですが、apexのstatic変数は、トランザクションを開始してから終了するまでが変数のスコープで、トランザクション単位に管理されるため、ユーザ毎の値になります。

 

以下、原文

A static variable is static only within the scope of the Apex transaction. It’s not static across the server or the entire organization. The value of a static variable persists within the context of a single transaction and is reset across transaction boundaries. For example, if an Apex DML request causes a trigger to fire multiple times, the static variables persist across these trigger invocations.