This week's giveaway is in the Threads forum.
We're giving away four copies of Java Concurrency Live Lessons and have Doug Schmidt on-line!
See this thread for details.
Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Is there a race condition in this code?  RSS feed

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Is there a chance of me getting a NullPointerException between the lines
8 to 11 ? This might be a stupid question. Bear with me. Thanks
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No.
 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I can sleep well at night. Thanks Jim.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The initialisation of "handler" to null is unnecessary.

Generally, one should not initialise variables except when the algorithm really requires it. Unnecessary initialisations: -

  • bloat the code
  • defeat the useful feature of the compiler that checks whether variables are initialised before they are used

  •  
    Pho Tek
    Ranch Hand
    Posts: 782
    Chrome Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Peter, good point!
     
    Gladwin Burboz
    Greenhorn
    Posts: 25
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You can get NullPointerExecption at line 5 if m_handlerRef is null
     
    Jim Yingst
    Wanderer
    Sheriff
    Posts: 18671
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Yes, but since m_handlerRef is final, the compiler must have forced the programmer to initialize the variable in a constructor or something, not shown here. It's possible that for some reason it's been initialized to null, but that's hardly a race condition - it's a fundamental problem with the program that will be very obvious as soon as it appears. Race conditions are generally much more elusive.
     
    Pho Tek
    Ranch Hand
    Posts: 782
    Chrome Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    @Gladwin,

    m_handlerRef is assigned a value in the constructor for the class.
    So it can't ever be null.
    [ March 10, 2008: Message edited by: Pho Tek ]
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!