• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

can I make static method / block as synchronized ? how does it work ?

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am bit confused in static & synchronized .....

can I make static method / block as synchronized ? and how does it work ?
is it works at class level ?

bye ...
 
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kavita


As per i know you can make static method as synchronized
i am not sure about static blocks so i cant say on it......

About its behaviour is ,i hope you must be knowing that static methods
are not related to instance of class so they can be called without object,
second thing is as it is synchronized so it can be used only by one thread at a time...........

and you asked how will it work so i can say on this you first try some code than you can bring up more queries............
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy Kavita,

yes it works on class level.

All static methods that are marked "synchronized" will block on the class.

E.g.:

produces:
one one one one one one one one one one
two two two two two two two two two two

Because it is synchronized, thread "two" will wait.

When you remove the "synchronized" keyword from method method() it will produce
one two one two one two one two one two one two one two one two one two one two


static blocks (class initializers) cannot and need not be marked synchronized. It is useless, the class will be loaded only once, and there will be no interferences.


But I guess, you meant blocks inside static methods. In this case you must specify the class literal as the object the lock is on.
For the above method you could also write:

This will behave just as if the whole static method is declared synchronized. Of course you could also sync only relative parts of the method, but in this example the whole thing is synchronized.

Dont't forget that Thread.sleep() does not return the lock, so it behaves "neutral".

Hoped that helped.


Yours,
Bu.
 
Water proof donuts! Eat them while reading this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic