目录
ConcurrentModificationException 在 Java 中如何工作?
Java ConcurrentModificationException 示例
示例#2
How to Avoid ConcurrentModificationException in Java?
Conclusion
首页 Java java教程 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): 有原因的构造函数,这里的原因可以为空,这意味着它是未知的。

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。请参阅下面所附的屏幕截图以获取正确的输出:

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) ;
}
}
}
登录后复制

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

热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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1672
14
CakePHP 教程
1428
52
Laravel 教程
1332
25
PHP教程
1277
29
C# 教程
1257
24
PHP与Python:了解差异 PHP与Python:了解差异 Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

突破或从Java 8流返回? 突破或从Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

PHP与其他语言:比较 PHP与其他语言:比较 Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP与Python:核心功能 PHP与Python:核心功能 Apr 13, 2025 am 12:16 AM

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

PHP的影响:网络开发及以后 PHP的影响:网络开发及以后 Apr 18, 2025 am 12:10 AM

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

PHP:许多网站的基础 PHP:许多网站的基础 Apr 13, 2025 am 12:07 AM

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

PHP与Python:用例和应用程序 PHP与Python:用例和应用程序 Apr 17, 2025 am 12:23 AM

PHP适用于Web开发和内容管理系统,Python适合数据科学、机器学习和自动化脚本。1.PHP在构建快速、可扩展的网站和应用程序方面表现出色,常用于WordPress等CMS。2.Python在数据科学和机器学习领域表现卓越,拥有丰富的库如NumPy和TensorFlow。

See all articles