我有一个服务类,其中包含向Section
添加Student
的方法。现在,每个Section
都有一个与之关联的set
Students
。
此外,还有一个Map<Section, Set<Student>>
定义了两者之间的关系。
使用addStudent
方法时,service
如下所示:
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
添加或读取学生会发生什么。
我清楚地知道用ConcurrentHashMap
替换Hashmap
会解决我的问题,但是我不能演示确切的行为。
My Solution
我创建了两个线程: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();
}
@Override
public 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();
}
@Override
public void run() {
final Student JOHN = new Student("john");
services.getMembershipService().addStudentToSection(JOHN,services.getSection());;
try {
System.out.println("Student 2 sleeping");
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e);
}
}
}
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
或general.Am中的多线程,知道这一点。我只是不能让它与我的需求保持一致。
发布于 2019-05-14 03:29:25
您的HashMap和ConcurrentHashMap在多线程环境中工作相同的原因是由于输入较少。我同时放入和读取200个键值对。
只需在代码中将ConcurrentHashMap替换为HashMap,即可获得concurrentModificationException。
ConcurrentHashMap实现:
package com.java.ConcurrentHashMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapDemo {
private final ConcurrentHashMap<Section,Set<Student>> studentsBySection = new ConcurrentHashMap<>();
public void addStudentToSection(Student student, Section sec) {
//System.out.println(Thread.currentThread().getName());
Set<Student> students = studentsBySection.get(sec);
if (students == null) {
students = new HashSet<>();
studentsBySection.putIfAbsent(sec, students);
}
students.add(student);
}
public static void main(String[] args) {
ConcurrentHashMapDemo ob = new ConcurrentHashMapDemo();
Thread t1 = new Thread(ob.new WriteThreasOne());
t1.setName("one");
Thread t3 = new Thread(ob.new WriteThreasTwo());
t3.setName("three");
Thread t2= new Thread(ob.new ReadThread());
t2.setName("two");
t1.start();
t2.start();
t3.start();
}
class WriteThreasOne implements Runnable {
@Override
public void run() {
final Section A = new Section("A");
for(int i=0;i<100;i++) {
addStudentToSection(new Student("alex"+i),A);
}
}
}
class WriteThreasTwo implements Runnable {
@Override
public void run() {
final Section A = new Section("A");
for(int i=1;i<100;i++) {
addStudentToSection(new Student("sam"+i),A);
}
}
}
class ReadThread implements Runnable {
@Override
public void run() {
//System.out.println(Thread.currentThread().getName());
Iterator<Section> ite = studentsBySection.keySet().iterator();
while(ite.hasNext()){
Section key = ite.next();
System.out.println(key+" : " + studentsBySection.get(key));
}
}
}
}
部分类:
package com.java.ConcurrentHashMap;
public class Section {
public Section(String sectionName) {
this.sectionName = sectionName;
}
private String sectionName;
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
@Override
public String toString() {
return "Section [sectionName=" + sectionName + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((sectionName == null) ? 0 : sectionName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Section other = (Section) obj;
if (sectionName == null) {
if (other.sectionName != null)
return false;
} else if (!sectionName.equals(other.sectionName))
return false;
return true;
}
}
学生类:
package com.java.ConcurrentHashMap;
public class Student {
private String studName;
public Student(String studName) {
this.studName = studName;
}
public String getStudName() {
return studName;
}
public void setStudName(String studName) {
this.studName = studName;
}
@Override
public String toString() {
return "Student [ studName=" + studName + "]";
}
}
https://stackoverflow.com/questions/56118386
复制相似问题