I have an application in java that uses two different threads.And for sharing data between these two threads I wanna use a Singleton class.
The data that needs to be shared between threads is (Latitude,Longitude).
And here is my problem:What should I use for storing this data in the Singleton class?
Some Lists..?
And if you can also provide an example it would be fantastic.Thank you!
Is this Singleton ????How could I make it non-Singleton
EDIT:
I have a java app that does the following thing:
1.The first thread(which is a ThreadPool)-which I believe will also write in the BlockingQ
Listens to one port for incoming connections from five different users
Let’s call them :
user1
user2
user3
user4
user5
each of them sending GPS data.
2.The second thread-which will read from the BlockingQ.
In the same time my java app listens to a second port where waits for another client(different from those who send GPS data) to connect to it.
Now…I have a second app that connects to the java app that I’ve just described it.
In this second app I have a list user1…user5 and depinding on which item I will choose(user1…5) I have to receive the correct data from there.
So now….how do I write/read the data in the BlockingQ in order for me to receive the correct data???
I think what you are trying to achieve is a Producer Consumer Pattern. You should use a
BlockingQueueand an immutableCoordinateobject with Latitude and Longitude for that.Coordinateshould only have the two fields Longitude and Latitude that are bothfinalfields and can only be set with the constructor. This way you can make sure, that you don’t have any race conditions or change the fields by accident with the wrong thread.BlockingQueuedoes not store the data permanently, so only if you need to do that you could create a Singleton.The better solution would be to create a class like ShareData and just pass them to the two threads so you can save yourself some time creating a threadsafe Singleton. This could look like this:
The
Coordinateclass should look like this and is threadsafe, since it is immutable and cannot change its value.