Java並發修改異常
Java程式語言提供了一系列異常處理案例,並發修改異常就是其中之一。當程式中的執行緒嘗試修改目前進程中沒有編輯權限的物件時,會發生並發修改異常。簡單來說,當我們嘗試編輯目前正在被另一個程序使用的物件時,就會出現 ConcurrentModificationException。
開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
一個非常簡單的例子就是一個執行緒正在處理的集合。正在處理的集合不允許被修改,因此會拋出 ConcurrentModificationException。
文法:
下面是異常的最簡單語法。 ConcurrentModificationException 是 java lang RunTimeException 的一部分,並且擴展了它。
public class Concurrent Modification Exception extends Runtime Exception
ConcurrentModificationException 在 Java 中如何運作?
我們在Java中建立物件時,根據自己的需求設定一些限制和權限,這是可以理解的。但有時,我們試圖在線程中更改值或修改列表,這時就會出現 ConcurrentModificationException,因為該物件已被另一個線程使用,無法編輯或修改。
了解此異常並不總是意味著有一個物件被同時修改也很重要。在單線程的情況下,如果發生方法調用,就會拋出此異常,這在某種程度上違反了物件契約。
建構子:
ConcurrentModificationException 的一個非常基本的建構子如下所示:ConcurrentModificationException ()。除了簡單的建構子之外,我們還有以下貢獻者,可以根據需要使用:
- ConcurrentModificationException ( String textmessage): 帶有簡單訊息的建構子。
- ConcurrentModificationException (String textmessage, Throwable textcause): 帶有訊息和詳細原因的建構子。
- ConcurrentModificationException (Throwable textcause): 有原因的建構函數,這裡的原因可以是 null,即未知。
Java ConcurrentModificationException 範例
現在我們已經了解了並發修改異常是什麼以及它是如何運作的,讓我們開始實現。現在我們將透過一個例子來理解異常;例如,我們有一個數組列表,隨著一些操作,我們將嘗試修改它,這將導致異常。範例程式碼如下:
範例#1
代碼:
import java.awt.List; import java.util.*; public class ConcurrentModificationException { public static void main ( String[] args) { ArrayList<Integer> Numberlist = new ArrayList<Integer> () ; Numberlist.add ( 1) ; Numberlist.add ( 2) ; Numberlist.add ( 3) ; Numberlist.add ( 4) ; Numberlist.add ( 5) ; Iterator<Integer> it = Numberlist.iterator () ; while ( it.hasNext () ) { Integer numbervalue = it.next () ; System.out.println ( "List Value:" + numbervalue) ; if ( numbervalue .equals ( 3) ) Numberlist.remove ( numbervalue) ; } } }
程式碼說明:從幾個匯入檔案開始,然後類別減速和main方法。初始化數組列表並添加一個不斷添加數字的功能;這樣,它將正在進行中。每次新增時,我們都會列印列表值。但是接下來我們有一個 if 循環,它將查找等於 3 的數字,一旦找到 3,它將嘗試刪除該數字,這就是遇到異常的地方,並且程式將被終止。清單中不會再添加任何內容。
如果執行上面的程式碼沒有任何錯誤,程式碼將偶然發現異常。該異常位於 ConcurrentModificationException.main (ConcurrentModificationException.java:14)。這個異常的原因很明顯,我們試圖修改一個列表,Numberlist。請參閱下面所附的螢幕截圖以獲取正確的輸出:
正如你所看到的,程式按照我們的預期執行了,列印語句成功執行,直到遇到值 3。程式流程在值 3 處中斷,因為我們有一個 if 循環,看起來等於 3 的值並將其刪除。但是迭代器已經在進行中,嘗試刪除 3 將會失敗,並且這會拋出異常 ConcurrentModificationException。
範例#2
出於第二個範例的目的,我們將嘗試執行一個能夠成功避開並發修改異常的程式。在相同的程式碼中,如果我們嘗試在進程中修改數組列表,它將捕獲 ConcurrentModificationException,並且程式將被終止。第二個例子的程式碼如下:
代碼:
import java.util.Iterator; import java.util.ArrayList; public class ConcurrentModificationException { public static void main ( String args[]) { ArrayList<String> arraylist = new ArrayList<String> ( ) ; arraylist.add ( "One") ; arraylist.add ( "Two") ; arraylist.add ( "Three") ; arraylist.add ( "Four") ; try { System.out.println ( "ArrayList: ") ; Iterator<String> iteratornew = arraylist.iterator () ; while ( iteratornew.hasNext ( ) ) { System.out.print ( iteratornew.next () + ", "); } System.out.println ( "\n\n Trying to add an element in between iteration:" + arraylist.add ( "Five") ) ; System.out.println ( "\n Updated ArrayList: \n") ; iteratornew = arraylist.iterator () ; while ( iteratornew.hasNext ( ) ) { System.out.print ( iteratornew.next () + ", "); } } catch ( Exception e) { System.out.println ( e) ; } } }
Code Explanation: Similar to the earlier program, we have the required files and methods. We are simply adding a few elements to the array list, and it is iterating; we add another element, which is Five. We will print the updated list upon the latest additions, which will have our newly added element. We have implemented the try-catch block to catch the exception. If any exception occurs, it will print the exception.
Output:
As you can see in the output, the first array list is plain, with few elements. Then in the next line, we attempt to add an element while in iteration, the element is “Five”. It is successfully added, and it prints true for the sentence. And in the next line, we print an updated list, which has the Five-element. We have updated the list after the process is ending; if we try to add the element while in the process, it will throw the ConcurrentModificationException, and the program will cease.
How to Avoid ConcurrentModificationException in Java?
Avoiding Concurrent Modification Exception is possible on a different level of threads. To avoid a Concurrent Exception with a single thread environment, you can remove the object from the iterator and modify it, use remove ().
And in the case of a multi-thread environment, you have few choices like converting the list in the process into an array and then working on the array. Then you can also put a synchronized block over a list and lock it. But locking the list is not recommended as it may limit the advantages of multi-threading programming. Using a sublist to modify a list will result in nothing. Out of all the ways to avoid, the most preferred way is to wait until the execution is finished and then edit or modify the list or the object.
Conclusion
When a process is using one resource and another process attempts to edit or amend it, the exception ConcurrentModificationException will be thrown. The simplest method to avoid is to modify the list after iteration. Many methods are listed to avoid the exception but advised to implement them with small programs.
以上是Java並發修改異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Java 8引入了Stream API,提供了一種強大且表達力豐富的處理數據集合的方式。然而,使用Stream時,一個常見問題是:如何從forEach操作中中斷或返回? 傳統循環允許提前中斷或返回,但Stream的forEach方法並不直接支持這種方式。本文將解釋原因,並探討在Stream處理系統中實現提前終止的替代方法。 延伸閱讀: Java Stream API改進 理解Stream forEach forEach方法是一個終端操作,它對Stream中的每個元素執行一個操作。它的設計意圖是處

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

膠囊是一種三維幾何圖形,由一個圓柱體和兩端各一個半球體組成。膠囊的體積可以通過將圓柱體的體積和兩端半球體的體積相加來計算。本教程將討論如何使用不同的方法在Java中計算給定膠囊的體積。 膠囊體積公式 膠囊體積的公式如下: 膠囊體積 = 圓柱體體積 兩個半球體體積 其中, r: 半球體的半徑。 h: 圓柱體的高度(不包括半球體)。 例子 1 輸入 半徑 = 5 單位 高度 = 10 單位 輸出 體積 = 1570.8 立方單位 解釋 使用公式計算體積: 體積 = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP成為許多網站首選技術棧的原因包括其易用性、強大社區支持和廣泛應用。 1)易於學習和使用,適合初學者。 2)擁有龐大的開發者社區,資源豐富。 3)廣泛應用於WordPress、Drupal等平台。 4)與Web服務器緊密集成,簡化開發部署。
