我有一个服务类,包含一个添加Student
到a的方法Section
。现在每个Section
拥有set
的Students
与它相关联。
此外,还有一个Map<Section, Set<Student>>
定义两者之间的关系。
在service
看起来像这样与addStudent
方法:
public class MembershipService {private final Map<Section, Set<Student>> studentsBySection = new HashMap<>();public void addStudentToSection(Student student, Section sec) { Set<Student> students = studentsBySection.get(sec); if (students == null) { students = new HashSet<>(); studentsBySection.put(sec, students); } students.add(student);}// ..... also containing helper method : getStudents(Section s)
我需要在多线程场景中测试功能,我需要展示如果两个或多个线程试图从公共端添加或读取学生将会发生什么map
。
我清楚的知道,更换Hashmap
与ConcurrentHashMap
能解决我的目的,但我不能够证明确切行为。
我的解决方案
我创建了两个线程:Student1
并Student2
尝试将同一个Service
实例传递给它们并执行添加。预期的行为hashmap
应该ConcurrentModificationException
和ConcurrentHashMap
它一起不应该抛出。但它并没有表现出预期的行为,即使有了正常的工作HashMap
。请指导。
这是代码:
Student1
public class Student1 implements Runnable{Services services;public Student1(Services ser) { this.services = ser; new Thread(this, "Student 1").start();}@Overridepublic void run() { final Student ALEX = new Student("alex"); services.getMembershipService().addStudentToSection(ALEX,services.getSection());; try { System.out.println("Student 1 sleeping"); Thread.sleep(100); } catch (Exception e) { System.out.println(e); }}
}
STUDENT2
public class Student2 implements Runnable{Services services;public Student2(Services ser) { this.services = ser; new Thread(this, "Student 2").start();}@Overridepublic void run() { final Student JOHN = new Student("john"); services.getMembershipService().addStudentToSection(JOHN,services.getSection());;
}
Tester.java
public static void main(String[] args) { final Services services = ServiceFactory.createServices(); final Section A = new Section("A"); services.createSection(A); Student1 one = new Student1(services); Student2 two = new Student2(services);}
我如何证明我的案子?
注意:这不是关于How ConcurrentHashMap works in java
或多线程的。一般都知道。我只是无法将其与我的要求保持一致。
相关分类