Solved

Critical section equivalent in java

Posted on 2007-12-04
5
974 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
The viewer will learn how to implement Singleton Design Pattern in Java.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

707 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

17 Experts available now in Live!

Get 1:1 Help Now