Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hi, I have a class that contains

Status
Not open for further replies.

DoraC

Programmer
May 7, 2002
98
US
Hi,

I have a class that contains both static and non-static methods, abstracted as such:

Code:
class MyClass
{
    static void doThis()
    {
        //-- code here...
    };

    public void doThat()
    {
        //-- code here...
    };
};

I need to synchronize these two methods - i.e. if a thread attempts to run one while another thread is running the other, *bad* things can happen...

Now, I know that if i synchronize both of these methods (i.e. write the "synchronized" keyword as part of their signature) they will be synchronized, but on different locks... the static method on the associated Class object, and the non-static instance method in the instance object. Does this mean that a separate thread can still run each of them simultaneously? If so, my issue is not resolved. How can I neatly synchronize them so that, if a thread attempts to execute the static method (for example) and another is running the instance method, the static-method execution will wait until the instance-method has completed, and vice-versa?

Thanks....
dora
 
>Does this mean that a separate thread can still run each >of them simultaneously?

Yes, to take it to the next level, even if a thread has the object locks, other threads can still access the non-synchronized codes.

hmm.. sticky situation.

Check into using join() on the static method. What you want to do is to let the static method to starts its thread after the instance-level object has dies.

Also, When you in there look for options under Object on using these methods, wait, notifyAll, notify. But remember, join() and wait() throw checkedException. Hence, you need to include them in a try/catch block or throws InterruptedException. Else, you will get a compilation error.
 
Thanks maxpower1,

I've managed to figure out a reasonable solution... I defined a static variable ( a "new byte[0]" object, although any object would have worked) and synchronized blocks of code on that object, instead of synchronizing the actual methods. That way, there is a common lock for the static-code and the instance-code to synchronize on...

thanks again -
dora c
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top