|
| |
"Multithreaded Access: Synchronizing Java Threads"
Vol. 7, Issue 1, p. 64
Listing 1
public void process (Request req) {
File file = new File(req.getFileName());
synchronized (file) {
// ... open/modify/close file as per the request parameters...
}
}
Listing 2
public void process (Request req) {
File file = acquireFile( req.getFileName() );
try {
synchronized (file) {
// ... open/modify/close file as per the request parameters...
}
}
finally {
releaseFile( file );
}
}
Listing 3
public void process (Request req) {
File file = new File( req.getFileName() );
Object semaphore = acquireSemaphore ( file );
try {
synchronized (semaphore) {
// ... open/modify/close file as per the request parameters...
}
}
finally {
releaseSemaphore( file );
}
}
Listing 4
public void methodA(LDAPObject obj) {
String dn = obj.getDN();
Object semaphore = acquireSemaphore ( dn );
try {
synchronized ( semaphore ) {
// read/modify/delete object
}
}
finally {
releaseSemaphore ( dn );
}
}
Listing 5
public class Monitor {
private WeakHashMap map = new WeakHashMap() {
public final Object get(Object key) {
Object ref = super.get(key);
Object monitor = ((ref == null) ? null : ((WeakReference)ref).get());
if (monitor == null) {
monitor = key;
put (monitor, new WeakReference(monitor));
}
return monitor;
}
};
public synchronized Object get(Object key) {
return map.get(key);
}
}
Listing 6
static final Monitor monitor = new Monitor();
public void process (Request req) {
File file = new File( req.getFileName() );
synchronized (monitor.get(file)) {
// ... open/modify/close file as per the request parameters...
}
}
|
|
All Rights Reserved
Copyright © 2004 SYS-CON Media, Inc.
E-mail: info@sys-con.com
Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.
|