Is synchronized (this) blocking only the synchronized block or all the "this" code?

public class ObjectCounter {
    private static long numOfInstances = 0;
    public ObjectCounter(){
        synchronized(this){
        numOfInstances++;
        }
    }
    **public static synchronized long getCount(){
        return numOfInstances;
    }**
//vs//
    **public static long getCount(){
        return numOfInstances;
    }**
}

If I run several threads, some of them will call a static function getCount(), and some of them will create new instances. I want to get the getCount()actual number of instances in each call at that time.

  • Is there a difference between the two parameters in the code?
  • If I block " this", this does not mean that I cannot call getCount()until the constructor exits the synchronized block (say, if I do not write synchronization to getCount ()).
  • If I make a synchronized block in some place in the code, does it block only the synchronized block or all the code " this"?
  • EDIT: , , , .
  • , () ( ) ( , numOfInstances)?
  • getCount() ? (, (obj) () - ).
  • f1() () ObjectCounter, (), f1() ( )?
  • f1() () f2() () ObjectCounter, f1() () . (this) , f1() ( )? ( , "" )

`

+4
4

synchronized , , , ( ) . static synchronized . synchronized(this) . - , , , .

, , , , , , . , , , . , .

:

public class ObjectCounter {
    private static long numOfInstances = 0;
    public ObjectCounter(){
        synchronized(ObjectCounter.class){
            numOfInstances++;
        }
    }
    public static synchronized long getCount(){
        return numOfInstances;
    }
}

. , , , , .

: " , ", , : static , . . , , , Java: java.lang.Object .

№ 6: , AtomicLong. , .

# 3, # 7 # 8 : / , /. , , . " synchronized" , .

+8
  • , . getCount() , .

  • , . , .

  • . synchronized (this) .

, , , . () , getCount() . , !

+2

synchronized :

  • , . , /
  • . , , (2.)
0

?

, . -, getCount() ObjectCounter. - .

"this", , getCount(), (, getCount()).

( , static synchronized), , - - synchronized(this){, , synchronized long getCount(){, , , , .

, static synchronized long getCount(){, synchronized(this){. , - - synchronized(this){, - getCount(), .

, "this"?

  • : public synchronized long getCount(){, , , , , .

  • : public static synchronized long getCount(){, .


:

  • , - , , ,

  • , , static synchronized.

-2

All Articles