Is this way of passing objects between threads safe under JMM? - java

I'm looking for a safe way to pass an object from a background thread to the UI thread. Does the code below do it safely?
// on background thread
final HugeObject object = constructHugeObjectFromDatabaseAndNetwork();
uiThreadHandler.post(new Runnable() {
public void run() { doSomethingWithObject(object); }
});
I.e., do JMM rules allow the object to be in fact partially constructed during the doSomethingWithObject call? Also, how relevant JMM is for Android and its virtual machine?

Yes - handlers are there to do exactly that: exchange information across threads in a thread safe way.
In practice, handlers use a thread safe (synchronized) message queue to post messages, creating a happens-before relationship between your code and whatever will happen on the UI with your object.
Recent versions of android comply with the JMM.

It depends on the implementation of post(). There's no memory barrier in the quoted code, so it generally wouldn't be thread safe. But, in practice, it becomes very difficult to have one thread waiting for a task to run without using a barrier to exchange objects. That is likely to be the case here, and if so, it will be safe.

Related

Is it possible for threads not sharing a common resource to notify based on thread-id/name?

If I know the ID of the thread I wish to notify, and share no other common resource, can I notify it?
Both the threads have been initiated by the same application.
the other thread went into wait by using Thread.currentThread().wait(500);
Yes - but you must stop using wait.
The technique is to maintain a Map<String,BlockingQueue> containing a queue for each thread that is running. The String key is the thread ID.
When you want the thread to pause, use queue.poll(long, TimeUnit) instead of wait. You merely need to put something in the queue to wake up the thread and obviously if you know the ID of the thread you can easily obtain it's Queue from the Map.
As long as it's in the same ThreadGroup, you can iterate through all the threads using Thread.enumerate() and find the given thread by it's id and do the usual synchronize and .notify().
This provides additional ways of iterating over all the Threads.
You would want to notify only threads waiting on the same lock. Don't use current thread object as the lock, it doesn't help. Once a thread has been awakened you need to check against a condition to guard against spurious wake ups. if you are sure that there is only one thread waiting on the lock then calling notify on the lock object should wake up the waiting thread.
You can give the threads some common object on which to communicate, and so you won't have to rely on thread names.
Example:
class Notifier extends Thread {
private final Object common;
Notifier(Object common) { this.common = common; }
public void run() {
// do work
synchronized (common) { common.notify(); }
}
}
class Waiter extends Thread {
private final Object common;
Waiter(Object common) { this.common = common; }
public void run() {
// do work
synchronized (common) { common.wait(TIMEOUT); }
}
}
A better yet approach would be to use a java.util.concurrent.CountDownLatch for the same effect.
Yes it is possible. But it is ugly and potentially fragile and/or inefficient.
As #nos says you can use Thread.enumerate() to enumerate the Thread objects in your ThreadGroup, test each one until you can find the thread with the expected name and/or thread id. That is clearly inefficient if there are lots of threads in the group.
The fragility arises in the following respects:
The thread with a given name or id may no longer exist.
There could be multiple threads with the same name.
Thread id values will eventually be recycled when enough threads have been and gone.
and on the synchronization side,
There could conceivably be other parts of your application (or library code) that synchronize using wait/notify on the Thread objects, and you could get unwanted notifies as a result.
On some Java platforms, (at least historically) it is possible to get spontaneous notifications ... so using wait / notify without testing a shared condition variable might result in bad synchronization.
IMO, you would be better off creating (private) objects that you can wait/notify on, and using proper condition variables. Or it that is unappealing, use one of the existing higher level concurrency class for synchronizing.

Threadsafe vs Synchronized

