Container sync and read-only settings

 

 

1 ArrayList HashSet HashMap are all thread-unsafe. The following methods are used to achieve thread-safety when multiple threads access these classes at the same time

 

/**
 * Use Collections to manage sync containers
  ArrayList HashSet HashMap are all thread-unsafe. The following methods are used to achieve thread-safety when multiple threads access these classes at the same time.
 * synchronizedList()
	synchronizedSet()
	synchronizedMap()

 * @author Administrator
 *
 */
public class Demo01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List<String> list =new ArrayList<String>();
		list.add("a");
		list.add("b");
		//list can be synchronized
		List<String> synList =Collections.synchronizedList(list);
		System.out.println("The thread-safe list is made");
	}

}

 

 

2 Read-only settings:

 

/**
 * read only settings
 * emptyXxx() empty immutable collection
 * 1、emptyList()
 *    emptyMap()
 *    emptySet()
2. singletonXxx() an immutable set of elements
singleton(T o)
singletonList(T o)
singletonMap(K key, V value)

3. unmodifiableXxx() immutable container
unmodifiableList(List<? extends T> list)
unmodifiableSet(Set<? extends T> s)
unmodifiableMap(Map<? extends K,? extends V> m)
 * @author Administrator
 *
 */
public class Demo02 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String,String> map =new HashMap<String,String>();
		
		map.put("test", "test");
		map.put("bjsxt", "bjsxt");
		
		// read only control
		Map<String,String> map2 =Collections.unmodifiableMap(map); // Control this container can no longer be modified
		//map2.put("a", "a"); //Cannot operate
		System.out.println(map2.size());
		
		// container test for an element
		List<String> list =Collections.singletonList(new String()); // container with only one element
		list.add("test");
		//list.add("bjsxt"); //Container that can only contain one element
	}
	
	public static Set<String> oper(Set<String> set){
		if(null==set){
			return Collections.EMPTY_SET; //External acquisition to avoid NullPointerException
		}
		//operate
		return set;
	}

}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326653937&siteId=291194637