搜尋
首頁Javajava教程Java並發修改異常

Java並發修改異常

Aug 30, 2024 pm 04:13 PM
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) ;
}
}
}</integer></integer></integer>

程式碼說明:從幾個匯入檔案開始,然後類別減速和main方法。初始化數組列表並添加一個不斷添加數字的功能;這樣,它將正在進行中。每次新增時,我們都會列印列表值。但是接下來我們有一個 if 循環,它將查找等於 3 的數字,一旦找到 3,它將嘗試刪除該數字,這就是遇到異常的地方,並且程式將被終止。清單中不會再添加任何內容。

如果執行上面的程式碼沒有任何錯誤,程式碼將偶然發現異常。該異常位於 ConcurrentModificationException.main (ConcurrentModificationException.java:14)。這個異常的原因很明顯,我們試圖修改一個列表,Numberlist。請參閱下面所附的螢幕截圖以獲取正確的輸出:

Java並發修改異常

正如你所看到的,程式按照我們的預期執行了,列印語句成功執行,直到遇到值 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) ;
}
}
}</string></string></string>

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:

Java並發修改異常

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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
平台獨立性如何使企業級的Java應用程序受益?平台獨立性如何使企業級的Java應用程序受益?May 03, 2025 am 12:23 AM

Java在企業級應用中被廣泛使用是因為其平台獨立性。 1)平台獨立性通過Java虛擬機(JVM)實現,使代碼可在任何支持Java的平台上運行。 2)它簡化了跨平台部署和開發流程,提供了更大的靈活性和擴展性。 3)然而,需注意性能差異和第三方庫兼容性,並採用最佳實踐如使用純Java代碼和跨平台測試。

考慮到平台獨立性,Java在物聯網(物聯網)設備的開發中扮演什麼角色?考慮到平台獨立性,Java在物聯網(物聯網)設備的開發中扮演什麼角色?May 03, 2025 am 12:22 AM

JavaplaysigantroleiniotduetoitsplatFormentence.1)itallowscodeTobewrittenOnCeandrunonVariousDevices.2)Java'secosystemprovidesuseusefidesusefidesulylibrariesforiot.3)

描述一個方案,您在Java中遇到了一個特定於平台的問題以及如何解決。描述一個方案,您在Java中遇到了一個特定於平台的問題以及如何解決。May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java平台獨立對開發人員有什麼好處?Java平台獨立對開發人員有什麼好處?May 03, 2025 am 12:15 AM

Java'splatFormIndenceistificantBecapeitAllowSitallowsDevelostWriTecoDeonCeandRunitonAnyPlatFormwithAjvm.this“ writeonce,runanywhere”(era)櫥櫃櫥櫃:1)交叉plat formcomplibility cross-platformcombiblesible,enablingDeploymentMentMentMentMentAcrAptAprospOspOspOssCrossDifferentoSswithOssuse; 2)

將Java用於需要在不同服務器上運行的Web應用程序的優點是什麼?將Java用於需要在不同服務器上運行的Web應用程序的優點是什麼?May 03, 2025 am 12:13 AM

Java適合開發跨服務器web應用。 1)Java的“一次編寫,到處運行”哲學使其代碼可在任何支持JVM的平台上運行。 2)Java擁有豐富的生態系統,包括Spring和Hibernate等工具,簡化開發過程。 3)Java在性能和安全性方面表現出色,提供高效的內存管理和強大的安全保障。

JVM如何促進Java的'寫作一次,在任何地方運行”(WORA)功能?JVM如何促進Java的'寫作一次,在任何地方運行”(WORA)功能?May 02, 2025 am 12:25 AM

JVM通過字節碼解釋、平台無關的API和動態類加載實現Java的WORA特性:1.字節碼被解釋為機器碼,確保跨平台運行;2.標準API抽像操作系統差異;3.類在運行時動態加載,保證一致性。

Java的較新版本如何解決平台特定問題?Java的較新版本如何解決平台特定問題?May 02, 2025 am 12:18 AM

Java的最新版本通過JVM優化、標準庫改進和第三方庫支持有效解決平台特定問題。 1)JVM優化,如Java11的ZGC提升了垃圾回收性能。 2)標準庫改進,如Java9的模塊系統減少平台相關問題。 3)第三方庫提供平台優化版本,如OpenCV。

說明JVM執行的字節碼驗證的過程。說明JVM執行的字節碼驗證的過程。May 02, 2025 am 12:18 AM

JVM的字節碼驗證過程包括四個關鍵步驟:1)檢查類文件格式是否符合規範,2)驗證字節碼指令的有效性和正確性,3)進行數據流分析確保類型安全,4)平衡驗證的徹底性與性能。通過這些步驟,JVM確保只有安全、正確的字節碼被執行,從而保護程序的完整性和安全性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。