I'm new to java.
I'm little bit confused between Threadsafe and synchronized.
Thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occurring.
Where as Synchronized means only one thread can operate at single time.
So how they are related to each other?
The definition of thread safety given in Java Concurrency in Practice is:
A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
For example, a java.text.SimpleDateFormat object has internal mutable state that is modified when a method that parses or formats is called. If multiple threads call the methods of the same dateformat object, there is a chance a thread can modify the state needed by the other threads, with the result that the results obtained by some of the threads may be in error. The possibility of having internal state get corrupted causing bad output makes this class not threadsafe.
There are multiple ways of handling this problem. You can have every place in your application that needs a SimpleDateFormat object instantiate a new one every time it needs one, you can make a ThreadLocal holding a SimpleDateFormat object so that each thread of your program can access its own copy (so each thread only has to create one), you can use an alternative to SimpleDateFormat that doesn't keep state, or you can do locking using synchronized so that only one thread at a time can access the dateFormat object.
Locking is not necessarily the best approach, avoiding shared mutable state is best whenever possible. That's why in Java 8 they introduced a date formatter that doesn't keep mutable state.
The synchronized keyword is one way of restricting access to a method or block of code so that otherwise thread-unsafe data doesn't get corrupted. This keyword protects the method or block by requiring that a thread has to acquire exclusive access to a certain lock (the object instance, if synchronized is on an instance method, or the class instance, if synchronized is on a static method, or the specified lock if using a synchronized block) before it can enter the method or block, while providing memory visibility so that threads don't see stale data.
Thread safety is a desired behavior of the program, where the synchronized block helps you achieve that behavior. ​There are other methods of obtaining Thread safety e.g immutable class/objects. Hope this helps.
Thread safety: A thread safe program protects it's data from memory consistency errors. In a highly multi-threaded program, a thread safe program does not cause any side effects with multiple read/write operations from multiple threads on shared data (objects). Different threads can share and modify object data without consistency errors.
synchronized is one basic method of achieving ThreadSafe code.
Refer to below SE questions for more details:
What does 'synchronized' mean?
You can achieve thread safety by using advanced concurrency API. This documentation page provides good programming constructs to achieve thread safety.
Lock Objects support locking idioms that simplify many concurrent applications.
Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.
ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.
Related SE question:
Synchronization vs Lock
Synchronized: only one thread can operate at same time.
Threadsafe: a method or class instance can be used by multiple threads at the same time without any problems occurring.
If you relate this question as, Why synchronized methods are thread safe? than you can get better idea.
As per the definition this appears to be confusive. But not,if you understand it analytically.
Synchronized means: sequentially one by one in an order,Not concurrently [Not at the same time].
synchronized method not allows to act another thread on it, While a thread is already working on it.This avoids concurrency.
example of synchronization: If you want to buy a movie ticket,and stand in a queue. you will get the ticket only after the person in front of you get the ticket.
Thread safe means: method becomes safe to be accessed by multiple threads without any problem at the same time.synchronized keyword is one of the way to achieve 'thread safe'. But Remember:Actually while multiple threads tries to access synchronized method they follow the order so becomes safe to access. Actually, Even they act at the same time, but cannot access the same resource(method/block) at the same time, because of synchronized behavior of the resource.
Because If a method becomes synchronized, so this is becomes safe to allow multiple threads to act on it, without any problem. Remember:: multiple threads "not act on it at the same time" hence we call synchronized methods thread safe.
Hope this helps to understand.
After patiently reading through a lot of answers and not being too technical at the same time, I could say something definite but close to what Nayak had already replied to fastcodejava above, which comes later on in my answer but look
synchronization is not even close to brute-forcing thread-safety; it's just making a piece of code (or method) safe and incorruptible for a single authorized thread by preventing it from being used by any other threads.
Thread safety is about how all threads accessing a certain element behave and get their desired results in the same way if they would have been sequential (or even not so), without any form of undesired corruption (sorry for the pleonasm) as in an ideal world.
One of the ways of achieving proximity to thread-safety would be using classes in java.util.concurrent.atomic.
Sad, that they don't have final methods though!
Nayak, when we declare a method as synchronized, all other calls to it from other threads are locked and can wait indefinitely. Java also provides other means of locking with Lock objects now.
You can also declare an object to be final or volatile to guarantee its availability to other concurrent threads.
ref: http://www.javamex.com/tutorials/threads/thread_safety.shtml
In practice, performance wise, Thread safe, Synchronised, non-thread safe and non-synchronised classes are ordered as:
Hashtable(slower) < Collections.SynchronizedMap < HashMap(fastest)

Thread with custom states

