0 votes
in Java/J2EE by
Constructor is also a Method, hence can we make constructor also synchronized? Can we add synchronized block inside constructor?
related to an answer for: synchronized block vs synchronized method?
   

1 Answer

0 votes
by Hot Users (2.3k points)

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

Yes you can add the synchronized block inside the constructor.

More Explanation with Example

 

Synchronized method

Synchronized methods have two effects.
First, when one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

Synchronized Statement

Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: Most often I use this to synchronize access to a list or map but I don't want to block access to all methods of the object.

Q: Intrinsic Locks and Synchronization Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.

Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock

//      output Synchronization method means "it is not possible for two invocations

//      of synchronized methods on the same object to interleave"



        // Start the thread

        thread.start();

        thread2.start();

    }



    public synchronized  void increment() {

        System.out.println("Begin thread " + Thread.currentThread().getName());

        System.out.println(this.hashCode() + "Value of C = " + c);

//      If we uncomment this for synchronized block, then the result would be different

//      synchronized(this) {

            for (int i = 0; i < 9999999; i++) {

                c += i;

            }

//      }

        System.out.println("End thread " + Thread.currentThread().getName());

    }



//    public synchronized void decrement() {

//        System.out.println("Decrement " + Thread.currentThread().getName());

//    }



    public int value() {

        return c;

    }



    @Override

    public void run() {

        this.increment();

    }

}

Cross check different outputs with synchronized method, block and without synchronization.
Welcome to Find4Answers.com

Where you can Ask Questions, Find Answers Or Receive Answers from other members of the community And Share in Social networking sites like facebook, linkedin, twitter.
3cx phone system bandar bola benches boiler business bóg chwilówka przez internet car car lease deals car leasing uk chwilówka przez internet zapewne company convey convey law complaints convey law reviews convey law service conveylaw cornwall cosmetic dentist data data recovery maidenhead data recovery nottingham deals deepika padukone deepika padukone hot design development dot net programming dzieje szybkie chwilówki electrician electrician manchester electricians emergency farm filmy bez limitu filmy bez limitów filmy online finlock finlock solutions general genral graduate jobs in london graduate jobs london gutters hard drive recovery heap http: www.seo-assist.in infrared sauna infrared sauna saunas inline skating installation jabong coupon java judi bola laptop recycling law law firm in leeds lease leasing led lights led bulbs leeds life insurance quotes log london manchester movies museums and art myntra coupon nikogo szybka chwilówka outsource link building personal porcelain veneers ramię szybkie chwilówki recovery seo seo agencies seo company seo company london seo services services solutions stair lifts steel synchronization szybka chwilówka przykład szybka chwilówka żaden szybkie chwilówki lekko thread tunnel lighting tymczasem chwilówki przez internet upvc windows manchester viagra kamagra videos vinyl flooring suppliers wait web design services london web development company window repairs london windows yebhi coupon zobaczyć szybka chwilówka
...