aspose file tools*
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


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
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: 18966
    
  40

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: If the funId is the same,synchronized