Is synchronized locking a Reentrantlock, or only its object? - java

The normal pattern with ReentrantLock and lock()/unlock() is like this:
lck.lock();
try {
// ...
}
finally {
lck.unlock();
}
Can this be refactored to
synchronized(lck) {
// ...
}
?
And why?

These are different things. synchronized is built into the language and can be used with any object. What it does is lock its intrinsic lock. Every single object has one. As it's a built-in mechanism, you don't need a try-finally block—the lock is always unlocked when the control exits the synchronized block. So as long as your code actually exits that block, the lock will be unlocked.
ReentrantLock is a special class. It locks some special internal object, that is probably implementation-specific. It does not lock its intrinsic lock. You could, of course, lock that one too—but it doesn't normally make any sense. This code will almost certainly deadlock, for example:
final ReentrantLock lock = new ReentrantLock();
new Thread(() -> {
lock.lock();
try {
System.out.println("Thread 1 locked the lock");
try { Thread.sleep(100); } catch (Exception ex) {}
synchronized (lock) {
System.out.println("Thread 1 locked lock's intrinsic lock");
}
} finally {
lock.unlock();
}
}).start();
new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 locked lock's intrinsic lock");
try { Thread.sleep(200); } catch (Exception ex) {}
lock.lock();
try {
System.out.println("Thread 2 locked the lock");
} finally {
lock.unlock();
}
}
}).start();
It deadlocks because two threads lock two different things in different order.
It certainly feels like ReentrantLock does almost the same thing as synchronized. It works similarly, but synchronized is both more convenient and less powerful. So unless you need any features of ReentrantLock, like interruptible lock attempts or lock time-outs, you should stick with synchronized for the purpose of reentrant locking, and use any objects for that. Simple private final Object lock = new Object() will do just fine. Note that final will prevent confusing things that could happen if you change that object at some moment; some IDEs will issue a warning if you omit final.

I assume that you are aware of differences in explicit and implicit locking provided by Lock and synchronized respectively.
I believe you are looking for a reason saying what's wrong in using instances of class implementing Lock interfaces inside synchronized block as in synchronized(lock).
Could it be refactored? Yes.
But should you be doing that? Not with instances of classes implementing Lock interface
Why? - Well.
It is all right if you just use lock only inside synchronized however you leave the possibility to other developers to misuse the code say for e.g. what if someone tomorrow tries calling Lock methods inside synchronized(lock) something like below.
Lock lock = new ReentrantLock();
synchronized(lock){ //You write this
// lock.lock(); // I am not taking a lock here
System.out.println("See emily play");
...
...
... // after 100 lines of code
//callAnotherMethod(lock); //Someone else does this
lock.unlock(); //Someone else does this
}
The above code is horrible but to give you an example, in the above example if you do not call lock(), then you end up with IllegalMonitorStateException. If you do call (uncomment above) lock.lock() it makes no difference.
Not to mention the callAnotherMethod(lock) where you are passing the lock instance and what sort of unexpected behaviours it can introduce.
Keep in mind that is one such example.
Bottom line, if it works correctly by any chance, it is just wasting resources and time and would serve no advantage/purpose. More importantly there is no guarantee that it would not introduce regressions in the future. And if there would be any such regressions, you may end up wasting significant amount of time because of misuse of concepts.
Softwares are always designed with Open-Close principle. You would be writing the code that would violate it very clearly.
In case if you do want to use fine grained locks using synchronized then you can make use of the below
Object obj1 = new Object();
Object obj2 = new Object();
public void doSomething(){
synchronised(obj1){
...
}
}
public void doSomethingMore(){
synchronised(obj2){
...
}
}
But then again, I don't see any reason why you would not use multiple lock instances to achieve the above.

Related

About Thread's wait()/ notify

