• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 998
  • Last Modified:

Critical section equivalent in java

Hi,

How do you protect a resource in java between threads as in a flag, something like this:

bool GetFlag()
{
    return m_bMyFlag;
}

bool SetFlag(bool b)
{
     m_bMyFlag = b;
}


somebody could be trying to set the flag while another thread is 'getting' it at the same time. How do you make sure only one touches either function at the same time?

Thanks
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
  • 3
1 Solution
 
sciuriwareCommented:
put the word 'synchronized' before each 'bool' for a start.

You can also declare the whole class synchronized to protect all methods at once.

;JOOP!
0
 
sciuriwareCommented:
In your example the second solution is mandatory; the first is incomplete.

;JOOP!
0
 
cmalakarCommented:
Use Synchronized methods...

0
 
sciuriwareCommented:
Well, we all agree:

public synchronized class YourClass
{
     bool GetFlag()
     {
         return m_bMyFlag;
     }

     bool SetFlag(bool b)
     {
          m_bMyFlag = b;
     }
}

is the best approach.

;JOOP!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now