I am doing a project in which I must make threads communicate.
For instance
I have two thread arrays, c[100] and e[10]. (customers and employees)
Once a customer say c[3] acquires a semaphore to let it speak with one of the employees say employee e[5], how do I associate the Customer object represented by the thread c[3] to the Employee object e[5], and let them pass info back and forth?
There are multiple techniques for allowing threads to communicate information. The simplest way is a mutex over shared state. One of the most classically scalable ways is message queues. The way that you need to use depends on the statement of your homework assignment.
In general, protect shared state with your synchronization primitive (be it a mutex or semaphore or whatever), and let unshared state run normally. If you have employees and customers, perhaps they communicate via a "mail slot" that they share. Protect that mail slot with your semaphore to prevent one from trying to read while the other is writing (or vice-versa), and you'll have the primary strategy that you need.
Another ways is by message passing. For instance you can one object subscribe to a listener for events. When the other thread causes a change, then it let all listeners know of the event and all listeners get notified of the change.
Another possible solution is to use piped streams or piped reades (i.e. PidedInputStrean, PipedOutputStream, PipedReader, PipedWriter). In this scheme, one thread writes in one side of the pipe, and the other thread reads the other side.
And I am pretty sure there are several other ways to do it.
Related
I have an Actor that - in its very essence - maintains a list of objects. It has three basic operations, an add, update and a remove (where sometimes the remove is called from the add method, but that aside), and works with a single collection. Obviously, that backing list is accessed concurrently, with add and remove calls interleaving each other constantly.
My first version used a ListBuffer, but I read somewhere it's not meant for concurrent access. I haven't gotten concurrent access exceptions, but I did note that finding & removing objects from it does not always work, possibly due to concurrency.
I was halfway rewriting it to use a var List, but removing items from Scala's default immutable List is a bit of a pain - and I doubt it's suitable for concurrent access.
So, basic question: What collection type should I use in a concurrent access situation, and how is it used?
(Perhaps secondary: Is an Actor actually a multithreaded entity, or is that just my wrong conception and does it process messages one at a time in a single thread?)
(Tertiary: In Scala, what collection type is best for inserts and random access (delete / update)?)
Edit: To the kind responders: Excuse my late reply, I'm making a nasty habit out of dumping a question on SO or mailing lists, then moving on to the next problem, forgetting the original one for the moment.
Take a look at the scala.collection.mutable.Synchronized* traits/classes.
The idea is that you mixin the Synchronized traits into regular mutable collections to get synchronized versions of them.
For example:
import scala.collection.mutable._
val syncSet = new HashSet[Int] with SynchronizedSet[Int]
val syncArray = new ArrayBuffer[Int] with SynchronizedBuffer[Int]
You don't need to synchronize the state of the actors. The aim of the actors is to avoid tricky, error prone and hard to debug concurrent programming.
Actor model will ensure that the actor will consume messages one by one and that you will never have two thread consuming message for the same Actor.
Scala's immutable collections are suitable for concurrent usage.
As for actors, a couple of things are guaranteed as explained here the Akka documentation.
the actor send rule: where the send of the message to an actor happens before the receive of the same actor.
the actor subsequent processing rule: where processing of one message happens before processing of the next message by the same actor.
You are not guaranteed that the same thread processes the next message, but you are guaranteed that the current message will finish processing before the next one starts, and also that at any given time, only one thread is executing the receive method.
So that takes care of a given Actor's persistent state. With regard to shared data, the best approach as I understand it is to use immutable data structures and lean on the Actor model as much as possible. That is, "do not communicate by sharing memory; share memory by communicating."
What collection type should I use in a concurrent access situation, and how is it used?
See #hbatista's answer.
Is an Actor actually a multithreaded entity, or is that just my wrong conception and does it process messages one at a time in a single thread
The second (though the thread on which messages are processed may change, so don't store anything in thread-local data). That's how the actor can maintain invariants on its state.
I have created a number of threads. I know each threads name(suppose through an alien mechanism I set name of thread.) Now I am inside a thread and want to send a message to another thread.
I am trying to code a simulator of Pastry and Chord protocol. I can not have a number of distributed nodes, so I have created a number of threads. Now I want each thread send and receive messages from one another. I have set each nodes name as its IP(a randomly generated number). Now I do not know how to send a message from one node to another. Please tell me how to send a message from one thread to another if you know another threads name.
I would suggest some kind of a message system. The easiest way would be to create a thread-safe FIFO and pass it into each thread. If you want to send messages directly to each different thread, make a "Topic" for each thread.
Don't try to hack something in using the thread name, it'll just constrain you later.
Pasted from comment so I can parse it:
private static BlockingQueue[] queue;
private static int queueNum = 0;
public static void newQueue(String ip)
{
queue[queueNum] = new ArrayBlockingQueue(1024);
try{ queue[queueNum].put(ip); }
catch (InterruptedException e){e.printStackTrace(); }
queueNum++;
}
Oh, I see your problem. You never assign BlockingQueue a value. Try changing that line to:
private static BlockingQueue[] queue=new BlockingQueue[10];
That will allow you 10 queues.
I'd also suggest that instead of an array you use a HashMap so you can name, add and delete queues at will. Instead of being queue[2] you'll be addressing queue.get("Thread1Queue") or something more descriptive.
Note response to comments:
A HashMap can generally replace an array, it's lookup is nearly as quick but it uses anything for an index instead of numbers--Strings, enums, Objects, whatever you want (as long as it has the hash and equals methods overriden), but usually strings.
So if you are storing a bunch of queues, and you want to name them specifically, you can say:
HashMap queues=new HashMap();
queues.put("queue1", new ArrayBlockingQueue(1024));
queues.put("queue2",new ArrayBlockingQueue(1024));
...
Then whenever you want to access one you can use:
queues.get("queue1").put(new ThingToAddToArrayBlockingQueue())...
to put a "Thing to add" to queue1.
If you just want a "Bunch" of them and don't need to know which is which (Just a collection of threads that can be fed generic taskss) there are specific collections/patterns for that in the concurrent package.
The usual way to communicate between threads is by passing an object to each thread which then allows to communicate between them. Keep in mind that all fields and methods of that object which are accessed by more than one thread should be synchronized.
But when you want to simulate a network protocol, then why not go all the way and use network sockets for interprocess communication? Just make each thread listen to a different socket on 127.0.0.1.
If you want to send messages and then have them processed by other threads you need a shared object (queue, map etc.) into which threads can pump messages. Receiving threads must check for incoming messages, pull them and do the necessary processing.
I am working on creating a chat client based on UDP. The main structure is that there is a server where clients register and where clients can also request to form a connection with another client that is registered with the server. The clients are structures as follows using pseudo code:
public UDPClient() {
// Create datagram socket
// Execute RECEIVE thread using datagram socket above
// Execute SEND thread using datagram socket above
}
The idea is to have the send and receive executing on separate threads so I don't get blocked I/O on the receive. Both of these threads have loops within their run methods that allow you to continually send and receive messages. The problem I have is this. If a message comes in on the RECEIVE thread that changes how my SEND should be executing, how do I communicate this to the SEND thread? Do I have to shoot a datagram off to myself or can I communicate this in the code somehow?
Assuming boths threads have no reference to each other, create a third singleton class, which both read/send threads (classes) reference, that has a volatile member field to store the state data you want shared and which has synchronized access.
The volatile keyword, combined with synchronized access, guarantees that a change made to the field by one thread will be seen by another thread. Without this, changes may not be visible due to the java memory model specification.
Edited:
Following "separation of concerns" design guideline, it would be better to not have the read/send threads know about each other and to use a third class to orchestrate their activities/behaviour. Add methods to your read/send classes to stop(), start() etc and call these from the other class.
Using a separate class would also allow:
Behaviour control by other means, for example a "stop sending" button on an admin web page
Allowing multiple threads of each type, yet still having proper control through a central point, perhaps using a pool of such threads (without a separate class, you would have a many-to-many nightmare and lots of code that has nothing to do with the job at hand: ie ending and receiving)
Easier testing of your worker classes, because they do less and are more focused
porting/embedding them stand-alone for other uses
your SEND thread should have public (accesible) method (synchronized if possible) that you should be able to access from your RECEIVE thread. You could use this method to create a boolean flag, string message, etc. that you should always read before you .send(yourPacket); from your SEND thread.
Have a member variable in your READ method that your code can read from and change the SEND method based on that variable.
I'm wondering what the best way to differentiate between server connections is. My client connection has their own thread, which I aim to put in a group with 2 other users (3 in total) kind of like a lobby.
I'm currently looking at ThreadGroup and trying to assign every 3 users to a thread group however I'm not sure this is even remotely correct, as I cannot see any clear way of then finding which users are in which thread group.
If someone could point me in the right direction it would be very helpful.
I wouldn't use a ThreadGroup for the purposes of classifications of threads. A ThreadGroup allows threads to do operations and get information about a collection of threads. I don't think you need this functionality.
I'd use one of the Collection classes to group your user or game threads together. The Collection could be inside of the custom class which you use to store the game state.
If you need to find the games that need more members then I'd have a Collection of games that need members that you add and delete from as users login/out.
is there any way two threads within the same process can communicate without knowing anything about each other's interface ?
basically, one thread is a STOMP server, the other is a client. they're supposed to communicate in a direct manner (not via a socket) and it should be independent of the implementation so i can't assume either of the threads is waiting for messages on some common message queue.
what i'm looking for is some kind of a built-in mechanism in java that allows threads within the same process to communicate.
is there such a mechanism ? and if not, is there any other way to approach this ?
You can use a concurrent message queue where threads can post and receive messages. Instead of knowing the other's thread interface, now each thread must be able to create own messages and understand the messages of other threads.
By using a distinct interface for these messages, this is rather easy. And as a bonus, there is a wide range of queues for concurrent access available, so you can pick the queue that fits most to your scenario.
Well, you can have a third thread to act as a message board. But then you'd have to hope that the two threads can agree on a protocol before hand. It would also be rather slow.
Can you provide more details/examples? What do you mean by "communicate" exactly?
There are a few ways I can think of for doing this, shared (global) state, PipedInputStream/PipedOutputStream etc. But the details will depend on what you're trying to do.