threading_model.md: Add Java code example to Objects Validity

This commit is contained in:
Karol Lewandowski 2025-02-24 12:30:34 +01:00
parent dab6fb58e4
commit 98b59e5a85

View File

@ -268,6 +268,10 @@ In all other cases, it is required to wrap read operation in a read action with
The read objects aren't guaranteed to survive between several consecutive read actions. The read objects aren't guaranteed to survive between several consecutive read actions.
Whenever starting a read action, check if the PSI/VFS/project/module is still valid. Whenever starting a read action, check if the PSI/VFS/project/module is still valid.
Example: Example:
<tabs group="languages">
<tab title="Kotlin" group-key="kotlin">
```kotlin ```kotlin
val virtualFile = runReadAction { // read action 1 val virtualFile = runReadAction { // read action 1
// read a virtual file // read a virtual file
@ -280,6 +284,25 @@ val psiFile = runReadAction { // read action 2
} }
``` ```
</tab>
<tab title="Java" group-key="java">
```java
VirtualFile virtualFile = ReadAction.compute(() -> {
// read a virtual file
});
// do other time-consuming work...
PsiFile psiFile = ReadAction.compute(() -> { // read action 2
if (virtualFile.isValid()) { // check if the virtual file is valid
return PsiManager.getInstance(project).findFile(virtualFile);
}
return null;
});
```
</tab>
</tabs>
Between executing first and second read actions, another thread could invalidate the virtual file: Between executing first and second read actions, another thread could invalidate the virtual file:
```mermaid ```mermaid