I was trying to write an example on how to use wait() and notify(), but seems that the wait() can't be notified
public class Transfer {
private int[] data;
private volatile int ptr;
private final Object lock = new Object();
public Transfer(int[] data) {
this.data = data;
this.ptr = 0;
}
public void send() {
while (ptr < data.length) {
synchronized (lock) {
try {
System.out.println("-----wait");
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
ptr++;
}
}
}
public void receive() {
while (ptr < data.length) {
synchronized (lock) {
System.out.println("current is " + data[ptr]);
System.out.println("-----notify");
lock.notifyAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
////in main()
int[] data = new int[] { 111, 222, 333, 444, 555, 666, 777, 888, 999, 000 };
Transfer tf = new Transfer(data);
Thread t1 = new Thread(() -> {
tf.receive();
});
Thread t2 = new Thread(() -> {
tf.send();
});
t2.start();
t1.start();
but the result is :
-----wait
current is 111
-----notify
current is 111
-----notify
[endless repeat]
this is not what I expected, it should be :
current is 111
current is 222...
The problem with your code specifically is that you are keeping your locks way too long.
I'll first explain how wait/notify works, which is intricately connected with the concept of the monitor (synchronized), then how to do it right, and then as an encore, that you probably don't want to use this at all, it's too low level.
How does 'synchronized' work
When you write synchronized(x) you acquire the monitor - this operation can do one of three things. In all cases, x is a reference, so the reference is followed, it's about the object you find by following it.
If the reference is null, this immediately throws NPE.
If the object x points at has no current monitor, this thread becomes the monitor, the monitor count becomes 1, and code continues.
If the object x points at has a monitor but it is this thread, then the monitor count is incremented and code continues.
If the object x points at has a monitor but it is another thread, the thread will block until the monitor becomes available. Once it is available, some unfair dice show up, are rolled, and determine which of all threads 'fighting' to acquire the monitor will acquire it. Unfair in the sense that there are no guarantees made and the JVM is free to use any algorithm it wants to decide who 'wins'. If your code depends on fairness or some set order, your code is broken.
Upon reaching the } of the synchronized block, the monitor count is decremented. If it hits 0, the monitor is released (and the fight as per #4 starts, if other threads are waiting). In other words, locks are 're-entrant' in java. A thread can write synchronized(a){synchronized(a){}} and won't deadlock with itself.
Yes, this establishes comes-before stuff as per the Java Memory Model: Any fights arbitrated by a synchronized block will also ensure any writes by things that clearly came before (as established by who wins the fight) are observable by anything that clearly came after.
A method marked as 'synchronized' is effectively equivalent to wrapping the code in synchronized(this) for instance methods, and synchronized(MyClass.class) for static methods.
Monitors are not released and cannot be changed in java code* except via that } mechanism; (there is no public Thread getMonitor() {..} in j.l.Object or anywhere else) - in particular if the thread blocks for any other reason, including Thread.sleep, the monitor status does not change - your thread continues to hold on to it and thus stops all other threads from acquiring it. With one exception:
So how does wait/notify factor into this?
to wait/notify on x you MUST hold the monitor. this: x.notify();, unless it is wrapped in a synchronized(x) block, does not work.
When you wait(), the monitor is released, and the monitor count is remembered. a call to wait() requires 2 things to happen before it can continue: The 'wait' needs to be cancelled, either via a timeout, or an interrupt, or via a notify(All), and the thread needs to acquire that monitor again. If done normally (via a notify), by definition this is a fight, as whomever called notify neccessarily is still holding that monitor.
This then explains why your code does not work - your 'receiver' snippet holds on to the monitor while it sleeps. Take the sleep outside of the synchronized.
How do you use this, generally
The best way to use wait/notifyAll is not to make too many assumptions about the 'flow' of locking and unlocking. Only after acquiring the monitor, check some status. If the status is such that you need to wait for something to happen, then and only then start the wait() cycle. The thread that will cause that event to happen will first have to acquire the monitor and only then set steps to start the event. If this is not possible, that's okay - put in a failsafe, make the code that wait()s use a timeout (wait(500L) for example), so that if things fail, the while loop will fix the problem. Furthermore, there really is no good reason to ever use notify so forget that exists. notify makes no guarantees about what it'll unlock, and given that all threads that use wait ought to be checking the condition they were waiting for regardless of the behaviour of wait, notifyAll is always the right call to make.
So, it looks like this... let's say we're waiting for some file to exist.
// waiting side:
Path target = Paths.get("/file-i-am-waiting-for.txt");
synchronized (lock) {
while (!Files.isRegularFile(target)) {
try {
lock.wait(1000L);
} catch (InterruptedException e) {
// this exception occurs ONLY
// if some code explicitly called Thread.interrupt()
// on this thread. You therefore know what it means.
// usually, logging interruptedex is wrong!
// let's say here you intended it to mean: just exit
// and do nothing.
// to be clear: Interrupted does not mean:
// 'someone pressed CTRL+C' or 'the system is about to shutdown'.
return;
}
}
performOperation(target);
}
And on the 'file creation' side:
Path tgt = Paths.get("/file-i-am-waiting-for.txt");
Path create = tgt.getParent().resolve(tgt.getFileName() + ".create");
fillWithContent(create);
synchronized (lock) {
Files.move(create, tgt, StandardOpenOption.ATOMIC_MOVE);
lock.notifyAll();
}
The 'sending' (notifying) side is very simple, and note how we're using the file system to ensure that if the tgt file exists at all, it's fully formed and not a half-baked product. The receiving side uses a while loop: the notifying is itself NOT the signal to continue; it is merely the signal to re-check for the existence of this file. This is almost always how to do this stuff. Note also how all code involved with that file is always only doing things when they hold the lock, thus ensuring no clashes on that part.
But.. this is fairly low level stuff
The java.util.concurrent package has superior tooling for this stuff; for example, you may want a latch here, or a ReadWriteLock. They tend to outperform you, too.
But even juc is low level. Generally threading works best if the comm channel used between threads is inherently designed around concurrency. DBs (with a proper transaction level, such as SERIALIZABLE), or message buses like rabbitmq are such things. Why do you think script kiddies fresh off of an 8 hour course on PHP can manage to smash a website together that actually does at least hold up, thread-wise, even if it's littered with security issues? Because PHP enforces a model where all comms run through a DB because PHP is incapable of anything else in its basic deployment. As silly as these handcuffs may sound, the principle is solid, and can be applied just as easily from java.
*) sun.misc.Unsafe can do it, but it's called Unsafe for a reason.
Some closing best practices
Locks should be private; this is a rule broken by most examples and a lot of java code. You've done it right: if you're going to use synchronized, it should probably be on lock, which is private final Object lock = new Object();. Make it new Object[0] if you need it to be serializable, which arrays are, and Objects aren't.
if ever there is code in your system that does: synchronized(a) { synchronized (b) { ... }} and also code that odes: synchronized(b) { synchronized (a) { ... }} you're going to run into a deadlock at some point (each have acquired the first lock and are waiting for the second. They will be waiting forever. Be REAL careful when acquiring more than one monitor, and if you must, put in a ton of effort to ensure that you always acquire them in the same order to avoid deadlocks. Fortunately, jstack and such (tools to introspect running VMs) can tell you about deadlocks. The JVM itself, unfortunately, will just freeze in its tracks, dead as a doornail, if you deadlock it.
class Transfer {
private int[] data;
private volatile int ptr;
private final Object lock = new Object();
public Transfer(int[] data) {
this.data = data;
this.ptr = 0;
}
public void send() {
while (ptr < data.length) {
synchronized (lock) {
try {
System.out.println("-----wait");
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
ptr++;
}
}
}
public void receive() {
while (ptr < data.length) {
synchronized (lock) {
System.out.println("current is " + data[ptr]);
System.out.println("-----notify");
try {
lock.notifyAll();
lock.wait();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
"Thread.sleep" does not release the lock. So you need "lock.wait" to release the lock and let other thread proceed. Then after "send" increment the pointer, it should also notify so that other thread who is stuck at receive can now proceed.

How to create user defined SettableFuture in java [duplicate]

I am using multi-threading in java for my program.
I have run thread successfully but when I am using Thread.wait(), it is throwing java.lang.IllegalMonitorStateException.
How can I make a thread wait until it will be notified?
You need to be in a synchronized block in order for Object.wait() to work.
Also, I recommend looking at the concurrency packages instead of the old school threading packages. They are safer and way easier to work with.
EDIT
I assumed you meant Object.wait() as your exception is what happens when you try to gain access without holding the objects lock.
wait is defined in Object, and not it Thread. The monitor on Thread is a little unpredictable.
Although all Java objects have monitors, it is generally better to have a dedicated lock:
private final Object lock = new Object();
You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:
private static final class Lock { }
private final Object lock = new Lock();
In order to wait or notify/notifyAll an object, you need to be holding the lock with the synchronized statement. Also, you will need a while loop to check for the wakeup condition (find a good text on threading to explain why).
synchronized (lock) {
while (!isWakeupNeeded()) {
lock.wait();
}
}
To notify:
synchronized (lock) {
makeWakeupNeeded();
lock.notifyAll();
}
It is well worth getting to understand both Java language and java.util.concurrent.locks locks (and java.util.concurrent.atomic) when getting into multithreading. But use java.util.concurrent data structures whenever you can.
I know this thread is almost 2 years old but still need to close this since I also came to this Q/A session with same issue...
Please read this definition of illegalMonitorException again and again...
IllegalMonitorException is thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
This line again and again says, IllegalMonitorException comes when one of the 2 situation occurs....
1> wait on an object's monitor without owning the specified monitor.
2> notify other threads waiting on an object's monitor without owning the specified monitor.
Some might have got their answers... who all doesn't, then please check 2 statements....
synchronized (object)
object.wait()
If both object are same... then no illegalMonitorException can come.
Now again read the IllegalMonitorException definition and you wont forget it again...
Based on your comments it sounds like you are doing something like this:
Thread thread = new Thread(new Runnable(){
public void run() { // do stuff }});
thread.start();
...
thread.wait();
There are three problems.
As others have said, obj.wait() can only be called if the current thread holds the primitive lock / mutex for obj. If the current thread does not hold the lock, you get the exception you are seeing.
The thread.wait() call does not do what you seem to be expecting it to do. Specifically, thread.wait() does not cause the nominated thread to wait. Rather it causes the current thread to wait until some other thread calls thread.notify() or thread.notifyAll().
There is actually no safe way to force a Thread instance to pause if it doesn't want to. (The nearest that Java has to this is the deprecated Thread.suspend() method, but that method is inherently unsafe, as is explained in the Javadoc.)
If you want the newly started Thread to pause, the best way to do it is to create a CountdownLatch instance and have the thread call await() on the latch to pause itself. The main thread would then call countDown() on the latch to let the paused thread continue.
Orthogonal to the previous points, using a Thread object as a lock / mutex may cause problems. For example, the javadoc for Thread::join says:
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Since you haven't posted code, we're kind of working in the dark. What are the details of the exception?
Are you calling Thread.wait() from within the thread, or outside it?
I ask this because according to the javadoc for IllegalMonitorStateException, it is:
Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
To clarify this answer, this call to wait on a thread also throws IllegalMonitorStateException, despite being called from within a synchronized block:
private static final class Lock { }
private final Object lock = new Lock();
#Test
public void testRun() {
ThreadWorker worker = new ThreadWorker();
System.out.println ("Starting worker");
worker.start();
System.out.println ("Worker started - telling it to wait");
try {
synchronized (lock) {
worker.wait();
}
} catch (InterruptedException e1) {
String msg = "InterruptedException: [" + e1.getLocalizedMessage() + "]";
System.out.println (msg);
e1.printStackTrace();
System.out.flush();
}
System.out.println ("Worker done waiting, we're now waiting for it by joining");
try {
worker.join();
} catch (InterruptedException ex) { }
}
In order to deal with the IllegalMonitorStateException, you must verify that all invocations of the wait, notify and notifyAll methods are taking place only when the calling thread owns the appropriate monitor. The most simple solution is to enclose these calls inside synchronized blocks. The synchronization object that shall be invoked in the synchronized statement is the one whose monitor must be acquired.
Here is the simple example for to understand the concept of monitor
public class SimpleMonitorState {
public static void main(String args[]) throws InterruptedException {
SimpleMonitorState t = new SimpleMonitorState();
SimpleRunnable m = new SimpleRunnable(t);
Thread t1 = new Thread(m);
t1.start();
t.call();
}
public void call() throws InterruptedException {
synchronized (this) {
wait();
System.out.println("Single by Threads ");
}
}
}
class SimpleRunnable implements Runnable {
SimpleMonitorState t;
SimpleRunnable(SimpleMonitorState t) {
this.t = t;
}
#Override
public void run() {
try {
// Sleep
Thread.sleep(10000);
synchronized (this.t) {
this.t.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thread.wait() call make sense inside a code that synchronizes on Thread.class object. I don't think it's what you meant.
You ask
How can I make a thread wait until it will be notified?
You can make only your current thread wait. Any other thread can be only gently asked to wait, if it agree.
If you want to wait for some condition, you need a lock object - Thread.class object is a very bad choice - it is a singleton AFAIK so synchronizing on it (except for Thread static methods) is dangerous.
Details for synchronization and waiting are already explained by Tom Hawtin.
java.lang.IllegalMonitorStateException means you are trying to wait on object on which you are not synchronized - it's illegal to do so.
Not sure if this will help somebody else out or not but this was the key part to fix my problem in user "Tom Hawtin - tacklin"'s answer above:
synchronized (lock) {
makeWakeupNeeded();
lock.notifyAll();
}
Just the fact that the "lock" is passed as an argument in synchronized() and it is also used in "lock".notifyAll();
Once I made it in those 2 places I got it working
I received a IllegalMonitorStateException while trying to wake up a thread in / from a different class / thread. In java 8 you can use the lock features of the new Concurrency API instead of synchronized functions.
I was already storing objects for asynchronous websocket transactions in a WeakHashMap. The solution in my case was to also store a lock object in a ConcurrentHashMap for synchronous replies. Note the condition.await (not .wait).
To handle the multi threading I used a Executors.newCachedThreadPool() to create a thread pool.
Those who are using Java 7.0 or below version can refer the code which I used here and it works.
public class WaitTest {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void waitHere(long waitTime) {
System.out.println("wait started...");
lock.lock();
try {
condition.await(waitTime, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
System.out.println("wait ends here...");
}
public static void main(String[] args) {
//Your Code
new WaitTest().waitHere(10);
//Your Code
}
}
For calling wait()/notify() on object, it needs to be inside synchronized block. So first you have to take lock on object then would be possible to call these function.
synchronized(obj)
{
obj.wait()
}
For detailed explanation:
https://dzone.com/articles/multithreading-java-and-interviewspart-2
wait(), notify() and notifyAll() methods should only be called in syncronized contexts.
For example, in a syncronized block:
syncronized (obj) {
obj.wait();
}
Or, in a syncronized method:
syncronized static void myMethod() {
wait();
}

Difference between synchronized(this) and few synchronized methods of class

In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?
Code in the book:
public class IntBuffer
{
private int index;
private int[] buffer = new int[8];
// Function called by producer thread
public synchronized void produce(int num) {
while(index == buffer.length - 1) {
try { wait();}
catch(InterruptedException ex) {}
}
buffer[index++] = num;
notifyAll();
}
// Function called by consumer thread
public synchronized int consume() {
while(index == 0) {
try { wait();}
catch(InterruptedException ex) {}
}
int ret = buffer[--index];
notifyAll();
return ret;
}
}
No, they are the same.
private synchronized void foo() {}
private void foo2() {
synchronized(this){
}
}
They will do the exact same as both monitor the instance which they are called from.
A good tutorial can be found in the blog of Jakob Jenkov
http://tutorials.jenkov.com/java-concurrency/synchronized.html#java-synchronized-example
Happy coding!
Using synchronized(this) requires the calling thread to take the same lock as when it calls an instance method using the synchronized modifier on the method. There are some differences in what bytecode is generated but that's a pretty low-level distinction.
The purpose of the synchronized keyword is to protect shared state from concurrent access. The produce and consume methods use the same internal state so it's reasonable that they are both protected by the same lock.
The posted code looks well-done, my only nitpick is i would let the methods throw InterruptedException instead of catching it. Both the produce and consume methods require the calling thread to acquire the lock on the instance that the method is being called on.
Q: Is this different than using synchronized(this) inside each of those methods ?
A : No, it is not different, by using block (synchronize(this) you can synchronize just part of your code, not the whole method.
For example :
public void m1(){
// some code
synchronized(this){
// thread-safe code
}
Is this different than using synchronized(this) inside each of those methods?
No.
The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion.
That's not correct. Both methods are synchronized on the same object, so only one thread can be in either method, unless wait() is called, which it is, which releases the lock.
The methods produce and consume should both entirely be synchronized right?
Yes, and you said they are. Unclear what you are asking here.

Alternative to Lock.tryLock() in Java 1.4

I would like to know if there is an existing alternative or how to implement the semantics of java.util.concurrent.locks.Lock#tryLock() before Java 5. That is the possibility to back off immediately if the lock is already held by another thread.
If you need a Lock supporting a tryLock operation, you can’t use the intrinsic locking facility of Java. You have to implement your own Lock class which maintains the required state, i.e. an owner Thread and a counter and might use the intrinsic locking for its implementation of the thread-safe updates and blocking (there are not much alternatives in older Java versions).
A very simple implementation might look like this:
public final class Lock {
private Thread owner;
private int nestCount;
public synchronized void lock() throws InterruptedException {
for(;;) {
if(tryLock()) return;
wait();
}
}
public synchronized boolean tryLock() {
Thread me=Thread.currentThread();
if(owner!=me) {
if(nestCount!=0) return false;
owner=me;
}
nestCount++;
return true;
}
public synchronized void unlock() {
if(owner!=Thread.currentThread())
throw new IllegalMonitorStateException();
if(--nestCount == 0) {
owner=null;
notify();
}
}
}
Note that the intrinsic lock of the Lock instance enforced by the synchronized methods is hold for a very short time only. The threads will either return immediately or go into the wait state which implies releasing the lock as well. Hence the tryLock will exhibit the desired behavior, though the Java 5 and newer equivalent will likely be more efficient. (The Java 5 and newer implementation of synchronized is more efficient as well…)

How do I create a Lock (concurrent.locks.Lock) in Android?

This must be really obvious, but I can't spot the answer. I need to put a lock around a variable to ensure that a couple of race-hazard conditions are avoided. From what I can see, a pretty simple solution exists using Lock, according to the android docs:
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
}
finally {
l.unlock();
}
So far, so good. However, I can't make the first line work. It would seem that something like:
Lock l = new Lock();
Might be correct, but eclipse reports, "Cannot instantiate the type Lock" - and no more.
Any suggestions?
If you're very keen on using a Lock, you need to choose a Lock implementation as you cannot instantiate interfaces.
As per the docs
You have 3 choices:
ReentrantLock
Condition This isn't a Lock itself but rather a helper class since Conditions are bound to Locks.
ReadWriteLock
You're probably looking for the ReentrantLock possibly with some Conditions
This means that instead of Lock l = new Lock(); you would do:
ReentrantLock lock = new ReentrantLock();
However, if all you're needing to lock is a small part, a synchronized block/method is cleaner (as suggested by #Leonidos & #assylias).
If you have a method that sets the value, you can do:
public synchronized void setValue (var newValue)
{
value = newValue;
}
or if this is a part of a larger method:
public void doInfinite ()
{
//code
synchronized (this)
{
value = aValue;
}
}
Just because Lock is an interface and can't be instantiated. Use its subclasses.

Categories

Resources