Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

【Android】安全なThreadとは?【ConcurrentModificationException】

Posted at

業務中にスレッドの安全性について学ぶ機会があったので共有します。

安全なスレッドとは

安全なスレッドとは、複数のスレッドが同時に実行されても、プログラムやデータが正しく動作し、データの整合性が保たれる状態を指します。複数のスレッドからアクセスされても

簡単に言う 「色んな所から色々処理しても問題なく動くスレッド」 ということです。
(かなり雑です。)

例外

逆に安全でないスレッドは以下のエラー文がでてクラッシュする可能性があります。
ConcurrentModificationException (直訳は 「同時実行変更例外」)

この例外は、オブジェクトの並行変更を検出したメソッドによってスローできます(そのような変更が許可されていないとき)。
引用:クラスConcurrentModificationException

どうやら、同時に同じオブジェクトを参照して、データ変更を加える際に発生するようです。

例外を防ぐには

上記のエラーを防ぐ簡単な対策としてコードの同期が挙げられます。
マルチスレッドにせず、データ変更は一つのスレッドで行えば基本的にこのエラーは防ぐことができます。

基本的にはです。。。

1つのスレッドでも例外が起きる

実は、1つのスレッドでも例外が起きることがあります。

ある日のことListの中をForEach文で中身をみて、nullだったらListから消すという
処理を実装したら上記のエラーが発生しました。
どうやら、繰り返しを行うために参照していたlistを途中で削除してしまったのが
よくなかったようです。

↓凄く分かりやすく解説されていた記事があったの是非。
【Java】初心者のためのConcurrentModificationExceptionについて【Java Silver対策】

最後には

安全でないかは、今回のように直ぐに判明するとは限らないので
日ごろから安全なThreadを意識したコーディングを心がけます!

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?