I have a java app with two different threads that does the following thing:
1.The first thread(which is a ThreadPool)- 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 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 depending on which item I will choose(user1...5) I have to receive the correct data from the user I pick. Also all this data will be stored at the second user in a DB.
Now can anyone give me a hint of how could I sha开发者_开发问答re all this data between the threads ????
I tried with Singleton classes and also with BlockingQ but seems none of these are suitable cause the data gets lost!
Concurrent execution in Java generally rely on "shared memory" so just make sure the code in the two threads share a reference to a common data structure in which they can exchange information.
All you need to make sure is that the access to this structure is done in a synchronized / thread safe manner. This can be done manually by using the synchronized
keyword (not recommended) or by using classes from the java.util.concurrent
package (recommended).
A BlockingQueue
would probably suit you well. What problems did you have when you tried this class?
The thing is that the thread that reads from the BlockingQueue needs to differentiate between the data that is written in the BlockingQ(data that comes from user1,2,3...).
I suggest you create a class for UserData
which contains both the data and which user it came from. (And store it in a BlockingQueue<UserData>
.)
How long and how much data can a BlockingQ keep????Because all this data needs to be stored in a DB in my second app...so I can afford losing any of it!!!!!!!!!!!
The BlockingQueue
is actually an interface, but all standard implementations of it (ArrayBlockingQueue
, LinkedBlockingQueue
...) can all keep an arbitrary ammount of data (i.e., are limited only by the ammount of free memory on your computer).
精彩评论