Solved

Critical section equivalent in java

Posted on 2007-12-04
5
980 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 Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
arguments to jar 5 35
SHA2 certs for IIS AND Java? 2 113
java mysql insert application 14 29
American Express @Work site and Java 4 32
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

820 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