Why is the Properties.list property table before printing?

Here's the implementation Properties.listfrom the JDK:

public void list(PrintWriter out) {
    out.println("-- listing properties --");
    Hashtable<String,Object> h = new Hashtable<>();
    enumerate(h);
    for (Enumeration<String> e = h.keys() ; e.hasMoreElements() ;) {
        String key = e.nextElement();
        String val = (String)h.get(key);
        if (val.length() > 40) {
            val = val.substring(0, 37) + "...";
        }
        out.println(key + "=" + val);
    }
}

What are the lines

Hashtable<String,Object> h = new Hashtable<>();
enumerate(h);

for? Could he just use the original table instead of making a copy and reading data from it?

+4
source share
3 answers

The method is list()not synchronized.
Thus, any call (even synchronized) to the instance Propertiesduring the call list()can violate the state of the object and lead to an exception or broken logic.

Assume that instead of using an intermediate instance of Properties, we iterating directly onto the instance, Propertiesit will not be thread safe

, : Thread A, list() Thread B, remove() Properties.

list() .

, list():

   String key = e.nextElement();
   String val = (String)h.get(key);
   if (val.length() > 40) {

, A :

 String key = e.nextElement();  

B instance.remove() , , A

, A , :

 String val = (String)h.get(key);

.

, val null:

    if (val.length() > 40) {
+2

, (.. no ConcurrentModificationException, , - ).

+2

.

A Properties , ( , PrintStream , ), - (enumerate ), .

+1

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


All Articles