My program will use threads, but some variables like a collection of links/pages, information about queries (if is updating or none) and some others informations(boolean fields, int fields, etc.) must be shared by the threads.
In this case, all the threads will be processing the same work, but in diferrente elements of a collection.
I want to know if there is a way to do this that don't be create a class/object only to hold these shared data.
My situation: I have a lot of pages in the database that will need to be processed, and I cant recover all in one time. In each thread, I have a boolean field to inform if the list of pages is being updated with links from database or not. Each thread has a collection with the pages to process.
In a past programa, I had similar situation. To solve it, I create a Master that hold these states and Slaves that get the infos from the Master. But now I want to do without the Master, work only with the Slaves, but I need to know if there is a way to have only one variable for all threads.
Example: if thread1 update some boolean to true, automatically, all the another threads have this boolean as true.
If you need to share data between threads you need to make sure it is shared in a synchronized fashion, i.e., that the data structures are thread safe.
Have a look at the java.util.concurrent
package. You could perhaps for instance make use of one of the BlockingQueue
implementations (ArrayBlockingQueue
, DelayQueue
, LinkedBlockingDeque
, LinkedBlockingQueue
, PriorityBlockingQueue
, SynchronousQueue
).
Regarding your comment: Have a look also at the java.util.concurrent.atomic
package. There you'll find classes such as AtomicBoolean
, AtomicInteger
, AtomicReference
and so on.
Example: if thread1 update some boolean to true, automatically, all the another threads have this boolean as true.
I'd suggest you use an AtomicBoolean
in such case. You could presumably also use an ordinary boolean
as long as you declare it volatile
(if you don't need compare-and-set operations etc that is).