I am a java beginner, I met a problem in my Restful class, I just wonder when my code is working on the Restful Class, like the thread is still working on one url request, at the same time I send another request to invoke the same Restful Class, this can work properly or not?
Now, I set a client using "GET" method. Do I need to change the method "GET" so the thread does not need to wait to the "Response"?
Any help, thanks a lot~
When you are using a framework, things are very easy. To answer your questions
How does the class behave when two simultaneous requests are made?
Each of your request will run in a separate thread. So its as simple as two different threads accessing a method simultaneously. Care must be taken not to use any shared resources (including instance variables) in the method. In that case, this becomes a bit tricky.
Do I need to change the method "GET" so the thread does not need to wait to the "Response"?
I am not sure what you mean by this. When you use HTTP, a request will always be accompanied by a response. That's how the the protocol works. Even in case of an asynchronous scenario, an immediate notional response is always returned.
Related
I'm trying to make a call by using slack's sdk client in java in order to get user's id by using the email name. The slack client returns CompletableFuture object. I can get the user_name if i use get() method but as far as i understand, it's a synchronous function and it will make the application slower. Is there another way to make this call asynchronous?
public static String lookUpUserId(String email) throws ExecutionException, InterruptedException {
CompletableFuture<UsersLookupByEmailResponse> response = slackClient.usersLookupByEmail(r -> r
.email(email));
UsersLookupByEmailResponse data = response.get();
return data.getUser().getId();
}
I tried using supplyFunc and thenApply like this but it gives an error saying 'missing return statement' although i return a value. I'm just concerned about the performance and curious if there's a a better way to handle this. Thanks
response.thenApply(r->r.getUser().getId());
Since the call returns CompletableFuture, it is alredy asynchronous. Yes, get() method is a synchronous function. Using it will NOT make the application slower, it will make application consume more memory. Asynchronous access like
response.thenApply(r->r.getUser().getId());
looks correct.
The reason of error message is that the method lookUpUserId is declared as returning String and so must have a return staement. If you want to make it asynchronous, then declare it as returning CompletableFuture<String> and add return statement
return response.thenApply(r->r.getUser().getId());
I don't know much specifically about the slack api but some information can be found in this answer with regards to housing your function in a class that implements Runnable.
Make your `CompletableFuture` in the constructor and run your gets in `run()`.
In my opinion it is a best practice to process all of your api requests off of the main thread but you should know that running some single thing in a separate thread on one line and joining that thread back on the next is only going to add a little overhead without any performance advantages. If you are processing a batch of requests you should start each on independent threads with a for loop and join them all together after.
I'm also noticing that my referenced answer doesn't really cover thread joins for retrieving your results sooo you will probably also find this informative. And if you havn't learned about object oriented programming yet that's ok! you'll be writing your own classes in no time.
Edit: Ask for code if you need it, It's better if you write it yourself.
So I've got a simple Server class that creates an instance of a Listener class for every connection made to the "server". The Listeners run on their own thread.
I get that there might be a concurrency control problem when invoking methods on the Server class that alter files/variables. But what happens if 2 Listeners try to invoke a method that e.g. only returns some information about the server status?
Can the same Server instance handle 2 calls at the same time? Or will one of the listeners have to wait till the server is done executing the method of the first caller?
Thanks for any help you guys might be able to provide!
If the method is not synchronized, the server can handle the two calls concurrently.
But if they ask for status, this means that the status changes over time. And if it changes over time, then all accesses, read and write, to this status should be done in a synchronized way. Otherwise, the listener threads could see an obsolete value of the status.
So the method should be synchronized, or the status should be an AtomicXxx value, or it should be volatile. The best, and correct solution is hard to give without seeing the code and knowing how the status is read and modified.
For something like that, that I imagine doesnt change that often, I'd consider using a ReadWriteLock - so most of the time you can have multiple threads reading the status concurrently, and only have to block them when you want to update the value.
For my game, I have it running on two servers (one for the game, one for the login system). They both need to interact with each other, and sometimes, ask questions about the state of something else in the other server.
For this example, the game server will be asking the login server if a player is trying to log in:
public boolean isLoggingIn(int accountId) {
//Form a packet to send.
int retVal = sendData();
return retVal > 0;
}
Obviously I'd use an int so information other than booleans can be returned.
My question is, how do I get this modal-style programming working? It'd work just like JFileChooser's getOpenDialog() function.
Also, I should mention that more than one thread can call this method at once.
I assume by modal, you mean trying to block all actions except one. I strongly suspect that this style will lead you into trouble. Modal interaction is a form of locking and therefore not very tolerant to hangups and disconnects and such. To make it tolerant, you need timeouts and cleanup code for cases when someone entered a mode and then nothing further happened. (i.e they closed their laptop, or the game crashed, they unplugged the network cable etc).
If I were you I would instead try to think of things in terms of authentication and authorization.
The quick answer - you need to expose methods on both servers as RMI-capable, and simply invoke methods like you described.
You might find it useful to review the official Oracle RMI tutorial: http://docs.oracle.com/javase/tutorial/rmi/index.html
Althought your design might be wrong - it's your design, and why not letting you shoot your head? ;)
Also, it's worth looking at Spring Security: http://static.springsource.org/spring-security/site/
If you use something like this on a thread that is supposed to handle other requests after it, it would hang up all those requests while it is blocking for a return value if the latency between the game and login servers is high. Certainly what you want instead is a callback so that your thread could handle other requests while it waits for a response.
I see no reason to halt execution of a thread until a value is received. If you need the value for an operation after it, then just copy all the code you have after the call you want to be "modal" in the callback. If you expect to send multiple requests while still waiting for a response, then send a unique "responseId" from the requester's side that the responder can include in its response. Use the "responseId" as a key for a Map with Runnables as values. When you receive a response, call remove on the Map with the responseId key and call run() on the Runnable value that is returned. MINA is supposed to asynchronous and should not block for a response packet.
If you have a really good reason for why you want to handle it all on the same thread, you can look into the java.util.concurrent package. I would implement it using a CountDownLatch of count 1, call await() after sending a request message, and call countDown() when you receive a response by MINA. You have to use an AtomicReference or an array of length 1 to hold the value you received in the response that you can read back into the waiting thread.
PS, you still doing MapleStory work?
I am developing a online game using red5 and flex. using RTMP connection. I used only netConnection.call. my issue is the red5 calls are not coming synchronized manor. some calls are coming to client suddenly some calls are taking time. I want to make this calls reach to client side in order. please help me any one...
Followings are my opinions, I'm sure there are far better ways to do this.
Write a class that is responsible from NetConnection.call execution. in this class, make sure that no call is made before previous one is completed. It ensures the order, but slows execution.
Write a class such that: There should be a data structure, maybe an array in its simplest form. Array contains objects that holds call order, callback function and result returned from server. When you call a method, add those calls into the array in calling order. When you receive a result from server, check the array. if previous calls are not returned yet, store them in array. If there are no previous calls pending, call your callback function any functions "called later but finished earlier that this" and remove that item from your array.
But, (there is always a but in red5), if your application needs some result in order, maybe you should consider your architecture. Most of the time, a carefully thought event handling mechanism removes the need or ordered results.
Red5 offers two application adapters which support synchronized and multithreaded access. To use them, simply extend org.red5.server.adapter.ApplicationAdapter for sync or org.red5.server.adapter.MultiThreadedApplicationAdapter in your application.
My question is about threads being queued. For my example I have one Spring context. I have a method named CalculateTax in a stateless class. A request comes in, a thread is created (tA) and it eventually enters the CalculateTax method. Within the same "time frame" another request comes in and another thread is created (tB). Now, here is what I want to understand. AFAIK tB cannot execute CalculateTax until tA has exited the method. Is this true?
As long as CalculateTax only uses local variables (i.e. declared in the method), you will not have any thread sync issues and multiple threads can call the method without a problem.
However if for some reason CalculateTax uses variables defined at the class level, and you are using the Singleton pattern (you tagged your question with "singleton", so I guess you are), you may have thread sync issues.
No it is not true if they are parallel thread, each thread is in its own stack of execution so it should be able to execute while tA is executing.
This is what Threads are for.
Generally speaking the answer is undefined. If your 'request' comes from remote client the answer depends on implementation details of the mechanism used for service exposing.
However, I'm not aware about remote communication frameworks that really make the proxy serializing the requests, i.e. that is assumed to be addressed by target service developer (e.g. its your task to provide thread-safety for the service implementation OR serialize all requests using explicit synchronization etc).