0
//What will happen when you attempt to compile and run the following code?

public class TestThread extends Thread {
    public static void main(String[] args) {
        new TestThread().start();
        new TestThread().start();
    }

    public void run() {
        Safe s1 = new Safe("abc");
        Safe s2 = new Safe("xyz");
    }
}

class Safe {
    String  str;

    public synchronized Safe(String s) {
        str = s;
        str = str.toUpperCase();
        System.out.print(str + " ");
    }
}

why does this method public synchronized Safe (String S) give me a compile error ? i know we cant synchronize variable but what is wrong with the above code ?!?!

Dici
  • 25,226
  • 7
  • 41
  • 82
jht
  • 605
  • 1
  • 6
  • 16

3 Answers3

8

Constructors such as this cannot be synchronized:

public Safe(String s) 

It doesn't make sense to synchronize a constructor, because each time the constructor is called, it is working on a separate, new object. It can't be in conflict, even if two constructors are working at the same time.

Section 8.8.3 of the JLS indicates what can modifiers are allowed on a constructor, and synchronized isn't one of them:

ConstructorModifier:

Annotation public protected private

Also, it states:

There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work.

There is no need, so it's disallowed.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
2

Your method is a constructor, and constructors cannot be synchronized.

Please refer to this question

Community
  • 1
  • 1
AntonBerezin
  • 350
  • 1
  • 5
1

Constructors (as far as I am aware) cannot be synchronized. Since when you call a constructor, it creates a new location in memory. This new location could not have 2+ things trying to access it at the same time before it is created, so synchronizing a constructor is not necessary. Your method should instead be:

public Safe(String s) {
    str = s;
    str = str.toUpperCase();
    System.out.print(str + " ");
}
Mike Elofson
  • 2,017
  • 1
  • 10
  • 16