Tag: java

Shared or Static – Visual Basic vs Java?

MP900386814 In Java there are 2 fundamental concepts that any developer should know: instances and classes. Class its the base of your code, your specification about an entity, like Account, Customer or Supplier. Instance its what you get after a “new ” (an object in the heap). So you have at maximum 1 class and N instances of that class.

Although a class its just the specification, in Java a class could have state and behavior like an instance, but with the condition “There could be only one” shared for all instances! Everything that are declared as static are executed(static blocks for instance)/initialized at class load time by the JVM, the rest (instances) are executed/initialized in runtime, after load time.

This word, static comes from very long time, since C, C++, C# and others, but Visual Basic uses other word “shared which somehow implies the behavior of the fields declared as static(java) or shared(visual basic) after a Class “is running”! After the JVM has loaded your class, every static(java) field are shared(visual basic) between all instances, so the question is:

What of these words captures better this behavior (of static) “static” vs “shared”?

So, although I really like a lot languages like C++, Java and C#, I must admit Visual Basic its somehow more expressive and more closely related with the true meaning of “shared” fields!

What I dont like about Java Application Servers

I have a lot of experience with Java Application Servers, from Weblogic to jBoss 5,6,7 and Glassfish. I’m a Java and J2EE Trainer too. So, I’m not here to make an argument against the use of Java Application Servers, I use them every day, however I must say some things that I really dont understand (from a user/developer perspective) about Java Application Servers:

Why Java Application Servers don’t isolate a deployed application? How many times are you deploying an application and you have to configure, customize, remove jars, add another’s jars, create additional files just because the application server already has some of the jars you use in your application? For instance, in my team, we are migrating sites and web services from weblogic and its a nightmare, jboss already have some of the jars, and at deployment time throws exceptions that are not so easy to understand at first sight. (like logging jars – in our case slf4g with logback) If an application could be isolated like a file system application its isolated in an operating system like linux or MAC OS these problems dont even existed! I just wanted to deploy my application with the jars I need, and don’t think about what jars the application already have.

I have experienced deploying applications in Microsoft IIS and in Java application servers. Using Microsoft Servers its much more easy than using similar java products. Usually, when starting and developing Microsoft products I spend 80% of the time focused in developing and  testing the product, and the other 20% finishing configuring and deployment. With Java Application Servers, first you must study the application server, know about several XML files with specific names, to configure datasources, jms queues, etc. Then you hope that exists some eclipse plugin or netbeans plugin that really works. I have experienced plugins for weblogic and jboss but sometimes when you deploy an application its just a view for your eyes, the application doesnt get really deployed to the application server, so I have to go to the localhost website, and deploy it. The inverse its also true. So, 80% configuring and preparing, learning and training and the rest 20% of time developing.

Don’t get me wrong, my experience its divided between these two worlds (Microsoft and Java), I like Java, after all the configuration its done everything will work as expected, but its a really tough job to put everything to work at first in Java Application Servers World!

 

Do you know ForkJoinPool Java 7?

Java 7 brings and/or improves thread management to handle heavy and complex tasks.

You can use threads, ExecutorServices and this: ForkJoinPool.

There is an increasing developers movement to coding in a functional state of mind, using Ruby, Scala, Clojure and other similar programming languages. Java 8 will follow this path too, with lambdas. If you are not using a functional approach in programming, I invite you to do so, its a very different way of thinking where the “divide to conquer” its a must!

In Java 7 you can use this way of thinking to resolve complicated problems, the ones where its necessary to think recursively where you can split a heavy task in simples ones, like when you are sorting a big list using quick sort, transverse a file system including every folder and file, etc. These are problems that seems complicated at first, but thinking recursively it turns out to be very simple tasks.

The main algorithm to implement a recursively task its always something like:

  1. What is the stop condition? (Here you return a “real” value)
  2. Call the method recursively calling it itself with some sort of improvement in the parameters, like if you are in a for.. loop.

For instance, long factorial(long n)

  1. stop condition: if( n <= 1) return 1;
  2. calling recursively like a loop: return n * factorial(n-1)

Has you know by now, the factorial(n-1) will have to stop in the future, because n-1 its decreasing until it reaches  n <= 1, and then n * will be really calculated!

 

In Java 7 you have a Class ForkJoinPool that automatically handle threads to execute the smaller tasks like the above: n and  factorial(n-1).

