Solved

Critical section equivalent in java

Posted on 2007-12-04
5
978 Views
Last Modified: 2008-02-01
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
Comment
Question by:DJ_AM_Juicebox
  • 3
5 Comments
 
LVL 24

Accepted Solution

by:
sciuriware earned 500 total points
ID: 20409380
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
 
LVL 24

Expert Comment

by:sciuriware
ID: 20409384
In your example the second solution is mandatory; the first is incomplete.

;JOOP!
0
 
LVL 23

Expert Comment

by:cmalakar
ID: 20409391
Use Synchronized methods...

0
 
LVL 9

Expert Comment

by:ysnky
ID: 20409393
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 20409401
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

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This video teaches viewers about errors in exception handling.

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now