I have a one String which will be access by four different threads in unpredicatable order.
String s = "When value is";
Now above string s will be updated by four different threads through Java Swing EDT. I have two JCombobox and two JTextField. Inside event handler of these components I will have to update above string.
For e.g.
when textfield focus changes string should be “When value is X”
when combo changes string should be “When value is less than X and Y”
So like above four thread will be changing one string. If I dont control them output is unexpected. What is the best way to solve this. I can use join() or may go for volatile but it will make code complex.
Please share your ideas. Thanks in advance.
Firstly, a
Stringis immutable so it cannot be updated. Another object, such as a Swing component, may however hold a reference to aString, and this reference can be updated to point to a differentString. This is what normally happens when text is updated in a GUI.If you have four different threads that need to update a Swing component, e.g. to display a different
String, they should do it by queuing a task to be run on the single Event Dispatching Thread using theSwingUtilitiesmethodsinvokeLaterorinvokeAndWait, e.g.Or in a more sophisticated application you might want to update a domain object, which would then need to be thread safe, from each of these four threads, and then separately update the Swing component on the EDT. Creating thread-safe code is not easy, in my opinion. I highly recommend the book Java Concurrency in Practice, but the main point is to ensure that only one thread at a time carries out any operation that involves the object in question being temporarily in an inconsistent state. This is sometimes possible by suitable use of existing thread-safe classes and atomic operations, but may require the use of a lock, typically through
synchronizedmethods or blocks.Of course, none of this is relevant if, as it now appears, you do not have four threads at all but only four event handlers called on the EDT.