I'm new to threads and am struggling to understand how to implement them. I have a basic understanding of what they are and how they work.
Right now I have two files and they are connected by a socket and I can writebytes back and forth. The purpose of this assignment is to enable multi-usability. By that I mean I want to be able to type a message and be able to receive one simultaneously. This is where threading comes in.
I've read articles on the oracle pages and many other sites that have tutorials for threading and I'm still lost on how to implement threads. What I know so far is:
You can either extend or implement the Thread Class. I'm currently extending the Thread Class.
I also know that by creating a constructor you can call that constructor as a Thread.
What I'm confused about:
A lot of tutorials use the "this" keyword in reference and I'm confused about what it is and why you would use it.
A lot of tutorials also use the "super" keyword. I'm always confused as to what it is and why you would use it.
I can provide further information and my current code for connecting these two classes if you think it will help. Any feedback relevant to this topic is very much appreciated.
You may want to look at Java's documentation for this and super first.
Update:
Based on your comments, it looks like it is calling the constructor.
this(/*args*/)
can often be used to call an alternate constructor of the object. Same with
super(/*args*/)
Related
Im currently learning java. SO I had this Question if it is necessary to create a method or function(create a class) outside the main body and then create its object and call it in main body?
There's several answers:
It is possible to have all the code of your program in a single main method and not split it into multiple methods or classes. That restricts what exactly you can do, but you could still get pretty far with that.
It's a terribly bad idea to do that, since your code will become really hard to read and you can't easily encapsulate individual sub-tasks and many design patterns won't be usable in such an environment
There is a technical restriction which limits how far you can go with that in Java and that is that the byte code of a single method can not exceed 64k bytes.
tl;dr: yes, but you shouldn't. Also no, you can't (for any serious code).
If you are asking if you can put all your application's code into the main method (without creating any other methods or classes): Yeah, I guess, but it is better to structure your code into smaller pieces. And there is a size limit for a method.
Also see:
https://softwareengineering.stackexchange.com/questions/141563/should-main-method-be-only-consists-of-object-creations-and-method-calls
https://softwareengineering.stackexchange.com/questions/154228/why-is-it-good-to-split-a-program-into-multiple-classes
It's not necessary to create a method/function outside the main body and then call it in main body, but if your code line in main is more i.e. 1000 or 2000 line then it is very difficult to manage code. So, if you create method outside main (In other class file) then call in main method using object then your code will be more readable.
It's part of the concept of object orientation in Java. You are not forced to use objects and methods apart from main, but I would really reccomended it. Java is instead of C based languages not procedural but object oriented.
As vimal said, This totally depends upon your code.
This question is not only limited to java but to all other languages too.
Suppose you are making an movie booking application for the explanation of this answer.
Then writing the whole code inside(Booking a ticket, deleting a ticket, Paying for a ticket purchased, and so on) main function would not be a good idea. One may think to write whole code in main method but it will make the code more tedious and complex. Whereas if you write your code in different functions, It will make your code modular, And also it will make your code easier for others to understand. Hope this helps to clear question.
It depends. You can do both, but there is a huge difference between them.
Java follows OOP paradigm. When you are defining a method outside your main(), you are associating the method with the class. You are defining the behaviour of a class.
However, if you are defining a method within main(), then it's just like any other method. You can call them as per your requirement.
I'm interested in the mediator object because it sounds useful, but deciphering code examples in order to learn how to interact with and build that object escapes me. I love code examples if they come with some explanations, however short. Would someone be able to just explain what I'm building when I build a mediator object?
Would a mediator object be a way to handle action events sent between classes? or does the mediator object simply serve better for consolidating like-code into one handy place?
I don't know if it's practical for convenience or if it's practical because there is no other way to do what it does. Any details, however "dumbed down", would be most excellent. Thanks in advance.
The mediator object is intended to do nothing itself. You should not move any logic that you already have into it, except maybe for some multiplexing/demultiplexing (when one object sends the same message to multiple other objects). The mediator is just an external interface (if it simultaneously serves as a facade), and definitely a message passing channel between pre-existing objects.
Likewise, a mediator should not be created until you are already perceiving the need for such a message passing channel. How does such a need look like? You already have a set of objects that start calling each other in increasingly complex ways. Those objects are storing references to each other; the number of such references is already getting bigger than the number of such objects themselves.
So instead of each object talking to each object (with a quadratic number of references and complicated graph of interactions) you introduce a star topology to interactions; everybody directly talks just to the mediator. It is then easier to instantiate, monitor, debug, extend, polymorphize...
Do not start introducing mediators too early or the overall complexity will grow instead of dropping.
I'm working on a moderate-sized Java project and trying to stick to the best possible practices, so I thought I'd run a few questions by you guys. Since I currently have time, I want to do it right. My apologies in advance if this sort of question isn't appropriate for StackOverflow. Perhaps others can refer to it for stylistic advice.
I'm writing a class called LinkOpener which has one public, static method: openAgencyWindows. You feed it an (oil) well serial number and, based on the serial number, a opens regulatory website for any one of the 50 US states. I'd be doing quite a bit of scraping, and due to the labyrinthine nature of these websites the code can get pretty extensive. Should I:
Include all of my scraping code in a LinkOpener class, including methods to handle serial numbers that correspond to each state in the US (sorted alphabetically).
Give each state its own class, which would extend a Scraper class that contains a few common website scraping/regex methods. Each state class would have one to three methods to assist with scraping.
Do something else?
Any assistance would be much appreciated.
Your second alternative will be more readable and a more object-oriented approach, which is good. It is also possible to call methods in the specific classes without knowing what state it is through abstract methods in the implemented class.
I know that to interact from Javascript to Java you have to inject a Java object using the addjavascriptInterface method in webview.
Here is the problem I am facing.
I register a java object using addJavascriptInterface method to be available in my JS.
I inject few JS in the webview using webview.loadURL("javascript:XXX");
I send a JS event when I am done with injecting the JS.
The problem is that if immediately after step 1, if I execute the following Javascript:
mWebView.loadUrl("javascript:if(window.myobject) console.log('myobject found---------'); else {console.log('myobject not found----');}");
I get "myobject not found" in my console's log.
I want to know that if there is some time before I can access my object and if so, how do I get to know how much time should I wait to call my object?
I want to know that if there is some time before i can access my object
Yes, I think there is a delay, because WebView.addJavascriptInterface will run in the WebView's internal worker thread. Perhaps you've thought about this, and realized that WebView has to maintain at least one worker thread to do asynchronous network IO. Maybe you also noticed these threads in DDMS while using a WebView.
It turns out that it also uses a thread to do work for a number of other public methods. I really wish the docs from Google made this clearer! But I hope I can help and show you how I tried to confirm this for myself.
Follow me as I take a look at the source for WebView. It's reasonably readable, even if you can't follow exactly what's going on, it's possible to trace through answer some questions with respect to threads.
You can download the Android framework source through the SDK manager tool, but it's also mirrored on Github, so that's what I've linked to here. I guessed and picked a tag that's close to some version of ICS. It's not hard to find WebView.addJavascriptInterface. I just Googled "WebView.java site:github.com/android".
The method WebView.addJavascriptInterface sends a message to an instance of WebViewCore:
mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
In WebViewCore.java there are a bunch of overloaded methods called sendMessage, but we don't really need to know which exactly is being called, since they do pretty much the same thing. There's even a nice comment to give us a hint that we're in the right place! All of them are delegating to an instance of EventHub which is some inner class. This method turns out to be synchronized, and is sending a message to an instance of Handler, which is a good indication that this is probably running in another thread, but for completeness sake, let's find out!
That Handler is instantiated in EventHub.transferMessages which is called from WebViewCore.initialize. There are a few more hops here, but eventually I found out that this is called from run in WebCoreThread (subclass of Runnable), which is instantiated along with a new Thread right here.
What an adventure! So, even though I really can't say for sure what's going on with all these moving parts, I am pretty confident to say that this method is not synchronous, and sends a message to the WebView's worker thread. I hope that makes sense!
if so, how do i get to know how much time should i wait to call my object?
Unfortunately, I don't know the answer to this. I was researching this exact issue and found this question on StackOverflow in the course of my Googling. I think you have the following options, some of which are nicer or easier than others:
1) Just Thread.sleep for 100 ms or something between addJavascriptInterface and loadUrl("javascript:..."). Blech, I don't like this, but it is potentially the easiest.
2) Another possibility is that you could call WebView.loadUrl with a snippet of JavaScript that specifically tests if the interface is set, and catches the ReferenceError that is thrown if it's not set yet. However, as you might have guessed, this kind of involves adding a JavaScript interface to the WebView!
3) Call WebView.setWebChromeClient instead, and catch JavaScript's alert() or console.log instead. From my experiments, this method is synchronous, so there is no delay. (I have confirmed this in source, but I'll leave details as an exercise for the reader) You should probably come up with some special string to call alert with and check for it inside onJsAlert, so you aren't just catching all alert()s.
Sorry for the length of this answer, I hope that helps. Good luck!
Ensure your Javascript objects declared in your HTML / Javascript that you need to access from Java are declared global otherwise they will most likely be collected. I have code that does this (where Android is my interface added with addJavascriptInterface):
<script>
var cb = function(location) {
alert('location is ' + location);
}
Android.getLocation('cb');
</script>
The getLocation method invokes Android's LocationManager.requestSingleUpdate which then invokes the callback when the LocationListener fires.
Without the "var" I find that by the time the location lookup invokes the callback the callback function has been garbage collected.
(copied from my response on a similar question)
I've taken Jason Shah's and Mr S's implementation as the building block for my fix and improved upon it greatly.
There's just far too much code to put into this comment I'll just link to it.
Details: http://twigstechtips.blogspot.com/2013/09/android-webviewaddjavascriptinterface.html
Source: https://github.com/twig/twigstechtips-snippets/blob/master/GingerbreadJSFixExample.java
Key points are:
Applies to all versions of Gingerbread (2.3.x)
Calls from JS to Android are now synchronous
No longer have to map out interface methods manually
Fixed possibility of string separators breaking code
Much easier to change JS signature and interface names
I learned the object-oriented in Java. Now in develop in C#. This means that I never really understood the functioning of delagates but I know how to use them.
Lately I discovered this page http://java.sun.com/docs/white/delegates.html.
If Java is able to create event without delagates is it possible to do the same in C#? Could we imagine writing our own events without writing a single delegate?
(Question already asked in french here)
Yes, you could use a single-method interface instead of a delegate. You'd also need an implementation of the multi-cast nature of delegates, both in terms of add/remove and invoke. It would be tough to have a single class implementing multicast and also implementing Invoke in a typesafe way, however, due to the interfaces having different numbers and types of parameters. You could have a bunch of them of course: Multicast<T>, Multicast<T1, T2> etc. (The same class would handle asynchronous execution too, probably.)
The other pain in the neck is that you could only implement the interface once per class, even if you wanted several different handlers - so you'd have a lot of nested classes.
There's little that's particularly magical about delegates - they're just a very useful abstraction, and with the syntactic sugar of lambda expressions, anonymous methods and expression trees, they're even nicer.
No, you can't do events in C# without delegates. In C#, events are defined as delegates:
An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.
However, you could mimic events using the Observer pattern.
Microsoft's answer to Sun's White Paper is worth reading.
That's a pretty old document and look where it's gotten them. You can do the exact same thing in .NET if you want. All the "Java Way" is doing is taking advantage of inheritance. That's fine but for many the "function pointer" semantic is much more straightforward and less verbose.
Yes you can. You can use predefined delegates. (I'm not sure what's your level of experience and what are you really asking about)
Why on earth would you want to do that?
I mean, if you have a rules engine, or commands that are more than just eventhandlers, then sure: You will want to implement an interface, because you will have state and behavior besides the actual piece of code you want to fire.
But if providing some code to fire when the event is raised, then there's no reason to not use delegates.
Delegates are thin abstractions over method/function pointers and as such they add very little overhead. And IMO, one should not add overhead just for the sake of it.