O
Olli Plough
Hello,
I need to access a shared variable. So I enclose the code that
accesses the shared var with a synchronized block:
synchronized(myLock) {
// access my shared variable.
}
While this works, the overhead of synchronization always applies. Now
I try to get the synchronization done without using synchronized, but
with a non-blocking construct where the synchronization overhead only
applies when really some other thread is waiting for entry into the
critical section:
AtomicInteger count = new AtomicInteger(0); // inst var
Semaphore sem = new Semaphore(0); // inst var
if(!count.compareAndSet(0, 1))
sem.acquire();
// access my shared variable.
if(count.compareAndSet(1, 0)
sem.release();
My question is whether the code above using an AtomicInteger is thread-
safe and not violating lifelyness requirements. The solution is a bit
crude since it can only handle 2 threads. But this can be improved.
What I first want to assure myself of is whether the whole thing is
correct or not...
Any opinions?
Thanks, Oliver
I need to access a shared variable. So I enclose the code that
accesses the shared var with a synchronized block:
synchronized(myLock) {
// access my shared variable.
}
While this works, the overhead of synchronization always applies. Now
I try to get the synchronization done without using synchronized, but
with a non-blocking construct where the synchronization overhead only
applies when really some other thread is waiting for entry into the
critical section:
AtomicInteger count = new AtomicInteger(0); // inst var
Semaphore sem = new Semaphore(0); // inst var
if(!count.compareAndSet(0, 1))
sem.acquire();
// access my shared variable.
if(count.compareAndSet(1, 0)
sem.release();
My question is whether the code above using an AtomicInteger is thread-
safe and not violating lifelyness requirements. The solution is a bit
crude since it can only handle 2 threads. But this can be improved.
What I first want to assure myself of is whether the whole thing is
correct or not...
Any opinions?
Thanks, Oliver