• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

this lock in run-method (Threads)

 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

is there any reason to synchronise the run() method in a subclass of the Thread class (or Runnable interface),
if we assume that this method is NOT invoked directly? E.g. by

someThreadInstance.run();


I mean, if a thread is started and enters the run-method, it gets the lock of the this object, which is the thread instance itself.
No other thread instance has ever any chance to acquire this lock. Are there any other reasons for that synchronizing?
Except of the direct invocation of the run()-method.
Is my reasoning OK?

thanks
Bob

Here one code example:
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I mean, if a thread is started and enters the run-method, it gets the lock of the this object, which is the thread instance itself.
No other thread instance has ever any chance to acquire this lock. Are there any other reasons for that synchronizing?
Except of the direct invocation of the run()-method.
Is my reasoning OK?



There are a few reasons why synchronizing the run() method is needed.

First, you answered it with the "Runnable" option. If you are not extending the Thread class, the "this" object is not the thread object for the thread, but a runnable object that may be shared between threads.

Second, just because the run() method is synchronized, it doesn't mean that the lock will be held for the lifetime of the method. It is possible to code the run() method to release the lock with the wait() method. So, it is possible to also have other synchronized methods that is used by other threads to communicate with the thread running the run() method.

Henry
 
Bob Wheeler
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great reply, Henry. Very good ideas. I understand the thread section more and more.

Thanks a lot.
Bob
 
reply
    Bookmark Topic Watch Topic
  • New Topic