How to have a run in an Service? - java

I have implemented an service that runs in a seperate process.
This service contains a separate thread where i have a socket connection.
This thread has a run() where it is continuously sending data to the port.
My problem is after triggering the run() in the thread i don't get any contact with it anymore, i can see in the program that have open the socket that it consciously sends the data but the idea was that i while it is running i could change data that it sends for an example time.
here is my run in the external thread:
public void run()
{
if(run)
{
// Team and player names message is sent when entering in a game
setBaseMessage();
SendMessageToCOMPort(base_message + CalculateCRC(base_message));
sleep(); // waits for 100 ms
}
}
Anyone have any idea what might be wrong ?

I did not quite get your problem. It seems that you want to run a separate thread in your service which does some socket communication. Furthermore you want to be able to influence the data the thread is sending using the socket.
I have implemented an service that runs in a seperate process.
First of all, android services aren't running in a separate process or thread by default. Therefore, to run long running operations you have to develop multithreading by your self using Java threading and implementing the run method as you have done it.
Threads of a single process share the same memory. Therefore, to influence what the socket thread is doing, you can use data structures like a queue or a list which are shared among the threads. For example, you could apply the producer-consumer pattern. The producer passes data to a shared queue. The consumer consumes the data from the queue and processes it. However, be aware that you have to synchronize the access to the shared queue.
I hope I was able to clarify the issue and give you some advice to solve the issue.

Related

Thread pool when serving multiple clients with blocking methods

I am developing a webserver in java that will provide websocket communication to its' clients. I have been proposed to use a thread pool when dealing with many clients because it is a lot more time efficient than to use one thread per client.
My question is simply, will Javas ExecutorService, newFixedThreadPool be able to handle a queue of runnable tasks with thread blocking methods being called inside of them?
In other words i guess i am wondering if this thread pool is asynchronous?
The reason i am asking is that i have tried using a newFixedThreadPool with, lets say, 2 threads. Then when i connect 3 clients to the server, i can only receive commands from the first two. But i guess i could be doing something wrong, thats why i am asking.
The runnable tasks are also in an infinite while loop (only ends when client disconnects).
Well, it depends on your implementation. The easiest case is having clients keeping their thread active until the disconnect (or get kicked out because of a timeout). In this case, your thread pool isn't very efficient. I'll only re-use disconnected users' threads instead of creating new one (which is good, but not really relevant).
The second case would be activating the threads only when needed (let's say when a client sends or receives a messages). In this case, you need to remember the server-side (keeping an id for example), in order to be able to sever the thread connection when they don't need them, and re-establish it when they do. In order to do that, you must keep the sockets somewhere, but unbound to any specific thread.
I actually didn't code that myself but I don't see why it would work as this is the mechanism used for websites (i.e. HTTP protocol)

How can I simulate a Client-Server application using Java threads?

For this school assignment, I need to simulate a client server type application using Java threads (no need for sockets etc). How might I go about doing it?
I need a way to server to start and wait for clients to call it then it should return a response. The "API" in my mind was something like:
server.start()
client1.connect(server)
client2.connect(server)
x = client1.getData()
y = client2.getData()
success1 = client1.sendData(1)
success2 = client2.sendData(2)
How might the server|client.run method look like? Assume I could hardcode the method calls for now.
I suggest to use the following approach:
1. Have "server" code that works with Blocking Queue -
A blocking queue is a data structure which is synchronized and let's the thread that reads data from it (the "consumer" thread) to wait until there is a data in the queue to be read.
The "producer" thread is a thread that "pushes" data on the queue.
I would recommend you use one of the blocking queue implementations.
I would also suggest you read more about "consumer producer" pattern.
Blocking queue also eliminates the need for "busy wait" which is not recommended in multi-threading programming.
From the description that you have provided What i can suggest is you should write some thing like
1) Have one queue where all the clients can put up messages.
2) server which is running in an infinite loop like while(true) waits for the new messages that has been put in the queue and if it finds one then processes it and marks it as processed.
3) The job of the client threads would be to create messages and put them in the queue. And notifying the server that new message has been added to the queue so that server can come to know that new message has been arrived for processing.
For this program to make it working i think you need to learn Thread's notify, notifyAll(), and wait() methods. So basically without sockets what you are looking for it "Inter thread communication". This link can help.
Hope this helps.

Implementing asynchronous message queue in java

