3 Replies Latest reply: Jun 13, 2011 2:05 PM by EJP RSS

    synchronized class refer to?

    866541
      If someone refers a class as synchronized class (like vector or hashtable), Does that mean all methods are synchronized for that class?
        • 1. Re: synchronized class refer to?
          796440
          JavaFunda wrote:
          If someone refers a class as synchronized class (like vector or hashtable), Does that mean all methods are synchronized for that class?
          That's not a standard term. I've never heard it. I would have to assume that that's what he means though. To be sure though, you'd have to ask the source.
          • 2. Re: synchronized class refer to?
            802316
            All the public and protected methods are synchronized, private methods are not synchronized.

            Note: you can get thread safety issues even in Vector even though it is synchronized.

            consider
            Vector<Integer> ints= new Vector<Integer>();
            ints.add(1);
            ints.add(2);
            Enumeration<Integer> en = ints.elements();
            while(en.hasMoreElements()) {
                System.out.println(en.nextElement());
            }
            This works fine, but imagine another thread removes an element between hasMoreElements and nextElement.
            Vector<Integer> ints= new Vector<Integer>();
            ints.add(1);
            ints.add(2);
            Enumeration<Integer> en = ints.elements();
            int count = 0;
            int count = 0;
            while(en.hasMoreElements()) {
                OnAnotherThread: if(count++ == 1) ints.remove(0);
                System.out.println(en.nextElement());
            }
            This throws an exception.

            You can get around this by synchronized the vector yourself.

            BTW: Vector and Hashtable are legacy classes replaced in Java 1.2 (1998)
            • 3. Re: synchronized class refer to?
              EJP
              There was a very brief period around 1.1.3 when a compiler bug allowed you to put the 'synchronized' modifier on a class declaration. It didn't have any actual effect.