This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes If the funId is the same,synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "If the funId is the same,synchronized" Watch "If the funId is the same,synchronized" New topic
Author

If the funId is the same,synchronized

eason liu
Greenhorn

Joined: Sep 21, 2008
Posts: 2
If three threads at the same time are trying to invoke this method.

public void test(String funId) {
// if the funId is the same,synchronized
// else not synchronized.
}

how should I do it?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 20037
    
  44

eason liu wrote:If three threads at the same time are trying to invoke this method.

public void test(String funId) {
// if the funId is the same,synchronized
// else not synchronized.
}

how should I do it?


A quick and dirty way to accomplish this is to intern the string and synchronize on it.

But ... it is probably better to create a class just for this. This class will use synchronization to "lock", but it only hold the sync lock long enough to add the id into a collection (and the thread that owns it). If another thread owns it, then it will have to wait for the unlock (using the wait and notify mechanism, of course).

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
eason liu
Greenhorn

Joined: Sep 21, 2008
Posts: 2
Thanks for your reply. I'm clear now.
 
Have you checked out Aspose?
 
subject: If the funId is the same,synchronized
 
It's not a secret anymore!