The recursively method will always be the protected Long compute(), which must be an @override because the class will extend: RecursiveTask, where will be the return value of the compute method!

In the example below, I have implemented a very simple example to calculate the sum between 2 numbers, using recursive smaller tasks.

I start with some range, if the stop condition (end – start), its below 10, then I return the sum between the start and end, otherwise I split the range in 2 parts, the first one executes concurrently (using fork witch puts the thread in the ForkJoinPool) the second half of (end – start) and the first one computes the sum delegating its execution to the compute method (itself!), or the other half.

Observe the last return: return t2.compute() + t1.join(); where the second thread calls the compute and then waits for the fork previously executed as the first thread!


 

I think the code its very clear and simple, if you have questions or comments don’t hesitate to post them!

This Is a very useful tool to resolve complex problems that I really invite you to learn and use it!

Java Blocks–Advanced–Part 1

Following a previous post I will deep into the discussion about anonymous blocks mixed with static variables.

Lets see a simple example, and then we will complicate a little bit.

public class TestStaticInitializer {

{
System.out.println(“block 1”);
}

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
}

{
System.out.println(“block 3”);
}

}

You can observe that:
– There is a static variable ‘x’ that its initialized calling a static method.
– There are 3 anonymous blocks.
– The constructor calls the static variable.

The main method references the class.

At first sight we can think the anonymous blocks are called in sequence, which it’s true. Although if there is a static variable initialized in anyway, this initialization runs before any anonymous block.(Why? Because a class is loaded in 2 phases: load class, run class. At load the JVM after some verification, initialized every static variable and runs any static anonymous initializer, and only after runs the class, or our instance.)

You can observe this by looking to the execution output:

static initialization of x
static main block before calling the constructor
block 1
block 2
block 3
static x = 5
static main block after constructor

The anonynous blocks are executed by sequence, but the initialization variable “static initialization of x” runs first, although its declaration is after “block 2”.

The sequence is:

1 – Initialize the static variable x

2 – run main method

3 – initialize the class (because I’m calling the constructor)

4 – run anonymous blocks

5 – runs the constructor (only after the static blocks)

6 – runs the other “main” statements.

 

You must be wondering why I underlined “The main method references the class” above.

Lets see if I remove (I will just comment it) the call to the class constructor.

public class TestStaticInitializer {

{
System.out.println(“static block 1”);
}

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“static block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

//TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
}

{
System.out.println(“static block 3”);
}

}

 

and the output is:

static initialization of x
static main block before calling the constructor
static main block after constructor

 

Well, where are the anonymous blocks initializers? Thet are not needed! We haven’t crated any instance of the class, so the JVM just considered the static stuff!

And if a static block references the static variable x?

public class TestStaticInitializer {

{
System.out.println(“block 1”);
x = 7;
System.out.println(“block 1 after x = 7”);
    }

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

//TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
System.out.println(“x = ” + x);
    }

{
System.out.println(“block 3”);
}

}

The output:

static initialization of x
static main block before calling the constructor
static main block after constructor
x = 5

The initialization of “x = 7” in the first anonymous block is simple ignored, because the code was never ran!

static int x;// = staticInitialization();

The output will show you “x = 0”.

 

I hope this post will help you understand the mix between anonymous and static initialization blocks. In a future post I will bring some class hierarchy to this discussion.

 

Anonymous Java Classes and Interfaces

In java you can use Anonymous Classes and Anonymous Interfaces.

Anonymous classes

class MyMessage {
    public void printMessage() {
        System.out.println("Original message");
    }
}

public class TestAnonymousClass {

    public static void main(String[] args) {
        TestAnonymousClass tac = new TestAnonymousClass();

        MyMessage m = new MyMessage();
        m.printMessage();
       
        tac.showGeneralMessage(new MyMessage() {
            public void printMessage() {
                System.out.println("Override message");
            }
        }
);
    }

    void showGeneralMessage(MyMessage msg) {
        msg.printMessage();
    }
}

The Bold source shows how to create the anonymous class. As you can see it’s not so anonymous as we expected, it’s just the name that is anonymous.

In anonymous classes the only think we can do it’s to instantiate an existing class, and override or add some methods.  What are we really doing is extending another class(in our example we are extending “MyMessage”) with the possibility to override or add new methods.

