Solved

Critical section equivalent in java

Posted on 2007-12-04
5
986 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

623 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