can you check if this code will be thread safe/ replace synchronization's features? like restricting access to multiple threads?
class CheckSynch{
public static booloean check=true;
public static void func() // I am trying to write alternative code for synchronized function
{
if(check) 开发者_如何学Python{
check=false;
//body of function
check=true;
notifyAll();
} else {
wait();
}
}
}
Anything that doesn't use proper synchronization is bound to break. If you have two hardware threads, they will run concurrently, so in the time between check
being checked and modified, a different thread could have come along and changed it.
I don't know why you're trying to shun synchronized
, but whatever you're trying to do with unsynchronized functions, it won't work and will eventually break in very hard-to-reproduce bugs.
Writing your own Locking/sychronizaton is very advanced topic, writing code which compiles is not an advanced topic. You have to ask yourself if this really is a good idea.
You can write something like
final Lock lock = new ReentrantLock();
public static void func() {
lock.lock();
try {
//body of function
} finally {
lock.unlock();
}
}
However, you haven't said WHY you want to write you own synchronisation. I assume it because you don't want to wait 1-2 micro-seconds it takes to acquire a lock.
You can instead use a busy loop.
final AtomicBoolean lock = new AtomicBoolean();
public static void func() {
// wait for the lock to be false and set it to true.
while(lock.getAndSet(true));
try {
// body of function
} finally {
lock.set(false);
}
}
no, wait() needs to be in a synchronized block.
Its always advisable to avoid the synchronized
block in a static method.
i agree with EboMike, although if you are looking to block threads based on read/write criteria.. you can always use the ReentrantReadWriteLock
精彩评论