If you run the code above the output will be:

Original message

Override message

 

Anonymous Classes with interfaces

interface MyMessage {
    void printMessage();
}

public class TestAnonymousClass {

    public static void main(String[] args) {
        TestAnonymousClass tac = new TestAnonymousClass();

        tac.showGeneralMessage(new MyMessage() {
            public void printMessage() {
                System.out.println("Override message");
            }
        }
);
    }

    void showGeneralMessage(MyMessage msg) {
        msg.printMessage();
    }
}

Now with interfaces, you can observe that the syntax it’s the same, but we are creating a class by “implementing” the interface MyMessage.

Look that I only changed the MyMessage class to be and interface,  but the remaining code is still the same and works with the same behavior (ok, now the output doesn’t have the “Original Message”, because we don’t have one! We lost it when we changed the class to be an interface.)

Hope it helps you in your projects, to implement callbacks, using swing components to register listeners, etc..

Technorati Tags: ,,,

Windows Live Tags: Anonymous,Java,Classes,Interfaces

WordPress Tags: Anonymous,Java,Classes,Interfaces

Java Initialization Blocks

Java has some features that are not well know from a lot of Java Developers, even developers with 5 and 10 years of Java Experience.As a Oracle/Java trainer I must study all of them to teach my students and prepare them well for the Java Certification.

One of these bot well know features are java Initialization blocks. One of these are blocks runs before the JVM runs any code (at class loader level) and the other one runs at constructor time.

Lets see an example and an explanation:

Instance Block
class MyClass {
    private int x;
    {
         x = 7;
         System.out.println(“This is called inside constructor, just after super(…)”);
     }

     public MyClass() {
         System.out.println(“the constructor”);
     }
}
Static Block
class MyClass {
    private int x;
    public static int y;
    static { 
        y = 7; // y must be static!
        System.out.println(“This is called by class loader before your program runs!”);
        // x = 5; it’s illegal because this is class context and not instance context
    }

    public MyClass() {
        System.out.println(“the constructor”);
    }
}

 

So, there are 2 types of code initialization blocks:

Instance

When we talk about instances we talk about objects, something that was already created and has memory allocated.

The instance code block is executed right after the call to super in any constructor called.

It’s a way to initialize variables in all constructors without write code in any of them, which it’s a great way to organize initialization code, too.

 

Static

Static context it’s called class context too. Everything that is static it’s only visible when we use de class name before the field, method or inner class. (ok, unless we use import static…)

When we talk about classes we are talking about the blueprint or definition of the object. This definition “runs” before the instance is created, so the static initialization block runs before the java interpreter and before any constructor called. So, who runs the static initialization blocks? The class loader of the Java Virtual Machine.

This is the place to initialize ONLY static variables, because they are the only ones that are visible at this time and in this context.

In the future I will post more about not so know java features.

 

Technorati Tags: ,,,,,,,,,
Windows Live Tags: Java,Initialization,Blocks,Instance,Static,constructor,initialize,variables,context,class
WordPress Tags: Java,Initialization,Blocks,Instance,Static,constructor,initialize,variables,context,class

Error starting jBoss inside eclipse

You install jBoss 7. Unzip it to a folder like d:\jboss.

Now install jboss tools 3.3 for eclipse indigo.

When you start the jboss from eclipse (servers tab) you get an error. The console in eclipse doesn’t show any log activity and jboss doesn’t start.

After some research you discover that eclipse cant “talk” with jboss. You can confirm this by reading jboss logs.

You start jboss with standalone.bat and it works.

I got this problem in our dev team, and after some research around I found this solution. It was so simple and at the same time one of that problems that make us thinking about changing to other version or product that I thought it was a good idea to share it.

Possible solution:

1) Go to runtime environment in eclipse options and add jdk runtime environment. Not jre.

2) Make sure that you remove the JRE probably already installed and configured  from eclipse. (really! Remove it from eclipse and just let the jdk as an environment).

3) Now, start jboss from the tab servers. It must work by now.

 

Technorati Tags: ,,,,,
Windows Live Tags: troubleshooting,java,eclipse,j2ee,Error,jboss
WordPress Tags: troubleshooting,java,eclipse,j2ee,Error,jboss

Bad Behavior has blocked 26 access attempts in the last 7 days.

Hyper Smash