I have a java server that handles logins from multiple clients. The server creates a thread for each tcp/ip socket listener. Database access is handled by another thread that the server creates.
At the moment the number of clients I have attaching to the server is quite low (<100) so I have no real performance worries, but I am working out how I should handle more clients in the future. My concern is that with lots of clients my server and database threads will get bogged down by constant calls to their methods from the client threads.
Specifically in relation to the database: At the moment each client thread accesses the public database thread on its server parent and executes a data access method. What I think I should do is have some kind of message queue that a client thread can put its data request on and the database thread will do it when it gets round to it. If there is data to be returned from the data access call then it can put it on a queue for the client thread to pick up. All of this wouldn't hit the main server code or any other client threads.
I therefore think that I want to implement an asynchronous message queue that client threads can put a message on and the database thread will pick up from. Is that the right approach? Any thoughts and links to somewhere I can read up about implementation would be appreciated.
I would not recommend this approach.
JMS was born for this sort of thing. It'll be better than any implementation you'll write from scratch. I'd recommend using a Java EE app server that has JMS built in or something like ActiveMQ or RabbitMQ that you can add to a servlet engine like Tomcat.
I would strongly encourage you to investigate these before writing your own.
What you are describing sounds like an ExecutorCompletionService. This is essentially an asynch task broker that accepts requests (Runnables or Callables) from one thread, returning a "handle" to the forthcoming result in the form of a Future. The request is then executed in a thread pool (which could be a single thread thread pool) and the result of the request is then delivered back to the calling thread through the Future.
In between the time that the request is submitted and response is supplied, your client thread will simply wait on the Future (with an optional timeout).
I would advise, however, that if you're expecting a big increase in the number of clients (and therefore client threads), you should evaluate some of the Java NIO Server frameworks out there. This will allow you to avoid allocating one thread per client, especially since you expect all these threads to spend some time waiting on DB requests. If this is the case, I would suggest looking at MINA or Netty.
Cheers.
//Nicholas
It sounds like what you want to do is limit the number of concurrent requests to the database you want to allow. (To stop it being overloaded)
I suggest you have a limited size connection pool. When too many threads want to use the database they will have to wait until a connection is free. A simple way to do this is with a BlockingQueue with all the connections created in advance.
private final BlockingQueue<Connection> connections = new ArrayBlockingQueue<Connection>(40); {
// create connections
}
// to perform a query.
Connection conn = connections.get();
try {
// do something
} finally {
connections.add(conn);
}
This way you can keep your thread design much the same as it is and limit the number of concurrent queries to the database. With some tweaking you can create the connections as needed and provide a time out if a database connection cannot be obtained quickly.

Asynchronous socket communication in Android with threads

I managed to programm an app that communicates with a server. I can write and I can read. I even managed to do it with Java NIO.
My problem is that I have a endless while loop that is listening for new data to read. It blocks the whole program and I can't write anymore data.
I need a solution so the loop keeps running in background listening for new data to read while I send data.
Any suggestions?
Use AsyncTask. It was created just for this kind of jobs (doing long running background tasks, while still have a possibility to update UI).
You could either create a separate thread to handle the socket asynchronously and pass messages through a handler, or create a local service to handle the comms.
You should never do a long wait on the main (UI) thread.
If your loop is blocking the whole program there is something wrong with it. I don't see what other answer you can realistically expect until you post some code.

Stateless Blocking Server Design

A little help please.
I am designing a stateless server that will have the following functionality:
Client submits a job to the server.
Client is blocked while the server tries to perform the job.
The server will spawn one or multiple threads to perform the job.
The job either finishes, times out or fails.
The appropriate response (based on the outcome) is created, the client is unblocked and the response is handed off to the client.
Here is what I have thought of so far.
Client submits a job to the server.
The server assigns an ID to the job, places the job on a Queue and then places the Client on an another queue (where it will be blocked).
Have a thread pool that will execute the job, fetch the result and appropriately create the response.
Based on ID, pick the client out of the queue (thereby unblocking it), give it the response and send it off.
Steps 1,3,4 seems quite straight forward however any ideas about how to put the client in a queue and then block it. Also, any pointers that would help me design this puppy would be appreciated.
Cheers
Why do you need to block the client? Seems like it would be easier to return (almost) immediately (after performing initial validation, if any) and give client a unique ID for a given job. Client would then be able to either poll using said ID or, perhaps, provide a callback.
Blocking means you're holding on to a socket which obviously limits the upper number of clients you can serve simultaneously. If that's not a concern for your scenario and you absolutely need to block (perhaps you have no control over client code and can't make them poll?), there's little sense in spawning threads to perform the job unless you can actually separate it into parallel tasks. The only "queue" in that case would be the one held by common thread pool. The workflow would basically be:
Create a thread pool (such as ThreadPoolExecutor)
For each client request:
If you have any parts of the job that you can execute in parallel, delegate them to the pool.
And / or do them in the current thread.
Wait until pooled job parts complete (if applicable).
Return results to client.
Shutdown the thread pool.
No IDs are needed per se; though you may need to use some sort of latch for 2.1 / 2.3 above.
Timeouts may be a tad tricky. If you need them to be more or less precise you'll have to keep your main thread (the one that received client request) free from work and have it signal submitted job parts (by flipping a flag) when timeout is reached and return immediately. You'll have to check said flag periodically and terminate your execution once it's flipped; pool will then reclaim the thread.
How are you communicating to the client?
I recommend you create an object to represent each job which holds job parameters and the socket (or other communication mechanism) to reach the client. The thread pool will then send the response to unblock the client at the end of job processing.
The timeouts will be somewhat tricky, and will have hidden gotcha's but the basic design would seem to be to straightforward, write a class that takes a Socket in the constructor. on socket.accept we just do a new socket processing instantiation, with great foresight and planning on scalability or if this is a bench-test-experiment, then the socket processing class just goes to the data processing stuff and when it returns you have some sort of boolean or numeric for the state or something, handy place for null btw, and ether writes the success to the Output Stream from the socket or informs client of a timeout or whatever your business needs are
If you have to have a scalable, effective design for long-running heavy-haulers, go directly to nio ... hand coded one-off solutions like I describe probably won't scale well but would provide fundamental conceptualizing basis for an nio design of code-correct work.
( sorry folks, I think directly in code - design patterns are then applied to the code after it is working. What does not hold up gets reworked then, not before )

Categories

Resources