Is it possible in Java (Android) to implement a customized version of a Thread which carries its own States?
What I mean is:
While ThreadA is in Running state, it still can be polled by ThreadB that asks for its state
e.g.
ThreadA.getState();
It is possible to modify the states values to some custom ones? So as to implement a sort of basic communication system between those two threads?
Thanks.
Yes that is possible. I used this a lot in my previous projects, all what you need is to extend the Thread class.
public class StateThread extends Thread{
String state = "ThreadState";
public synchronized void setState(String newState){
state = newState;
}
public synchronized String getState(){
return state;
}
#override
public void run(){
// Do stuff and update state...
}
}
Yes, it is possible to perform this task.
Is it a good design? I don't think so.
There are other means to perform communication between threads -
For example, you should use a queue with a Producer/Consumer pattern.
I am sure that Android, as JavaSE supports thread local - you can use it in order to manage local thread data (including states) (maybe in combination with a queue that will get "operations" to change the state managed by a thread
If you do decide to go for the solution of having setState and getState methods, at least consider using the ReaderWriterLock to optimize your locking
Threads state is maintained by the Virtual Machine. VM uses the state to monitor and manage the actual thread.
That's why there is no mechanism to modify the state of the Thread. There is no setState function that allows to set your custom state.
For your application purpose, you can define your own instance variables by extending Thread but that cannot alter Thread's state in any way.
Synchronizing with shared data is not very useful for determining the 'state' of a thread - the thread writes its state as 'healthy', then gets stuck - the monitor thread then checks the state and finds it healthy.
Monitoring the 'state' should mean making the checked thread do something, not just looking directly at some shared object.
If you have a message-passing design, (as suggested by zaske), you can pass around a 'state record' on the input queue of evey thread, asking it to record its state inside and pass it on to the next thread. The 'monitor' thread waits for the record to come back, all filled in. If it does not get it in a resonable time, it could log what it has got - it keeps a reference to the state record object, so it could see which thread has not updated its state. It could, perhaps, fail to feed a watchdog timer.

What does Thread-Safe mean in java or when do we call Thread-Safe?

I am not understanding this concept in any manner.
public class SomeName {
public static void main(String args[]) {
}
}
This is my class SomeName. Now what is thread here.
Do we call the class as a thread.
Do we call this class as thread when some other object is trying to access its method or members?
Do we call this class as thread when some other object is trying to access this object?
What does it mean when we call something in java as thread-safe ?
Being thread-safe means avoiding several problems. The most common and probably the worst is called threadlock. The old analogy is the story of the dining philosophers. They are very polite and will never reach out their chopsticks to take food when someone else is doing the same. If they all reach out at the same time, then they all stop at the same time, and wait...and nothing ever happens, because they're all too polite to go first.
As someone else pointed out, if your app never creates additional threads, but merely runs from a main method, then there is only one thread, or one "dining philosopher," so threadlock can't occur. When you have multiple threads, the simplest way to avoid threadlock is to use a "monitor", which is just an object that's set aside. In effect, your methods have to obtain a "lock" on this monitor before accessing threads, so there are no collisions. However, you can still have threadlock, because there might be two objects trying to access two different threads, each with its own monitor. Object A has to wait for Object B to release its lock on monitor object 1; Object B has to wait for Object A to release its lock on monitor object 2. So now you're back to threadlock.
In short, thread safety is not terribly difficult to understand, but it does take time, practice and experience. The first time you write a multi-threaded app, you will run into threadlock. Then you will learn, and it soon becomes pretty intuitive. The biggest caveat is that you need to keep the multi-threaded parts of an app as simple as possible. If you have lots of threads, with lots of monitors and locks, it becomes exponentially more difficult to ensure that your dining philosophers never freeze.
The Java tutorial goes over threading extremely well; it was the only resource I ever needed.
You might want to think of thread as CPU executing the code that you wrote.
What is thread?
A thread is a single sequential flow of control within a program.
From Java concurrency in practice:
Thread-safe classes encapsulate any needed synchronization so that
clients need not provide their own.
At any time you have "execution points" where the JVM is running your code stepping through methods and doing what your program tells it to do.
For simple programs you only have one. For more complex programs you can have several, usually invoked with a new Thread().run or an Executor.
"Thread-safe" refers to that your code is written in such a way that one execution point cannot change what another execution point sees. This is usually very desirable as these changes can be very hard to debug, but as you only have one, there is not another so this does not apply.
Threads is an advanced subject which you will come back to later, but for now just think that if you do not do anything special with Threads or Swing this will not apply to you. It will later, but not now.
Well, in your specific example, when your program runs, it has just 1 thread.
The main thread.
A class is thread safe when an object of that class can be accessed in parallel from multiple threads (and hence from multiple CPUs) without any of the guarantees that it would provide in a single threaded way to be broken.
You should read first about what exactly threads are, for instance on Wikipedia, which might make it then easier to understand the relation between classes and threads and the notion of threadsafety.
Every piece of code in Java is executed on some thread. By default, there is a "main" thread that calls your main method. All code in your program executes on the main thread unless you create another thread and start it. Threads start when you explicitly call the Thread.start() method; they can also start implicitly when you call an API that indirectly calls Thread.start(). (API calls that start a thread are generally documented to do so.) When Thread.start() is called, it creates a new thread of execution and calls the Thread object's run() method. The thread exits when its run() method returns.
There are other ways to affect threads, but that's the basics. You can read more details in the Java concurrency tutorial.

Is there a way to stabilize direct communication between threads in java?

We have a system in which each thread (there can be dozens of them) works as an individual agent.
It has its own inner variables and objects, and it monitors other threads' objects as well as its own) in order to make decisions.
Unfortunately the system is deadlocking quite often.
Going through java tutorial (http://download.oracle.com/javase/tutorial/essential/concurrency/index.html) and through other topics here at stackoverflow, I managed to avoid some of these deadlocks by synchronizing the methods and using a monitor, as in:
Producer->monitor->Consumer.
However, not all communication between threads can be modeled like this. As I've mentioned before, at a given time one thread must have access to the objects (variables, lists, etc) of the other threads.
The way it's being done now is that each thread has a list with pointers to every other thread, forming a network. By looping through this list, one thread can read all the information it needs from all the others. Even though there is no writing involved (there shouldn't be any problems with data corruption), it still deadlocks.
My question is: is there an already known way for dealing with this sort of problem? A standard pattern such as the monitor solution?
Please let me know if the question needs more explanation and I'll edit the post.
Thank you in advance!
-Edit----
After getting these answers I studied more about java.concurrency and also the actor model. At the moment the problem seems to be fixed by using a reentrant lock:
http://download.oracle.com/javase/tutorial/essential/concurrency/newlocks.html
Since it can back out from an attempt to acquire the locks, it doesn't seem to have the problem of waiting forever for the them.
I also started implementing an alternate version following the actor model since it seems to be an interesting solution to this case.
My main mistakes were:
-Blindly trusting synchronize
-When in the tutorial they say "the lock is on the object" what they actually mean is the whole object running the thread (in my case), not the object I would like to access.
Thank you all for the help!
Look at higher-level concurrency constructs such as the java.util.concurrent package and the Akka framework/library. Synchronizing and locking manually is a guaranteed way to fail with threads in Java.
I would recommend to apply Actor model here (kind of share nothing parallelism model).
Using this model means that all your thread don't interrupt each other explicitely and you don't need to do any synchronization at all.
Instead of making synchronization you'll use messages. When one Actor (thread) needs to get info about another Actor, it just asynchronously send a correspondent message to that Actor.
Each Actor can also respond to messages of certain types. So, when a new message comes, Actor analyses it and sends a response (or does any other activity). The key point here is that processing of incoming messages is being done synchronously (i.e. it's the only point where you need the simplest way of synchronization - just mark the method which processes messages with synchronized modifier).
When one thread needs to synchronize with many other threads in a manner that a deadlock may occur, greedily acquire all your resources, and in the case that you can't acquire a single resource out of the set, release all resources and try again.
It's an algorithm based on the dining philosophers problem.
One important thing to remember is, that you have to aquire all locks in a consistent order across all your threads, in order to avoid the following situation:
Thread 1 Thread 2
acquire A acquire B
acquire B acquire A
One way to do it would be to have only objects used as locks, which can be ordered.
class Lock {
static final AtomicLong counter = new AtomicLong()
final long id = counter.incrementAndGet();
}
which must be used like
if (lock1.id < lock2.id) {
synchronized (lock1) {
synchronized (lock2) {
...
}
}
} else {
synchronized (lock2) {
synchronized (lock1) {
...
}
}
}
Obviously, this becomes tedious soon, in particular, the more locks are involved. Using explicit ReentrantLocks might help, as it more easily allows all that stuff to be factored out into a generic “grab multiple locks method“.
Another strategy, which might be applicable for your problem, would be "hand-over-hand" locking. Consider
class Node {
final ReentrantLock lock = new ReentrantLock();
Node previous;
Node next;
}
with a traversal operation like
Node start = ...;
Node successor;
start.lock.lock();
try {
successor = start.next;
successor.lock.lock();
} finally {
start.lock.unlock();
}
// Here, we own the lock on start's next sibling. We could continue
// with this scheme, traversing the entire graph, at any time holding
// at most two locks: the node we come from and the node we want to
// go to.
The above scheme still requires, that the locks are acquired in a consistent order across all threads. This means, that you can only every traverse the graph either in "forward" direction (i.e., following the thread of next pointers) or "backward" direction (going via previous). As soon as you start using both at random, things become prone to deadlocks again. This is potentially true also, if you make arbitrary changes to the graph structure, changing the positions of nodes.
How about actor model? Shortly speaking, in actor-based programming all threads work as independent actors (or, as you said, agents). Communication is done via messages. Each actor has its own message queue and processes these messages one by one. This model is implemented in a Scala programming language, and one of its frameworks - Akka - may be used from Java.
What I do is use ExecutorServices for each Thread Pool. When you want another thread to do work, you pass it copies (or immutable data) of all the information it will need. This way you have state which is local to a thread or thread pool and you have information which is passed to another thread. i.e. you never pass mutable state to another thread. This avoid the need to ever lock another threads data.

Categories