The program allows you to duplicate in a set. How did it go?

I checked a synchronizedSet and a normal set with threads. I wrote a program below.

package thread;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Sivaranjani D
 * 
 */

public class ThreadSafeCheck {
    public static void main(String[] args) {
        SyncList job = new SyncList();
        Thread t1 = new Thread(job);
        Thread t2 = new Thread(job);
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(job.set);
        System.out.println("Normal :" + job.set.size());
        System.out.println(job.synSet);
        System.out.println("Synchronized :" + job.synSet.size());
    }
}

class SyncList implements Runnable {
    Set<Integer> synSet = Collections.synchronizedSet(new HashSet<Integer>());
    Set<Integer> set = new HashSet<Integer>();

    public void run() {
        displaysynchronizedMap();
        displayNormalMap();
    }

    private void displaysynchronizedMap() {
        for (int i = 0; i < 50; i++) {
            synSet.add(i);
        }
    }

    private void displayNormalMap() {
        for (int i = 0; i < 50; i++) {
            set.add(i);
        }
    }
}

To my surprise, the kit allows for duplication. How is this possible? Someone please explain this.

+4
source share
2 answers

If you simultaneously modify an unsynchronized data structure, all bets are disabled. You cannot expect duplicates to be banned. The behavior is completely undefined: for example, demons can come out of your nose .

+1
source

HashSet HashMap. put() , , , . , , addEntry() (. HashMap.java). hashCode, bucket , .

+1

Source: https://habr.com/ru/post/1532882/


All Articles