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.
Related
I need to make a Server socket in a web application that listen for Asterisk AGI requests but i need to enable CDI injection in the socket, don't know how to do that.
Today i already have this socket working very well, the problem is i can't inject a CDI bean with the socket.
Ex:
class RequestProcessor implements Runnable
{
private Socket socket;
#Inject
private PhoneService phoneService;
#Override
public void run()
{
// Do the logic here
}
}
Method that receives the request and send to a pool.
ExecutorService pool = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(25000);
Socket client = server.accept();
pool.execute(new RequestProcessor(client));
It's not the production code, it's just a illustrated example!
I can't make the #Inject PhoneService phoneService works.
As we've already established, newing the RequestProcessor won't populate the #Inject-annotated field since new completely cuts out the DI system. So you need a way to bring it in.
Your goal looks particularly non-trivial because RequestProcessor wants a DI-provided dependency (phoneService) and one that you provide programmatically (socket). As a general rule I would advise against mixing the two where possible – once you're using DI, it wants to spread like a virus. Let that happen. If you can design your system so that (almost) everything is injected for you, that's fanstastic!
That said, your situation is completely workable.
It looks like you have some method in some class which is a potential injection site. Assuming that this unknown class is in fact created by CDI you could #Inject the PhoneService into that class, and then pass it to the RequestProcessor constructor:
public class SomeClass {
#Inject
private PhoneService phoneService;
private void someMethod() {
ExecutorService pool = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(25000);
Socket client = server.accept();
pool.execute(new RequestProcessor(client, phoneService));
}
}
Or you could use a factory to create RequestProcessor instances, which will basically have the same effect in the end. You can write this factory by hand, which will look pretty familiar:
public class RequestProcessorFactory {
#Inject
private PhoneService phoneService;
public RequestProcessor createNewProcessor(Socket socket) {
return new RequestProcessor(socket, phoneService);
}
}
then inject an instance of that factory into your class:
public class SomeClass {
#Inject
private RequestProcessorFactory requestProcessorFactory;
private void someMethod() {
ExecutorService pool = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(25000);
Socket client = server.accept();
pool.execute(requestProcessorFactory.createNewProcessor(client));
}
}
There's a third way that you can do it, which is similar to Guice's assisted injection. Effectively it just generates that factory implementation for you, if you provide the interface. To my knowledge, CDI does not support this, but there is at least one CDI extension which does.
Happy DI-ing!
My server aperiodically receives join requests from new clients. Upon receiving a new join request, the server runs a service that can be finished real quick. I implement the service as a Java class (called JC) implementing the Runnable interface. I have parameters within the JC class.
At the caller side, I like to have only one instance (or static) of the JC. My question is how to trigger the run() method in the JC every time. Please show me some code. Thanks.
Hope following edits make sense, which is my current implementation.
In the Server that wants to trigger thread executing:
public class Server {
private static RealService mm = new RealService();
private static void update(){
new Thread(mm).start();
}
}
In the Service class:
public class RealService implements Runnable{
#Override
public void run() {
// TODO Auto-generated method stub
// Do something
}
}
You're question is not really clear here, but I would suggest reading about TimerTask in Java
You could use a socket to listen for incoming requests, the server can spawn a new thread each time there is a request. Once the thread completes, you should intimate the client.
You could read about how a concurrent server works.
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.
This is a little weird question, I have a GUI class that in the constructor initiates a Logic class that takes care of the processing of the Processing or Logistics in the App then their is a Handler class that contains a bunch of ActionListners KeyListeners that are attached to UI components in the GUI class
In Constructor of both the Logic and Handler class I take in as parameter the GUI class to be able to manipulate the GUI components created in the GUI class from both the Logic and Handler classes
My problem is that The Handler makes use of the Logic class and vise versa (the Logic class uses the Handler class) and thats not really possible with the method I described above, one is instance before the other, one will be null when attempting to use the other.
Example:
public class GUI()
{
this.handler = new Handler(this);
this.logic = new Logic(this);
}
If handler tries to use something in logic then null would be returned.
One way to fix this is to a setter for the handler to take the logic and vise versa but that doesn't seem like the answer to this.
simple:
public class GUI()
{
this.handler = new Handler(this);
this.logic = new Logic(this);
handler.setLogic(logic);
logic.setHandler(handler);
}
I think it is possible just to expose the Handler and Logic in GUI, and let the public access it. By doing so, as your Handler and Logic already have reference to GUI, they can indirectly get access to each other:
class Gui {
private Handler handler;
private Logic logic;
public Handler getHandler() {
return this.handler;
}
public Logic getLogic() {
return this.logic;
}
}
class Handler {
private Gui gui;
public Handler(Gui gui) {
this.gui = gui;
}
public void doSomething() {
// access logic
this.gui.getLogic().doSomeLogic();
}
}
Regarding to "elegance", I don't think the original design of (imho) messy dependencies between component is elegant at all :) So, instead of focusing making such things look "elegant", do some rethinking and possibly you will find everything become much more elegant automatically. :)
Right before your first usage of handler and logic you could put this code snippet
if(handler == null)
this.handler = new Handler(this);
if(logic == null)
this.logic = new Logic(this);
I would like to create a java class (thread) that pings twitter and if there is no connectivity wait until there is connection and re-run some other classes and threads.
I have the code that "pings" websites and a way to run every static method is in my Main class. Is this a good solution to the problem?
Here is the basic part of the code:
while (true){
try {
final URLConnection connection = new URL(url).openConnection();
connection.connect();
}
catch (Exception e) {
Thread.sleep(10000*t);
if (url.matches(twitter1)){
Thread method1= new Thread(Class1.method1);
method1.start();
}else if (url.matches(twitter2)){
Thread method2 = new Thread(Class1.method2);
method2.start();
}else if (url.matches(twitter3)){
Main.StaticMethod();
}else if (url.matches(twitter4)){
Main.StaticMethod2();
}else if (url.matches(twitter5)){
Main.StaticMethod3();
}else{
System.out.println("Unknown URL");
}
t=2^t;
}
}
You do not run classes or threads, you can only invoke methods. If the methods are instance methods then you need some object; otherwise they are static and you need to know the class in which they are defined. If you want to start another thread, then you need an object of a class that implements Runnable.
For example,
try {
final URLConnection connection = new URL(url).openConnection();
connection.connect();
} catch (Exception e) {
}
// connection is available, either use it or close it. then,
// AfterConnect is a class that implements Runnable. Perhaps it takes
// the connection as parameter?
AfterConnect afterConnect = new AfterConnect(..);
// this will start a new thread
new Thread(afterConnect).start();
BTW your example does not "wait until there is connection". If you are going to put the try...catch in a loop, you should sleep for some time between iterations.
How will you define "running" the classes ? One way to do it would be to store references to these classes in your timeOut class, and then to invoke the methods that you want when you successfully ping the site.
I'm not quite sure how you have structured the "re-run some other classes and threads" stuff. If it is in a mishmash of method calls, then you could put the code you presented in an abstract class, and add an abstract method
abstract class AbstractTimeout {
... your code here, but add a call to afterConnection() ...
protected abstract void afterConnection();
}
A subclass would implement that by setting up some fields for all the classes objects and calls in a constructor, then implementing the mishmash of calls in
protected void afterConnection() {
class1.goDoThis();
object2.goDoThat();
someRunnable.run();
// ... etc...
}
This is classic inheritance. BTW, you need to consider what Exceptions might be thrown and which to declare. For simplicity, I ignored that issue.
Alternatively, if the "re-run some other classes and threads" stuff is already in something fairly simple and well organized like a Runnable, you could have your class take a Runnable along with the URLConnection as an argument, and run() the Runnable (or launch it in a new thread) after the connection is complete. This is classic composition. e.g.
public void doTimeout(URL url, Runnable afterConnection) {
// your connection stuff from above
afterConnection.run();
}
NOTE : I didn't put afterConnection.run() into a Thread, cause I think that doTimeout should already be in it's own thread. YMMV.
NOTE2: My 2nd solution is similar to #Miserable Variable afterConnect() concept. I used a Runnable, he used a a more flexible interface.