I would like to know if it is a bad idea to call a blocking method from within constructor itself.
I am curious to know if we have any guidelines/rules in such a scenario, that we should never call blocking methods in Constructor.
Basically I am trying to do this:
class A
{
// Many instance variables that is to be initialized on instantiaion
String tempVar = null;
public A()
{
// Initialize all the instance variables
tempVar=objectClassB.**callBlockingMethod**(); // this method call would return
// some data from ClassB Object
}
public static void main(String args ...)
{
A a = new A();
// Or should I call the blocking method call only after instantiation according
// to any guidelines of Java pertaining to performance ?
// IMPORTANT: It's only when the blocked method returns value , should the main
// thread proceed as the object 'a' would be sent for further processing
}
}
PS: Eh ,I'm sorry if my question sounds very basic.
I thought its better you can create one method like connect () inside the class A. After creating object you can call like
A a = new A()
A.connect()
Inside connect method you define the blocking method
StreamConnection con=notifier.acceptAndOpen()
.....
if your blocking call doesn't return in specified time period, you consider some mechanism to recover this scenario
Related
While studying for a Java OCA-examn, I have found it difficult to understand the difference between chaining constructors with this() and using new.
Example:
public class BirdSeed {
private int numberBags;
public BirdSeed(){
this(2); // but why not use 'new BirdSeed(2);' instead of 'this(2)' ?
}
public BirdSeed(int numberBags){
this.numberBags = numberBags;
}
public static void main(String[] args) {
BirdSeed seed = new BirdSeed();
System.out.println(seed.numberBags);
}
}
But why not use new BirdSeed(2);, as suggested in the single-line comment, since this will call the constructor and create a new object.
So, given the context above, how is 'this()' and 'new' different?
But why not use new BirdSeed(2);, as suggested in the single-line comment, since this will call the constructor and create a new object
If you write new BirdSeed(2), you'll create a second instance of BirdSeed (in addition to the original instance for which the BirdSeed() constructor is executed), and you won't execute the body of the BirdSeed(int numberBags) constructor for the original BirdSeed instance.
On the other hand, calling this(2) executes the BirdSeed(int numberBags) constructor body for the original instance.
You can convince yourself of the difference by first running:
public BirdSeed(){
this(2);
System.out.println(numberBags); // prints 2
}
and then running:
public BirdSeed(){
new BirdSeed(2);
System.out.println(numberBags); // prints 0
}
You can also observe the different behavior with the following code:
public BirdSeed(){
BirdSeed other = new BirdSeed(2);
System.out.println(this == other); // prints false
}
As you can see, the instance for which the BirdSeed(int numberBags) constructor is executed in not the same instance for which the BirdSeed() constructor is executed.
Because new BirdSeed(2) creates a new (and totally unrelated) object, while this(2) calls the corresponding constructor on the current object.
You can use new BirdSeed(2) as well, it is perfectly valid. The reason of this() syntax is when you want to initialise a class without any parameter, the default value for numberBags is initialised for you using that this() syntax which is simply calling the BirdSeed(2) for you (however it calls that constructor but it does not create new instance of BirdSeed).
Using ByteBuddy, can I implement one instance method by calling another and transforming the result?
For instance (toy example):
public abstract class Foo {
public String bar() {
return "bar";
}
public abstract int baz();
}
Given the above, can I implement baz such that it calls bar() and returns the length of the returned string? I.e., as if it were:
public int baz() {
return bar().length();
}
Naively, I tried the following:
Method bar = Foo.class.getDeclaredMethod("bar");
Method baz = Foo.class.getDeclaredMethod("baz");
Method length = String.class.getDeclaredMethod("length");
Foo foo = new ByteBuddy()
.subclass(Foo.class)
.method(ElementMatchers.is(baz))
.intercept(
MethodCall.invoke(bar) // call bar()...
.andThen(MethodCall.invoke(length)) // ... .length()?
).make()
.load(Foo.class.getClassLoader())
.getLoaded()
.newInstance();
System.out.println(foo.baz());
However, it looks like I was wrong in thinking andThen() is invoked on the return value of the first invocation; it looks like it's invoked on the generated instance.
Exception in thread "main" java.lang.IllegalStateException:
Cannot invoke public int java.lang.String.length() on class Foo$ByteBuddy$sVgjXXp9
at net.bytebuddy.implementation.MethodCall$MethodInvoker$ForContextualInvocation
.invoke(MethodCall.java:1667)
I also tried an interceptor:
class BazInterceptor {
public static int barLength(#This Foo foo) {
String bar = foo.bar();
return bar.length();
}
}
with:
Foo foo = new ByteBuddy()
.subclass(Foo.class)
.method(ElementMatchers.is(baz))
.intercept(MethodDelegation.to(new BazInterceptor()))
// ...etc.
This ran, but produced the nonsensical result 870698190, and setting breakpoints and/or adding print statements in barLength() suggested it's never getting called; so clearly I'm not understanding interceptors or #This properly, either.
How can I get ByteBuddy to invoke one method and then invoke another on its return value?
Per k5_'s answer: BazInterceptor works if either:
we delegate to new BazInterceptor(), as above, but make barLength() an instance method, or:
we leave barLength() a class method, but delegate to BazInterceptor.class instead of to an instance.
I suspect the 870698190 was delegating to hashCode() of the BazInterceptor instance, though I didn't actually check.
There is not currently a good way in Byte Buddy but this would be an easy feature to add. You can track the progress on GitHub. I will add it once I find some time.
If you want to implement such chained calls today, you can implement them in Java code and inline this code using the Advice component. Alternatively, you can write the byte code more explicitly by creating your own ByteCodeAppender based on MethodInvocation instances where you have to load the arguments manually however.
You use an instance as interceptor, that means instance methods are prefered (maybe static method are not accepted at all). There is an instance method that matches the signature of your int baz() method, it is int hashCode(). The number you are getting is the hashcode of the new BazInterceptor() instance.
Options i am aware of:
Remove static from barLength that way it will actually be used for interception.
Add the class as interceptor .intercept(MethodDelegation.to(BazInterceptor.class))
I would prefer the second option as you are not using any fields/state of the BazInterceptor instance.
Yes, this is an academic question, I know people will complain that I'm not posting any code
but I'm genuinely struck with this question, really don't know where to begin. I would really appreciate an explanation and maybe some code example.
If an object constructor starts a new thread that executes the method
run of an anonymous inner class object, it is possible that this new
thread can access its surrounding outer object before it has been
fully constructed and its fields fully initialized. How would you
prevent this from happening?
This is called "leaking this". Here you have the code
public class Test {
// this is guaranteed to be initialized after the constructor
private final int val;
public Test(int v) {
new Thread(new Runnable() {
#Override public void run() {
System.out.println("Val is " + val);
}
}).start();
this.val = v;
}
}
Guess what it will (may, since it's a thread) print. I used a final field to stress that the object is accessed before it has been fully initialized (final fields must be definitely assigned after the last line of every constructor)
How do you recover
You don't want to pass this around when you are in a constructor. This also mean you don't want to call non-final virtual methods in the very same class (non-static, non-private), and not using inner classes (anonymous classes are inner classes), that are implicitely linked to the enclosing instance, thus it's as they could access this.
Think about the single-threaded situation first:
Whenever you create an object via new, its constructor is called which (hopefully) initializes the fields of the new object before a reference to this object is returned. That is, from the point of view of the caller, this new is almost like an atomic operation:
Before calling new, there is no object. After returning from new, the object exists fully initialized.
So all is good.
The situation changes slightly when multiple threads come into play. But we have to read your quote carefully:
...has been fully constructed and its fields fully initialized.
The crucial point is fully. The subject line of your question says "before created", but what is meant here is not before the object has been created, but between object creation and initialization. In a multi-threaded situation, new can no longer be considered (pseudo-)atomic because of this (time flows from left to right):
Thread1 --> create object --> initialize object --> return from `new`
^
|
| (messing with the object)
Thread2 ------------------/
So how can Thread2 mess with the object? It would need a reference to that object but since new will only return the object after is both been created and initialized, this should be impossible, right?
Well, no - there is one way where it's still possible -- namely if Thread 2 is created inside the object's constructor. Then the situation would be like this:
Thread1 --> create object --> create Thread2 --> initialize object --> return from `new`
| ^
| |
| | (messing with the object)
\-----/
Since Thread2 is created after the object has been created (but before it has been fully initialized), there is already a reference to the object that Thread2 could get a hold of. One way is simply if the constructor of Thread2 explicitly takes a reference to the object as a parameter. Another way is by using a non-static inner class of the object for Thread2's run method.
I would change the title of the question, as threads are not accessing themselves, but the second one to the first one. I mean:
You have one thread, creating an object.
Inside the constructor for this object, you declare an anonymous inner class that implements Runnable.
In the same constructor of the first thread, you start a new thread to run your anonymous inner class.
Thus, you're having two threads. If you want to assure that the new thread doesn't do anything before the constructor is "fully ended", I would use some locks in the constructor. This way, the 2nd thread can be started but will wait until the first thread ends.
public class A {
int final number;
A() {
new Thread(
new Runnable() {
public void run() {
System.out.pritnln("Number: " + number);
}
}).start();
number = 2;
}
}
I do not fully agree with Pablos answer because it heavily depends on your initialization method.
public class ThreadQuestion {
public volatile int number = 0;
public static void main(String[] args) {
ThreadQuestion q = new ThreadQuestion();
}
public ThreadQuestion() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
System.out.println(number);
}
});
try {
Thread.sleep(500);
} catch(Exception e) {
e.printStackTrace();
}
number = 1;
t.start();
}
}
When you
place t.start() at the end, the correct data is printed.
place t.start() before the sleep command, it will print 0
remove the sleep command and place t.start() before the assignment it can print 1 (not determinable)
Play a mind game on 3.) you can say a "tiny" assignment of 1 simple data type will work as expected but if you create a database connection it will not achieve a reliable result.
Do not hesitate to raise any question.
So a situation like this?
public class MyClass {
private Object something;
public MyClass() {
new Thread() {
public void run() {
something = new Object();
}
}.start();
}
}
Depending on the actual code used, the behaviour could vary. This is why constructors should be carefully made so that they don't for example call non-private methods (a subclass could override it, allowing the superclass this to be accessed from a subclass before the superclass is fully initialized). Although this particular example deals with a single class and a thread, it's related to the reference leaking problem.
I have a Java utility package, which can be used by multiple services(written in Java) for performing some utility tasks.
Lets say the Java utility package name is U and one of the Service be S. Now S calls a function F of U.
My question is, whether there is a way where function F of package U is able to determine which service S has called it ?
There can be multiple services S1, S2, ... , Sn calling F. I need to know upon a call, which Service Sx is calling that particular F.
You could use something like the following requiring you only to create a function findServiceContainingClass mapping class names to services (or null):
void callee() {
StackTraceElement[] st = new RuntimeException().getStackTrace();
for (int i = 1; i < st.length; i++) {
Service service = findServiceContainingClass(st[i].getClassName());
if (service != null) break;
}
// ... use service
}
However it is deemed bad practice to make code behave differently depending on the caller. I would use such code only as a last resort. (It would be okay to use it in a breakpoint condition during debugging. Maybe that is what you intend.)
Object Oriented programming in Java states that your service is scope for invocation, nothing else (forget static). So there is no normal way to find who is calling instance's method other than passing S instance as argument.
But that does not mean it is impossible.
If you only need to know what is the type of caller, you can use Thread.currentThread().getStackTrace():
StackTraceElement[] elements = Thread.currentThread().getStackTrace()
StackTraceElement caller = elements[elements.length - 2];
printLn(caller.getClassName());
As I said at the beginning it is totally counter objective Java code.
If you need to refer exact instance, you probably should add caller as call parameter. I assume that if you want to refer to caller, callee's code is written by you, so you are able to do it. As for me it would be best choice, because if you need caller in scope of callee, you should pass it directly. Other option is to set caller on ThreadLocal in U, but you don't have confidence that developer will do it each time.
If interface cannot be changed, and U is an interface, you could create U builder object:
public class UBuilder {
public U getS(final S caller) {
Proxy.newProxyInstance(getClass().getClassLoader(), U.class,
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// store caller value on some ThreadLocal variable
try {
method.invoke(proxy, args);
} finally {
// remove caller from ThreadLocal variable
}
}
}
}
}
After that you have additional invocation context (ThreadLocal) referring S instance.
If U is not interface, Javassist, CgLib or something similar would help, but only if invoked method is not static or final.
If F is static or final I see only dramatically hackish answers. Maybe creating own interface imitating U, and forwarding method invocations in InvocationHandler could be some way. Of course S should refer to this interface, not U directly.
Hope it helps.
If there needs to be some service-specific code that is executed by that utility method, I would declare an interface in the utility class and have the services pass in an instance of it to the method.
Here is a contrived example:
public class Utility {
public interface UtilityInterface {
public void specificBehavior( Object arg );
}
public void utilityMethodF( UtilityInterface utilityInterface, Object... args ) {
// perform work with args or whatever
utilityInterface.specificBehavior( null );
// perform work with args or whatever
}
}
I've heard about this happening in non thread-safe code due to improperly constructed objects but I really don't have the concept down, even after reading about in in Goetz's book. I'd like to solidify my understanding of this code smell as I maybe doing it and not even realize it. Please provide code in your explanation to make it stick, thanks.
Example : in a constructor, you create an event listener inner class (it has an implicit reference to the current object), and register it to a list of listener.
=> So your object can be used by another thread, even though it did not finish executing its constructor.
public class A {
private boolean isIt;
private String yesItIs;
public A() {
EventListener el = new EventListener() { ....};
StaticListeners.register(el);
isIt = true;
yesItIs = "yesItIs";
}
}
An additional problem that could happen later : the object A could be fully created, made available to all threads, use by another thread ... except that that thread could see the A instance as created, yesItIs with it "yesItIs" value, but not isIt! Believe it or not, this could happen ! What happen is:
=> synchronization is only half about blocking thread, the other half is about inter-thread visibility.
The reason for that Java choice is performance : inter-thread visibility would kill performance if all data would be shared with all threads, so only synchronized data is guaranteed to be shared...
Really simple example:
public class Test
{
private static Test lastCreatedInstance;
public Test()
{
lastCreatedInstance = this;
}
}
This is the reason why double-checked locking doesn't work. The naive code
if(obj == null)
{
synchronized(something)
{
if (obj == null) obj = BuildObject(...);
}
}
// do something with obj
is not safe because the assignment to the local variable can occur before the rest of the construction (constructor or factory method). Thus thread 1 can be in the BuildObject step, when thread 2 enters the same block, detects a non-null obj, and then proceeds to operate on an incomplete object (thread 1 having been scheduled out in mid-call).
public class MyClass{
String name;
public MyClass(String s)
{
if(s==null)
{
throw new IllegalArgumentException();
}
OtherClass.method(this);
name= s;
}
public getName(){ return name; }
}
In the above code, OtherClass.method() is passed an instance of MyClass which is at that point incompletely constructed, i.e. not yet fulfilling the contract that the name property is non-null.
Steve Gilham is correct in his assesment of why double checked locking is broken. If thread A enters that method and obj is null, that thread will begin to create an instance of the object and assign it obj. Thread B can possibly enter while thread A is still instantiating that object (but not completing) and will then view the object as not null but that object's field may not have been initialized. A partially constructed object.
However, the same type of problem can arrise if you allow the keyword this to escape the constructor. Say your constructor creates an instance of an object which forks a thread, and that object accepts your type of object. Now your object may have not be fully initialized, that is some of your fields may be null. A reference to your object by the one you have created in your constructor can now reference you as a non null object but get null field values.
A bit more explanation:
Your constructor can initialize every field in your class, but if you allow 'this' to escape before any of the other objects are created, they can be null (or default primative) when viewed by other threads if 1. They are not declared final or 2. They are not declared volatile
public class Test extends SomeUnknownClass{
public Test(){
this.addListner(new SomeEventListner(){
#Override
void act(){}
});
}
}
After this operation instanse of SomeEventListner will have a link to Test object, as a usual inner class.
More examples can be find here:
http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html
Here's an example of how uninitialized this of OuterClass can be accessed from inside of inner class:
public class OuterClass {
public Integer num;
public OuterClass() {
Runnable runnable = new Runnable() { // might lead to this reference escape
#Override
public void run() {
// example of how uninitialized this of outer class
// can be accessed from inside of inner class
System.out.println(OuterClass.this.num); // will print null
}
};
new Thread(runnable).start();
new Thread().start(); // just some logic to keep JVM busy
new Thread().start(); // just some logic to keep JVM busy
this.num = 8;
System.out.println(this.num); // will print 8
}
public static void main(String[] args) {
new OuterClass();
}
}
Output:
null
8
Pay attention to OuterClass.this.num instruction in the code