I don't know how to solve this problem I hope that you can help me.
Behind Server side I have this:
class Baza0 implements Runnable{
anotherclass arraylist_handle = new anotherclass();
public method1(string s1){uses methods figured in arraylist_handle)
public run(){
while(true){
Socket s = s.accept();
if(s==NULL) continue;
//there I'm starting another thread that handles client connection
}
}
public static void main(){
Baza0 baza0 = new Baza0();
Thread t = new Thread(baza0);
}
}
Connected clients sends Strings by socketserver feature to client handler. How can I send this string from client handler to the method1 as parameter? It must use the only one Baza0 object, because of the ArrayList that must be common for all the clients.
EDIT
can someone tell me why something like Baza0.baza0.method1() won't work?
EDIT2
Look what I did!
I've made in Class Baza0 an static variable:
static Baza0 baza1;
and in main method I've started an Baza0 object:
Baza0 baza0 = new Baza0();
after this run the method that makes baza1 = baza0.
now from client handler I have access to method, by:
Baza0.baza1.method1(param);
It does work! :D ...don't know why.
If you are using the arraylist only for reading, then all the child threads are free to access it concurrently;
if the threads want to modify the list, then the list must be thread-safe;
if the modification involves many steps (reading and writing), then you must use synchronized blocks within which a "transaction" with the list happens.
Pass a Baza0 reference to Client Handler thread which can be used for calling method1.
public method1(string s1){
synchonized(arrayList){
//list operation
}
}
...
while(true){
Socket s = s.accept();
if(s==NULL) continue;
new Thread(
new WorkerRunnable(
clientSocket, this).start();
}
....
public class WorkerRunnable implements Runnable{
public WorkerRunnable(Socket socket,Baza0 ba){
this.socket = socket;
this.baza =ba;
}
public void run(){
...
this.ba.method1(...);
}
}
Your client thread must have a reference to that ArrayList - directly or (better) indirectly. Simplest way to do this is to pass Baza0 instance (this) to the client thread:
public class Client implements Runnable {
private final Baza0 baza;
public Client(Baza0 baza) {
this.baza = baza;
}
public void run() {
//...
baza.method1("Some string");
}
}
When you create your Client thread simply pass this:
new Thread(new Client(this)).start();
Important thread safety issue: method1() has to be synchronized or your ArrayList must be thread-safe.
I'd say what #Marko Topolnik said. Also I have a book Java Concurrency In Practice (that right now is not responding to me :-() or a link that led me to the book, in the blog The Java Specialists for handling thread issues. The book has examples of all queues, concurrent, synchronized lists, ways to implement code to do several things, etc, and all pretty straight forward, an example and a few paragraphs of every subject.
Related
I checked source code of ZMQueue class from JeroMQ which implements Runnable interface looks like:
private final Socket inSocket;
private final Socket outSocket;
public ZMQQueue( Context context, Socket inSocket, Socket outSocket ){
this.inSocket = inSocket;
this.outSocket = outSocket;
}
#Override
public void run(){
zmq.ZMQ.proxy( inSocket.base(), outSocket.base(), null );
}
As you can see inside the run() only one statement is there, i.e. calling a
ZMQ.proxy() - what happens here?
And in constructor,it's taking a Context instance as a parameter and doing nothing with it.
can any one explains, for what purpose this class has implemented?
It's simple proxy that works in separate thread, it takes a msg from one socket and puts it to another, ZMQueue class is just a some kind of high-level api in jeromq/jzmq library.
Also you can use proxy without ZMQueue class (doc).
Or you can implement something more complicated by yourself with any processing you need.
I am pretty new to using multithreading, but I want to invoke a method asynchronously (in a separate Thread) rather than invoking it synchronously. The basic idea is that I'm creating a socket server with an object in memory, so for each client I will have to run something like object.getStuff() asynchronously.
The two constructs I found were:
having the class implement Runnable and threading this and
declaring a runnable class within a method.
Additionally this method needs a return value- will it be necessary to use Executor and Callable to achieve this? Could someone point me in the right direction for implementing this?
I have tried implement option 2, but this doesn't appear to be processing concurrently:
public class Test {
private ExecutorService exec = Executors.newFixedThreadPool(10);
public Thing getStuff(){
class Getter implements Callable<Thing>{
public Thing call(){
//do collection stuff
return Thing;
}
}
Callable<Thing> callable = new Getter();
Future<Thing> future = exec.submit(callable);
return future.get();
}
}
I am instantiating a single test object for the server and calling getStuff() for each client connection.
Threading Tutorial
The Java tutorial on concurrency has a good section on this. It's at https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html. Essentially, you can either implement Runnable or Callable, or inherit from Thread.
Subclassing Thread
You can write a class, including an anonymous inner class, that extends Thread. Instantiate it, then invoke the start() method.
public class MyThread extends Thread {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyThread m = new MyThread();
m.start();
}
}
Implementing Runnable
You can write a class that implements Runnable, then wrap an instance in a Thread and invoke start(). Very much like the previous.
public class MyRunnable implements Runnable {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
(new Thread(r)).start();
}
}
Return Value
Runnable doesn't allow for return values. If you need that, you need to implement Callable instead. Callable looks a lot like Runnable, except you override the call() method instead of the run() method, and you need to give it to an ExecutorService.
public class MyCallable implements Callable<Integer> {
public Integer call() {
System.out.println("A thread using Callable<Integer>");
return 42;
}
public static void main(String[] args) {
MyCallable c = new MyCallable();
Future<Integer> f = Executors.newSingleThreadExecutor().submit(c));
System.out.println("The thread returned: " +
f.get());
}
}
The two constructs I found were 1) having the class implement Runnable and threading 'this' and 2) declaring a runnable class within a method.
Option (2) probably is better. Most programs would be improved if they had more classes, not fewer. Each named entity in a program—each package, class, method, whatever—should have just one responsibility. In your option (1), you are asking the class to do two things.
For your option (2), you don't actually have to declare a whole class. You can either use an anonymous inner class, or if you can go with Java8 all the way, you can use a lambda expression. Google for either one to learn more.
Additionally this method needs a return value.
The classic way, is for the Runnable object to return the value through one of its own fields before the thread terminates. Then the parent thread, can examine the object and get the return value afterward.
Will it be necessary to use Executor and Callable to achieve this?
Necessary? A lot of people think that ExecutorService is a Good Thing.
Sounds like you are creating a server that serves multiple clients. Do these clients continually connect and disconnect? The advantage of using a thread pool (i.e., ThreadPoolExecutor) is that it saves your program from continually creating and destroying threads (e.g., every time a client connects/disconnects). Creating and destroying threads is expensive. If you have a lot of clients connecting and disconnecting, then using a thread pool could make a big difference in the performance of your server.
Creating and managing threads by yourself is generally bad approach.
As you already pointed - use Executors utility class to create executor and submit Callables to it.
public class RunWResult implements Runable{
private volatile ResultType var;
//the thread method
public void run(){
...
//generate a result and save it to var
var = someResult();
//notify waiting threads that a result has been generated
synchronized(this){
notify();
}
}
public ResultType runWithResult(){
//run the thread generating a result
Thread t = new Thread(this);
t.start();
//wait for t to create a result
try{
wait();
}catch(InterruptedException e){}
//return the result
return var;
}
}
Just a quick question look at the code below, is there any reason why wouldn't do this or is it fine?
public class MyClass implements Runnable, MyClassInterface {
Thread threader;
void start() {
threader = new Thread(this);
threader.start();
}
#Override
public void run() {
Thread current = Thread.getCurrentThread();
while (threader = current) {
..
}
}
}
The original logic was not to expose that fact it runs in a separate thread to the caller
who creates a "MyClass" but then there are doubts if that is a good thing or bad.
Can anyone see any good reason not to do it or is it acceptable. It can be expected that MyClass.start() maybe called a few times.
EDIT: Updated the code to show it is implementing Runnable and one other interface, the interface is used by client code, the actual implementation may run in a separate thread, same thread or any other way. The idea was to abstract that away from the client, as the client is simply an object that "MyClass" will notify and is not aware (currently) of the Runnable interface it implements.
Perhaps that abstraction is not needed and client should have more control?
EDIT: The start() was simply to tell the object it is ready to start receiving notifications rather than start a thread.
Have a look at this: http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
In my opinion, it is a bad design, because you are breaking encapsulation by implementing an interface (Runnable) and by providing a public method (run) that are of no use of the consumer of the class.
You can start a thread from the start method without inhering from Runnable:
public class MyClass {
private Thread thread;
public void start() {
thread = new Thread(this::doWork); // Java 8 method reference
thread.start();
}
private void doWork() {
// ...
}
}
If you can't use method references from Java 8, replace this::doWork with:
new Runnable() { public void run() { doWork(); } }
In a swing application, I would like to re-utilize a spawned thread instead of creating a new one to serve requests. This is because the requests would be coming in short intervals of time and the cost of creating a new thread for every request could be high.
I am thinking of using the interrupt() and sleep() methods to do this as below and would like to know any potential performance problems with the code:
public class MyUtils {
private static TabSwitcherThread tabSwitcherThread = null;
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
tabSwitcherThread = new TabSwitcherThread();
tabSwitcherThread.start();
}
else
tabSwitcherThread.interrupt();
}
private static class TabSwitcherThread extends Thread{
#Override
public void run() {
try {
//Serve request code
//Processing complete, sleep till next request is received (will be interrupted)
Thread.sleep(60000);
} catch (InterruptedException e) {
//Interrupted execute request
run();
}
//No request received till sleep completed so let the thread die
}
}
}
Thanks
I wouldn't use sleep() and interrupt() - I'd use wait() and notify() if I absolutely had to.
However, is there any real need to do this instead of using a ThreadPoolExecutor which can handle the thread reuse for you? Or perhaps use a BlockingQueue in a producer/consumer fashion?
Java already provides enough higher-level building blocks for this that you shouldn't need to go down to this level yourself.
I think what you're looking for is a ThreadPool. Java 5 and above comes with ThreadPoolExecutor. I would suggest you use what is provided with Java instead of writing your own, so you can save yourself a lot of time and hairs.
Of course, if you absolutely has to do it the way you described (hey, sometimes business requirement make our life hard), then use wait() and notify() as Jon suggested. I would not use sleep() in this case because you have to specified timeout, and you never know when the next request will come in. Having a thread that keep waking up then go back to sleep seems a bit wasteful of CPU cycle for me.
Here is a nice tutorial about the ThreadPoolExecutor.
EDIT:
Here is some code example:
public class MyUtils {
private static UIUpdater worker = null;
private static ExecutorService exeSrv = Executors.newFixedThreadPool(1);
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
worker = new UIUpdater();
}
//this call does not block
exeSrv.submit(worker, new Object());
}
private static class UIUpdater implements Runnable{
#Override
public void run() {
//do server request and update ui.
}
}
}
Assume I have a class like this:
public class Server {
public static void main(String[] args) {
Map<Integer, ServerThread> registry = Collections.synchronizedMap(new LinkedHashMap<Integer, ServerThread>());
...
while(true) {
Socket socket = serverSocket.accept();
ServerThread serverThread = new ServerThread(id, registry);
registry.put(id, serverThread);
}
}
}
Then:
public class ServerThread extends Thread {
private Map<Integer, ServerThread> registry;
private int id;
public ServerThread(int id, Map<Integer, ServerThread> registry) {
this.id = id;
this.registry = registry;
}
...
private void notify() {
synchronized(registry) {
for(ServerThread serverThread : registry.values()) {
serverThread.callSomePublicMethodOnThread();
}
}
}
}
I just want to make sure that registry doesn't get modified while I am iterating over it. Does making it a synchronized map guarantee this behavior? Or do I need the synchronized statement. Will the synchronized statement behave like I expect it to?
Thanks
You need the synchronized block around the loop.
See the JavaDoc for the details.
Yes the synchronized statement you have will work like you expect it. I would just add one comment, the thread you are accepting socket connections will block on registry.put(id, serverThread); while you are in the synchronized section on another thread. This means that your server will not process any new incoming requests while you are processing the notification.....
You might want to consider moving the put statement(of course changing serverThread to this)
to the very first line of the run method of ServerThread's run method. That way you will not block incoming connections if callSomePublicMethodOnThread winds up taking a long time to process.
To make everything easier I would use ConcurrentHashMap (http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html) so you don't need to use the sync block in the loop, because concurrentHashMap uses a different type of iterator (not fail-fast iterator) and it will not thorw concurrentModificationException, you will also have better performance.
There is one issue in code, you can not define your method as "private void notify()" because "notify()" is a method defined in Object class