Best java questions in July 2012

How does the String class override the + operator?

70 votes

Why in Java can you add Strings with the + operator when String is a class? In theString.java code I did not find any implementation for this operator. Does this concept violate object orientation?

Let's look at the following simple expressions in Java

int x=15;
String temp="x = "+x;

The compiler converts "x = "+x; into a StringBuilder internally and uses .append(int) to "add" the integer to the string.

From the Java Language Specification:

15.18.1.1 String Conversion

Any type may be converted to type String by string conversion. A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:

If T is boolean, then use new Boolean(x). If T is char, then use new Character(x). If T is byte, short, or int, then use new Integer(x). If T is long, then use new Long(x). If T is float, then use new Float(x). If T is double, then use new Double(x). This reference value is then converted to type String by string conversion. Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

The toString method is defined by the primordial class Object; many classes override it, notably Boolean, Character, Integer, Long, Float, Double, and String.

15.18.1.2 Optimization of String Concatenation

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression. For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

The optimized version will not actually do a full wrapped String conversion first.

This is a good illustration of an optimized version used by the compiler, albeit without the conversion of a primitive, where you can see the compiler changing things into a StringBuilder in the background:

http://caprazzi.net/posts/java-bytecode-string-concatenation-and-stringbuilder/


This java code:

public static void main(String[] args) {
    String cip = "cip";
    String ciop = "ciop";
    String plus = cip + ciop;
    String build = new StringBuilder(cip).append(ciop).toString();
}

Generates this - see how the two concatenation styles lead to the very same bytecode:

 L0
    LINENUMBER 23 L0
    LDC "cip"
    ASTORE 1
   L1
    LINENUMBER 24 L1
    LDC "ciop"
    ASTORE 2
// cip + ciop
   L2
    LINENUMBER 25 L2

    NEW java/lang/StringBuilder
    DUP
    ALOAD 1
    INVOKESTATIC java/lang/String.valueOf(Ljava/lang/Object;)Ljava/lang/String;
    INVOKESPECIAL java/lang/StringBuilder.<init>(Ljava/lang/String;)V
    ALOAD 2
    INVOKEVIRTUAL java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;

    ASTORE 3
    // new StringBuilder(cip).append(ciop).toString()
   L3
    LINENUMBER 26 L3

    NEW java/lang/StringBuilder
    DUP
    ALOAD 1
    INVOKESPECIAL java/lang/StringBuilder.<init>(Ljava/lang/String;)V
    ALOAD 2
    INVOKEVIRTUAL java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;

    ASTORE 4
   L4
    LINENUMBER 27 L4
    RETURN

The compiler has transformed cip+ciop into new StringBuilder(cip).append(ciop).toString(). In other words, + is effectively a shorthand for the more verbose StringBuilder idiom.

Static fields on a null reference in Java

52 votes

static fields (or static methods) in Java are associated with their respective classes rather than the objects of those classes. The following code attempts to invoke a static field on a null reference.

public class Main
{
    private static final int value = 10;

    public Main getNull()
    {
        return null;
    }

    public static void main(String[] args)
    {
        Main main=new Main();
        System.out.println("value = "+main.getNull().value);
    }
}

Although main.getNull() returns null, it works and displays value = 10. How does this code work?

That behaviour is specified in the Java Language Specification:

a null reference may be used to access a class (static) variable without causing an exception.

In more details, a static field evaluation, such as Primary.staticField works as follows (emphasis mine) - in your case, Primary = main.getNull():

  • The Primary expression is evaluated, and the result is discarded. [...]
  • If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression. [...]

What additional rotation is required for deletion from a Top-Down 2-3-4 Left-leaning Red Black tree?

41 votes

I have been implementing an LLRB package that should be able to operate in either of the two modes, Bottom-Up 2-3 or Top-Down 2-3-4 described by Sedgewick (code - improved code, though dealing only with 2-3 trees here, thanks to RS for pointer).

Sedgewick provides a very clear description of tree operations for the 2-3 mode, although he spends a lot of time talking about the 2-3-4 mode. He also shows how a simple alteration of the order of color flipping during insertion can alter the behaviour of the tree (either split on the way down for 2-3-4 or split on the way up for 2-3):

private Node insert(Node h, Key key, Value value)
{
    if (h == null)
        return new Node(key, value);

    // Include this for 2-3-4 trees
    if (isRed(h.left) && isRed(h.right)) colorFlip(h);

    int cmp = key.compareTo(h.key);

    if (cmp == 0)     h.val = value;
    else if (cmp < 0) h.left = insert(h.left, key, value);
    else              h.right = insert(h.right, key, value);

    if (isRed(h.right) && !isRed(h.left))    h = rotateLeft(h);
    if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);

    // Include this for 2-3 trees
    if (isRed(h.left) && isRed(h.right)) colorFlip(h);

    return h;
}

However, he glosses over deletion in 2-3-4 LLRBs with the following:

The code on the next page is a full implementation of delete() for LLRB 2-3 trees. It is based on the reverse of the approach used for insert in top-down 2-3-4 trees: we perform rotations and color flips on the way down the search path to ensure that the search does not end on a 2-node, so that we can just delete the node at the bottom. We use the method fixUp() to share the code for the color flip and rotations following the recursive calls in the insert() code. With fixUp(), we can leave right-leaning red links and unbalanced 4-nodes along the search path, secure that these conditions will be fixed on the way up the tree. (The approach is also effective 2-3-4 trees, but requires an extra rotation when the right node off the search path is a 4-node.)

His delete() function:

private Node delete(Node h, Key key)
{
    if (key.compareTo(h.key) < 0)
        {
            if (!isRed(h.left) && !isRed(h.left.left))
            h = moveRedLeft(h);
            h.left = delete(h.left, key);
        }
    else
        {
            if (isRed(h.left))
                h = rotateRight(h);
            if (key.compareTo(h.key) == 0 && (h.right == null))
                return null;
            if (!isRed(h.right) && !isRed(h.right.left))
                h = moveRedRight(h);
            if (key.compareTo(h.key) == 0)
                {
                    h.val = get(h.right, min(h.right).key);
                    h.key = min(h.right).key;
                    h.right = deleteMin(h.right);
                }
            else h.right = delete(h.right, key);
        }
    return fixUp(h);
}

My implementation correctly maintains LLRB 2-3 invariants for all tree operations on 2-3 trees, but fails for a subclass of right-sided deletions on 2-3-4 trees (these failing deletions result in right leaning red nodes, but snowball to tree imbalance and finally null pointer dereferencing). From a survey of example code that discusses LLRB trees and includes options for construction of trees in either mode, it seems that none correctly implements the deletion from a 2-3-4 LLRB (i.e. none has the extra rotation alluded to, e.g. Sedgewick's java above and here).

I'm having trouble figuring out exactly what he means by "extra rotation when the right node off the search path is a 4-node"; presumably this is a rotate left, but where and when?

If I rotate left passing upwards past a 4-node equivalent (i.e. RR node) or a right leaning 3-node equivalent (BR node) either before calling fixUp() or at the end of the fixUp function I still get the same invariant contradiction.

Here are the tree states of the smallest failing examples I have found (generated by sequential insertion of elements from 0 to the respective maximum value).

The first pair of trees shows the transition from invariant-conforming state prior to deletion of element 15 to obviously broken state after.

A 2-3-4 LLRB containing 0..15

State after deleting item 15

The second is essentially the same as above, but with deletion of 16 of 0..16 (deletion of 15 results in the same topology). Note that the invariant contradiction manages to cross the root node.

A 2-3-4 LLRB containing 0..16

State after deleting item 16

The key is going to be understanding how to revert the violations generated during the walk down the tree to the target node. The following two trees show how the first tree above looks after a walk down the left and right respectively (without deletion and before walking back up with fixUp()).

After attempt to delete '-1' without fixUp: After attempt to delete '-1' without fixUp

After attempt to delete '16' without fixUp: After attempt to delete '16' without fixUp

Trying rotate left on the walk back up when the node has only a red right child seems to be part of the solution, but it does not deal correctly with two red right children in a row, preceding this with a flipColor when both children are red seems to improve the situation further, but still leaves some invariants violated.

If I further check whether the right child of a right child is red when its sibling is black and rotate left if this is true I only fail once, but at this point I feel like I'm needing a new theory rather than a new epicycle.

Any ideas?

For reference, my implementation is available here (No, it's not Java).

Follow-up:

Part of the reason I was interested in this was to confirm the claim by many that 2-3 LLRB trees are more efficient that 2-3-4 LLRB trees. My benchmarking has confirmed this for insertion and deletion (2-3 are about 9% faster), but I find that retrieval is very slightly faster for 2-3-4 trees.

The following times are representative and consistent across runs:

BU23:
BenchmarkInsert        1000000        1546 ns/op
BenchmarkDelete        1000000        1974 ns/op
BenchmarkGet           5000000         770 ns/op

TD234:
BenchmarkInsert        1000000        1689 ns/op
BenchmarkDelete        1000000        2133 ns/op
BenchmarkGet           5000000         753 ns/op

First column is bench name, second is number of operations, third is result. Benchmark on i5M 2.27.

I have had a look at branch lengths for 2-3 tree and 2-3-4 trees and there is little in that to explain the retrieval difference (mean distance from root to node and S.D. of 1000 trees each with 10000 random inserts):

Means:
TD234 leafs  BU23 leafs 
 12.88940     12.84681 
TD234 all    BU23 all 
 11.79274     11.79163 

StdDev:
TD234 leafs  BU23 leafs 
 1.222458     1.257344 
TD234 all    BU23 all 
 1.874335     1.885204 

Updated and verified

Of key importance to testing this is that the implementation doesn't support deleting a nonexistent or previously deleted node! I spent way too long trying to figure out why my working solution was "broken". This can be fixed by doing a preliminary search for the key and returning false if it's not in the tree at all, and that solution was employed in the linked code at the bottom.

It doesn't appear Sedgewick wrote a deletion for 2-3-4 deletion that is publicly available. His results specifically deal with 2-3 trees (he only makes cursory mention of 2-3-4 trees in that their average path length (and thus search cost), as well as that of other red-black trees, is indistinguishable from the 2-3 case). Nobody else seems to have one easily found, either, so here's what I found after debugging the problem:

To begin, take Sedgewick's code and fix the out of date bits. In the slides here (pg 31) you can see that his code still uses the old representation of 4 nodes where it was done by having two left reds in a row, rather than balance. The first bit to write a 2-3-4 deletion routine, then, is to fix this so that we can do a sanity check which will help us verify our fixes later:

private boolean is234(Node x)
{         
   if (x == null)
      return true;
   // Note the TD234 check is here because we also want this method to verify 2-3 trees
   if (isRed(x.right))
      return species == TD234 && isRed(x.left);

   if (!isRed(x.right))
      return true;

   return is234(x.left) && is234(x.right);
} 

Once we have this, we know a couple things. One, from the paper we see that 4 nodes should not be broken on the way up when using a 2-3-4 tree. Two, there's a special case for a right 4-node on the search path. There's a third special case that isn't mentioned, and that is when you are going back up a tree, you may end up where you have h.right.left be red, which would leave you invalid with just a rotate left. This is the mirror of the case described for insert on page 4 of the paper.

The rotation fix for a 4-node you need is as follows:

    private Node moveRedLeft(Node h)
    {  // Assuming that h is red and both h.left and h.left.left
       // are black, make h.left or one of its children red.
       colorFlip(h);
       if (isRed(h.right.left))
       { 
          h.right = rotateRight(h.right);

          h = rotateLeft(h);
          colorFlip(h);

          if (isRed(h.right.right) )
             h.right = rotateLeft(h.right);
       }
      return h;
    }

And this removes the splitting on 2-3-4, as well as adds the fix for the third special case

private Node fixUp(Node h)
{
   if (isRed(h.right))
   {      
      if (species == TD234 && isRed(h.right.left))
         h.right = rotateRight(h.right);
      h = rotateLeft(h);
   }

   if (isRed(h.left) && isRed(h.left.left))
      h = rotateRight(h);

   if (species == BU23 && isRed(h.left) && isRed(h.right))
      colorFlip(h);

   return setN(h);
}

Finally, we need to test this and make sure it works. They don't have to be the most efficient, but as I found during the debugging of this, they have to actually work with the expected tree behavior (i.e. not insert/delete duplicate data)! I did this with a test helper methods. The commented lines were there for when I was debugging, I'd break and check the tree for obvious imbalance. I've tried this method with 100000 nodes, and it performed flawlessly:

   public static boolean Test()
   {
      return Test(System.nanoTime());
   }
   public static boolean Test(long seed)
   {
      StdOut.println("Seeding test with: " + seed);
      Random r = new Random(seed);
      RedBlackBST<Integer, Integer> llrb = new RedBlackBST<Integer,Integer>(TD234);
      ArrayList<Integer> treeValues = new ArrayList<Integer>();
      for (int i = 0; i < 1000; i++)
      {
         int val = r.nextInt();
         if (!treeValues.contains(val))
         {
            treeValues.add(val);
            llrb.put(val, val);
         }
         else
            i--;
      }
      for (int i = 0; i < treeValues.size(); i++)
      {
         llrb.delete(treeValues.get(i));
         if (!llrb.check())
         {
            return false;
         }
//         StdDraw.clear(Color.GRAY);
//         llrb.draw(.95, .0025, .008);
      }
      return true;
   }

The complete source can be found here.

Multiple Main Functions

40 votes

I'm a bit new at this so bear with me. I'm currently learning C# and Java and one of their similarities is that the main function needs to be encapsulated within a class. For example

public class HelloWorld {
    public static void main(String[] args) {
        // Some Code
    }
}

Now I understand that main is often the "entry point" when you run the program. So basically, your program will start executing wherever the main function is. But I believe in both languages you can have multiple main functions within multiple classes. So when I compile a project with multiple main functions, where is the "entry point"? How does the compiler know where to start?

In .NET, you can define which class contains the Main method you want to use when you're compiling.

http://msdn.microsoft.com/en-us/library/x3eht538.aspx

In Java, if you're bundling to a jar, you can define your entry point in the jar's manifest.

http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

What are the cases in which it is better to use unconditional AND (& instead of &&)

35 votes

I'd like to know some cases in Java (or more generally: in programming) when it is preferred in boolean expressions to use the unconditional AND (&) instead of the conditional version (&&).

I know how they work, but I cannot think about a case when use the single & is worth it.

I have found cases in real life where both sides of the expression were really cheap, so it shaved off a nanosecond or two to avoid the branch and to use the unconditional & instead of &&. (These were extremely high-performance math utilities, though; I would almost never use this in other code, and I wouldn't have done it anyway without exhaustive benchmarking to prove it was better.)

(To give specific examples, x > 0 is going to be super cheap and side-effect-free. Why bother risking a branch misprediction to avoid a test that's going to be so cheap anyway? Sure, since it's a boolean the end result is going to be used in a branch anyway, but if (x >= 0 && x <= 10) involves two branches, and if (x >= 0 & x <= 10) involves only one.)

Method Chaining in Java

28 votes

While answering a few questions on here earlier and from some work I have been doing lately I have been wondering why Java does not support method chaining on its built in classes.

If I were to create a Car class for example, I could make it chainable by reutrning this instead of void as follows:

public class Car {
    private String make;        

    public Car setMake(String make) {
        this.make = make;
        return this;
    }   
}

Is there any particular reason why the built in libraries don't tend to do things this way? Is there a downside to method chaining?

I may have overlooked something which would explain the lack of method chaining however any setter method that returns void by default should return a reference to this (at least in my eyes it should). This would make situations like the following much cleaner.

container.add((new JLabel("label text")).setMaximumSize(new Dimension(100,200)));

rather than the more long winded: Note: It would not stop you from coding this way if you wished.

JLabel label = new JLabel("label text");
label.setMaximumSize(new Dimension(100,200));
container.add(label);

I would be very interested to hear the reasons behind this decision, If I had to guess it would be that there is an overhead associated with this and so should only be used when needed.

Eh. There's readability arguments to be made in both directions -- there's such a thing as trying to put too much into a single line.

But honestly, I suspect here it's for historical reasons: pervasive "chaining" behavior hadn't really become popular or well-known when e.g. Swing was being developed. You could argue that it should've been added in later on, but things like that tend to create binary incompatibilities and other issues that Sun/Oracle have historically been extremely cautious about.

More recent JDK libraries -- see e.g. ByteBuffer for a major, well-known example -- have provided chaining behavior and the like, where it makes sense.

Covariance and Overloading in Java

27 votes
class A {
   boolean f(A a) { return true; }
}
class B extends A {
   boolean f(A a) { return false; } // override A.f(A)
   boolean f(B b) { return true; }  // overload A.f
}

void f() {  
   A a = new A();
   A ab = new B();
   B b = new B();
   ab.f(a); ab.f(ab); ab.f(b); //(1) false, false, *false*
   b.f(a); b.f(ab); b.f(b);    //(2) false, false, true
}

Can you please explain the first line last false output, why it is not true?

can you please explain the first line last false output, why it is not true?

The compile-time type of ab is A, so the compiler - which is what performs overload resolution - determines that the only valid method signature is f(A a), so it calls that.

At execution time, that method signature is executed as B.f(A a) because B overrides it.

Always remember that the signature is chosen at compile time (overloading) but the implementation is chosen at execution time (overriding).

Don't get it. Why not JUL?

26 votes

For the first time in my life I find myself in a position where I'm writing a Java API that will be open sourced. Hopefully to be included in many other projects.

For logging I (and indeed the people I work with) have always used JUL (java.util.logging) and never had any issues with. However now I need to understand in more detail what I should do for my API development. I've done some research on this and with the information I've got I just get more confused. Hence this post.

Since I come from JUL I'm biased on that. My knowledge of the rest is not that big.

From the research I've done I've come up with these reasons why people do not like JUL:

  1. "I started developing in Java long before Sun released JUL and it was just easier for me to continue with logging-framework-X rather than to learn something new". Hmm. I'm not kidding, this is actually what people say. With this argument we could all be doing COBOL. (however I can certainly relate to this being a lazy dude myself)

  2. "I don't like the names of the logging levels in JUL". Ok, seriously, this is just not enough of a reason to introduce a new dependency.

  3. "I don't like the standard format of the output from JUL". Hmm. This is just configuration. You do not even have to do anything code-wise. (true, back in old days you may have had to create your own Formatter class to get it right).

  4. "I use other libraries that also use logging-framework-X so I thought it easier just to use that one". This is a cyclic argument, isn't ? Why does 'everybody' use logging-framework-X and not JUL?

  5. "Everybody else is using logging-framework-X". This to me is just a special case of the above. Majority is not always right.

So the real big question is why not JUL?. What is it I have missed ? The raison d'être for logging facades (SLF4J, JCL) is that multiple logging implementations have existed historically and the reason for that really goes back to the era before JUL as I see it. If JUL was perfect then logging facades wouldn't exist, or what? Rather than embracing them shouldn't we question why they were necessary in the first place? (and see if those reasons still exist)

Ok, my research so far has led to a couple of things that I can see may be real issues with JUL:

  1. Performance. Some say that performance in SLF4J is superior to the rest. This seems to me to be a case of premature optimization. If you need to log hundreds of megabytes per second then I'm not sure you are on the right path anyway. JUL has also evolved and the tests you did on Java 1.4 may no longer be true. You can read about it here and this fix has made it into Java 7. Many also talk about the overhead of string concatenation in logging methods. However template based logging avoids this cost and it exist also in JUL. Personally I never really write template based logging. Too lazy for that. For example if I do this with JUL:

    log.finest("Lookup request from username=" + username 
       + ", valueX=" + valueX
       + ", valueY=" + valueY));
    

    my IDE will warn me and ask permission that it should change it to:

    log.log(Level.FINEST, "Lookup request from username={0}, valueX={1}, valueY={2}", 
       new Object[]{username, valueX, valueY});
    

    .. which I will of course accept. Permission granted ! Thank you for your help.

    So I don't actually write such statements myself, that is done by the IDE.

    In conclusion on the issue of performance I haven't found anything that would suggest that JUL's performance is not ok compared to the competition.

  2. Configuration from classpath. Out-of-the-box JUL cannot load a configuration file from the classpath. It is a few lines of code to make it do so. I can see why this may be annoying but the solution is short and simple.

  3. Availability of output handlers. JUL comes with 5 output handlers out-of-the-box: console, file stream, socket and memory. These can be extended or new ones can be written. This may for example be writing to UNIX/Linux Syslog and Windows Event Log. I have personally never had this requirement nor have I seen it used but I can certainly relate to why it may be a useful feature. Logback comes with an appender for Syslog for example. Still I would argue that

    1. 99.5% of the needs for output destinations are covered by what is in JUL out-of-the-box.
    2. Special needs could be catered for by custom handlers on top of JUL rather than on top of something else. There's nothing to me that suggests that it takes more time to write a Syslog output handler for JUL than it does for another logging framework.

I'm really concerned that there's something I've overlooked. The use of logging facades and logging implementations other than JUL is so widespread that I have to come to the conclusion that it's me who just doesn't understand. That wouldn't be the first time, I'm afraid. :-)

So what should I do with my API? I want it to become successful. I can of course just "go with the flow" and implement SLF4J (which seems the most popular these days) but for my own sake I still need to understand exactly what is wrong with the JUL of today that warrants all the fuzz? Will I sabotage myself by choosing JUL for my library ?

Testing performance

(section added by nolan600 on 07-JUL-2012)

There's a reference below from Ceki about SLF4J's parametrization being 10 times or more faster than JUL's. So I've started doing some simple tests. At first glance the claim is certainly correct. Here are the preliminary results (but read on!):

  • Execution time SLF4J, backend Logback: 1515
  • Execution time SLF4J, backend JUL: 12938
  • Execution time JUL: 16911

The numbers above are msecs so less is better. So 10 times performance difference is by first actually pretty close. My initial reaction: That is a lot !

Here is the core of the test. As can be seen an integer and a string is construted in a loop which is then used in the log statement:

    for (int i = 0; i < noOfExecutions; i++) {
        for (char x=32; x<88; x++) {
            String someString = Character.toString(x);
            // here we log 
        }
    }

(I wanted the log statement to have both a primitive data type (in this case an int) and a more complex data type (in this case a String). Not sure it matters but there you have it.)

The log statement for SLF4J:

logger.info("Logging {} and {} ", i, someString);

The log statement for JUL:

logger.log(Level.INFO, "Logging {0} and {1}", new Object[]{i, someString});

The JVM was 'warmed up' with the same test executed once before the actual measurement was done. Java 1.7.03 was used on Windows 7. Latest versions of SLF4J (v1.6.6) and Logback (v1.0.6) was used. Stdout and stderr was redirected to null device.

However, careful now, it turns out JUL is spending most of its time in getSourceClassName() because JUL by default prints the source class name in the output, while Logback doesn't. So we are comparing apples and oranges. I have to do the test again and configure the logging implementations in a similar manner so that they actually output the same stuff. I do however suspect that SLF4J+Logback will still come out on top but far from the initial numbers as given above. Stay tuned.

Btw: The test was first time I've actually worked with SLF4J or Logback. A pleasant experience. JUL is certainly a lot less welcoming when you are starting out.

Testing performance (part 2)

(section added by nolan600 on 08-JUL-2012)

As it turns out it doesn't really matter for performance how you configure your pattern in JUL, i.e. whether or not it includes the source name or not. I tried with a very simple pattern:

java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"

and that did not change the above timings at all. My profiler revealed that the logger still spent a lot of time in calls to getSourceClassName() even if this was not part of my pattern. The pattern doesn't matter.

I'm therefore concluding on the issue of performance that at least for the tested template based log statement there seems to be roughly a factor of 10 in real performance difference between JUL (slow) and SLF4J+Logback (quick). Just like Ceki said.

I can also see another thing namely that SLF4J's getLogger() call is a lot more expensive than JUL's ditto. (95 ms vs 0.3 ms if my profiler is accurate). This makes sense. SLF4J has to do some time on the binding of the underlying logging implementation. This doesn't scare me. These calls should be somewhat rare in the lifetime of an application. The fastness should be in the actual log calls.

Final conclusion

(section added by nolan600 on 08-JUL-2012)

Thank you for all your answers. Contrary to what I initially thought I've ended up deciding to use SLF4J for my API. This is based on a number of things and your input:

  1. It gives flexibility to choose log implementation at deployment time.

  2. Issues with lack of flexibility of JUL's configuration when run inside an application server.

  3. SLF4J is certainly a lot faster as detailed above in particular if you couple it with Logback. Even if this was just a rough test I have reason to believe that a lot more effort has gone into optimization on SLF4J+Logback than on JUL.

  4. Documentation. The documentation for SLF4J is simply a lot more comprehensive and precise.

  5. Pattern flexibility. As I did the tests I set out to have JUL mimic the default pattern from Logback. This pattern includes the name of the thread. It turns out JUL cannot do this out of the box. Ok, I haven't missed it until now, but I don't think it is a thing that should be missing from a log framework. Period!

  6. Most (or many) Java projects today use Maven so adding a dependency is not that big a thing especially if that dependency is rather stable, i.e. doesn't constantly change its API. This seems to be true for SLF4J. Also the SLF4J jar and friends are small in size.

So the strange thing that happened was that I actually got quite upset with JUL after having worked a bit with SLF4J. I still regret that it has to be this way with JUL. JUL is far from perfect but kind of does the job. Just not quite well enough. The same can be said about Properties as an example but we do not think about abstracting that so people can plug in their own configuration library and what have you. I think the reason is that Properties comes in just above the bar while the opposite is true for JUL of today ... and in the past it came in at zero because it didn't exist.

Disclaimer: I am the founder of log4j, SLF4J and logback projects.

There are objective reasons for preferring SLF4J. For one, it grants the end-user the liberty to choose the underlying logging framework. In addition, savvier users tend to prefer logback which offers capabilities beyond log4j, with j.u.l falling way behind. Feature-wise j.u.l may be sufficient for some users but for many others it just isn't. In a nutshell, if logging is important to you, you would want to use SLF4J with logback as the underlying implementation. If logging is unimportant, j.u.l is fine.

However, as an oss developer, you need to take into account the preferences of your users and not just your own. It follows that you should adopt SLF4J not because you are convinced that SLF4J is better than j.u.l but because most Java developers currently (July 2012) prefer SLF4J as their logging API. If ultimately you decide not to care about popular opinion, consider the following facts:

  1. those who prefer j.u.l do so out of convenience because j.u.l is bundled with the JDK. To my knowledge there are no other objective arguments in favor of j.u.l.
  2. your own preference for j.u.l is just that, a preference.

Thus, holding "hard facts" above public opinion, while seemingly brave, is a logical fallacy in this case.

If still not convinced, JB Nizet makes an additional and potent argument:

Except the end user could have already done this customization for his own code, or another library that uses log4j or logback. j.u.l is extensible, but having to extend logback, j.u.l, log4j and God only knows which other logging framework because he uses four libraries that use four different logging frameworks is cumbersome. By using SLF4J, you allow him to configure the logging frameworks he wants, not the one you have chosen. Remember that a typical project uses myriads of libraries, and not just yours.

If for whatever reason you hate the SLF4J API and using it will snuff the fun out of your work, then by all means go for j.u.l. After all, there are means to redirect j.u.l to SLF4J.

By the way, j.u.l parametrization is at least 10 times slower than SLF4J's which ends up making a noticeable difference.

I can't wrap my head around the "draw some stairs with stick-men" program

20 votes

You've probably seen it before in a Java 1 class: it's a problem that asks you write a program that draws the following figure:

enter image description here

I have to use a constant. I am not allowed to use anything but for-loops, print, and println. No parameters, no arrays. I know how I could do it with parameters and arrays, lucky me. Any help is appreciated!

Here is my incomplete code:

public class Stairs {
    public static final int LENGTH=5;

    public static void main(String[] args) {
        printStairs();
    }

    public static void printStairs() {
        for (int allStairs=1; allStairs<=15; allStairs++) {
            for (int spaces=1; spaces<=(-5*allStairs+30); spaces++) {
                System.out.print(" ");
            }
            for (int stair = 1; stair <= 5; stair++) {
                System.out.println("  o  *******");

            }
        }
    }
}

This sounds like a homework question, so I don't just want to give you the answer, but try breaking it down into steps. Think about the things that you know:

1) Every stickman has this shape:

  o  ******
 /|\ *     
 / \ *     

2) You can print this out using the following code:

System.out.println("  o  ******");
System.out.println(" /|\ *     ");
System.out.println(" / \ *     ");

3) You can print multiple by using a loop:

for (int stair = 1; stair <= LENGTH; stair++) {
    System.out.println("  o  ******");
    System.out.println(" /|\ *     ");
    System.out.println(" / \ *     ");
}

Think about what kind of output this would give you, and what needs to be changed. Realize that each stickman needs to be indented a certain amount. Figure out how to indent them appropriately based on the value of stair.

Generic method with parameters vs. non-generic method with wildcards

17 votes

According to this entry in the Java Generics FAQ, there are some circumstances where a generic method has no equivalent non-generic method that uses wildcard types. According to that answer,

If a method signature uses multi-level wildcard types then there is always a difference between the generic method signature and the wildcard version of it.

They give the example of a method <T> void print1( List <Box<T>> list), which "requires a list of boxes of the same type." The wildcard version, void print2( List <Box<?>> list), "accepts a heterogenous list of boxes of different types," and thus is not equivalent.

How do you interpret the the differences between the following two method signatures:

 <T extends Iterable<?>> void f(Class<T> x) {}
                         void g(Class<? extends Iterable<?>> x) {}

Intuitively, it seems like these definitions should be equivalent. However, the call f(ArrayList.class) compiles using the first method, but the call g(ArrayList.class) using the second method results in a compile-time error:

g(java.lang.Class<? extends java.lang.Iterable<?>>) in Test
    cannot be applied to (java.lang.Class<java.util.ArrayList>)

Interestingly, both functions can be called with each others' arguments, because the following compiles:

class Test {
    <T extends Iterable<?>> void f(Class<T> x) {
        g(x);
    }
    void g(Class<? extends Iterable<?>> x) {
        f(x);
    }
}

Using javap -verbose Test, I can see that f() has the generic signature

<T::Ljava/lang/Iterable<*>;>(Ljava/lang/Class<TT;>;)V;

and g() has the generic signature

(Ljava/lang/Class<+Ljava/lang/Iterable<*>;>;)V;

What explains this behavior? How should I interpret the differences between these methods' signatures?

Well, going by the spec, neither invocation is legal. But why does the first one type check while the second does not?

The difference is in how the methods are checked for applicability (see §15.12.2 and §15.12.2.2 in particular).

  • For simple, non-generic g to be applicable, the argument Class<ArrayList> would need to be a subtype of Class<? extends Iterable<?>>. That means ? extends Iterable<?> needs to contain ArrayList, written ArrayList <= ? extends Iterable<?>. Rules 4 and 1 can be applied transitively, so that ArrayList needs to be a subtype of Iterable<?>.

    Going by §4.10.2 any parameterization C<...> is a (direct) subtype of the raw type C. So ArrayList<?> is a subtype of ArrayList, but not the other way around. Transitively, ArrayList is not a subtype of Iterable<?>.

    Thus g is not applicable.

  • f is generic, for simplicity let us assume the type argument ArrayList is explicitly specified. To test f for applicability, Class<ArrayList> needs to be a subtype of Class<T> [T=ArrayList] = Class<ArrayList>. Since subtyping is reflexisve, that is true.

    Also for f to be applicable, the type argument needs to be within its bounds. It is not because, as we've shown above, ArrayList is not a subtype of Iterable<?>.

So why does it compile anyways?

It's a bug. Following a bug report and subsequent fix the JDT compiler explicitly rules out the first case (type argument containment). The second case is still happily ignored, because the JDT considers ArrayList to be a subtype of Iterable<?> (TypeBinding.isCompatibleWith(TypeBinding)).

I don't know why javac behaves the same, but I assume for similar reasons. You will notice that javac does not issue an unchecked warning when assigning a raw ArrayList to an Iterable<?> either.

Thread.sleep() Never Returns

16 votes

I am having an odd error with Thread.sleep() on Java. For some reason, when I call sleep on some machines, it never returns. I can't figure out what could be causing this behaviour. At first, I thgouth the error might be elsewhere in my code, so I made the simplest possible sleep test:

public class SleepTest {
    public static void main (String [] args) {
        System.out.println ("Before sleep...");
        try {
            Thread.sleep (100);
        } catch (InterruptedException e) {
        }
        System.out.println ("After sleep...");
    }
}

On most machines it works, but on several machines which I am remotely logging into, it pauses indefinitely between the print statements. I have waited up to a half an hour with no change in behaviour. The machines that are displaying this error are Linux machines. Here is some information about the machines:

$ uname -a
Linux zone29ea 2.6.32-220.17.1.el6.x86_64 #1 SMP Tue May 15 17:16:46 CDT 2012 x86_64 x86_64 x86_64 GNU/Linux
$ java -version
java version "1.6.0_22"
OpenJDK Runtime Environment (IcedTea6 1.10.6) (rhel-1.43.1.10.6.el6_2-x86_64)
OpenJDK 64-Bit Server VM (build 20.0-b11, mixed mode)

What could be causing this behaviour?

UPDATE

Revised version, which still never ends:

public class SleepTest {
    public static void main (String [] args) {
        new Thread () {
            public void run () {
                System.out.println ("Before sleep...");
                try {
                    Thread.sleep (100);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                System.out.println ("After sleep...");
            }
        }.start();
    }
}

if your server is running under Linux, you may be hit by the Leap Second bug which appears last week-end.

This bug affects the Linux kernel (the Thread management), so application which uses threads (as the JVM, mysql etc...) may consume high load of CPU.

What is the difference between declaration and definition in Java?

16 votes

I'm very confused between the two terms. I checked on stackoverflow and there's a similar question for C++ but not for java.

Can someone explain the difference between the two terms for java?

The conceptual difference is simple:

  • Declaration: You are declaring that something will come, such as a class, function or variable. You don't say anything about what that class or function looks like, you just say that you will say what it looks like.

  • Definition: You define how something is implemented, such as a class, function or variable, i.e. you say what it actually is.

In Java, there is little difference between the two, and formally speaking, a declaration includes not only the identifier, but also it's definition. Here is how I personally interpret the terms in detail:

  • Classes: Java doesn't really separate them as C/C++ does (in header and cpp files). You define them at the point where you declare them.

  • Functions: When you're writing an interface (or an abstract class), you could say that you're declaring a function, without defining it. Ordinary functions however, are always defined right where they are declared. See the body of the function as its definition if you like.

  • Variables: A variable declaration could look like this:

    int x;
    

    (you're declaring that a variable x exists and has type int) either if it's a local variable or member field. In Java, there's no information left about x to define, except possible what values it shall hold, which is determined by the assignments to it.

Here's a rough summary of how I use the terms:

abstract class SomeClass {                // class decl.
                                          //                           \
    int x;                                // variable decl. and def.   |
                                          //                           |
    public abstract void someMethod();    // function decl.            |
                                          //                           |
    public int someOtherMethod() {        // function decl.            |
                                          //                           | class
        if (Math.random() > .5)           // \                         | def.
            return x;                     //  |  function definition   |
        else                              //  |                        |
            return -x;                    // /                         |
                                          //                           |
    }                                     //                           |
}                                         //                          /

How can I analyse ~13GB of data?

15 votes

I have ~300 text files that contain data on trackers, torrents and peers. Each file is organised like this:

tracker.txt

time torrent
    time peer
    time peer
    ...
time torrent
...

I have several files per tracker and much of the information is repeated (same information, different time).

I'd like to be able to analyse what I have and report statistics on things like

  • How many torrents are at each tracker
  • How many trackers are torrents listed on
  • How many peers do torrents have
  • How many torrents to peers have

The sheer quantity of data is making this hard for me to. Here's What I've tried.

MySQL

I put everything into a database; one table per entity type and tables to hold the relationships (e.g. this torrent is on this tracker).

Adding the information to the database was slow (and I didn't have 13GB of it when I tried this) but analysing the relationships afterwards was a no-go. Every mildly complex query took over 24 hours to complete (if at all).

An example query would be:

SELECT COUNT(DISTINCT torrent) 
    FROM TorrentAtPeer, Peer 
    WHERE TorrentAtPeer.peer = Peer.id 
    GROUP BY Peer.ip;

I tried bumping up the memory allocations in my my.cnf file but it didn't seem to help. I used the my-innodb-heavy-4G.cnf settings file.

EDIT: Adding table details

Here's what I was using:

Peer         Torrent                  Tracker        
-----------  -----------------------  ------------------  
id (bigint)  id (bigint)              id (bigint)
ip* (int)    infohash* (varchar(40))  url (varchar(255))
port (int)

TorrentAtPeer      TorrentAtTracker
-----------------  ----------------
id (bigint)        id (bigint)
torrent* (bigint)  torrent* (bigint)
peer* (bigint)     tracker* (bigint)
time (int)         time (int)

*indexed field. Navicat reports them as being of normal type and Btree method.
id - Always the primary key

There are no foreign keys. I was confident in my ability to only use IDs that corresponded to existing entities, adding a foreign key check seemed like a needless delay. Is this naive?

Matlab

This seemed like an application that was designed for some heavy lifting but I wasn't able to allocate enough memory to hold all of the data in one go.

I didn't have numerical data so I was using cell arrays, I moved from these to tries in an effort to reduce the footprint. I couldn't get it to work.

Java

My most successful attempt so far. I found an implementation of Patricia Tries provided by the people at Limewire. Using this I was able to read in the data and count how many unique entities I had:

  • 13 trackers
  • 1.7mil torrents
  • 32mil peers

I'm still finding it too hard to work out the frequencies of the number of torrents at peers. I'm attempting to do so by building tries like this:

Trie<String, Trie<String, Object>> peers = new Trie<String, Trie<String, Object>>(...);
for (String line : file) {
    if (containsTorrent(line)) {
        infohash = getInfohash(line);
    }
    else if (containsPeer(line)) {
        Trie<String, Object> torrents = peers.get(getPeer(line));
        torrents.put(infohash, null);
    }
}

From what I've been able to do so far, if I can get this peers trie built then I can easily find out how many torrents are at each peer. I ran it all yesterday and when I came back I noticed that the log file wan't being written to, I ^Z the application and time reported the following:

real 565m41.479s
user 0m0.001s
sys  0m0.019s

This doesn't look right to me, should user and sys be so low? I should mention that I've also increased the JVM's heap size to 7GB (max and start), without that I rather quickly get an out of memory error.

I don't mind waiting for several hours/days but it looks like the thing grinds to a halt after about 10 hours.

I guess my question is, how can I go about analysing this data? Are the things I've tried the right things? Are there things I'm missing? The Java solution seems to be the best so far, is there anything I can do to get it work?

I would give MySQL another try but with a different schema:

  • do not use id-columns here
  • use natural primary keys here:

    Peer: ip, port
    Torrent: infohash
    Tracker: url
    TorrentPeer: peer_ip, torrent_infohash, peer_port, time
    TorrentTracker: tracker_url, torrent_infohash, time

  • use innoDB engine for all tables

This has several advantages:

  • InnoDB uses clustered indexes for primary key. Means that all data can be retrieved directly from index without additional lookup when you only request data from primary key columns. So InnoDB tables are somewhat index-organized tables.
  • Smaller size since you do not have to store the surrogate keys. -> Speed, because lesser IO for the same results.
  • You may be able to do some queries now without using (expensive) joins, because you use natural primary and foreign keys. For example the linking table TorrentAtPeer directly contains the peer ip as foreign key to the peer table. If you need to query the torrents used by peers in a subnetwork you can now do this without using a join, because all relevant data is in the linking table.

If you want the torrent count per peer and you want the peer's ip in the results too then we again have an advantage when using natural primary/foreign keys here.

With your schema you have to join to retrieve the ip:

SELECT Peer.ip, COUNT(DISTINCT torrent) 
    FROM TorrentAtPeer, Peer 
    WHERE TorrentAtPeer.peer = Peer.id 
    GROUP BY Peer.ip;

With natural primary/foreign keys:

SELECT peer_ip, COUNT(DISTINCT torrent) 
    FROM TorrentAtPeer 
    GROUP BY peer_ip;

EDIT Well, original posted schema was not the real one. Now the Peer table has a port field. I would suggest to use primary key (ip, port) here and still drop the id column. This also means that the linking table needs to have multicolumn foreign keys. Adjusted the answer ...

Array Initialization using { } in Java

15 votes

We can initialize an array like this:

int myArray[][] = { {10,20} ,{30,40} , {50} };

It works fine.

But I came across a peculiar situation.

int myAnotherArray[][] = { {,} ,{,} , {,} };

The above line of code compiles fine. This according to me is weird. Because when the compiler would parse this statement , it would encounter { and , and } all together. Shouldn't the compiler be expecting a constant or a literal in between ? I would appreciate it if someone would tell me how exactly the above statement is parsed and what exactly the compiler does when it encounters such a situation.

This is simply a quirk of the fact that the syntax allows for trailing commas.

Allowing trailing commas is for instance kind to code generators generating things such as { 0, 1, } and allows you to for instance conveniently comment out the last row in

int[] myArray = {
    0,
//  1
};

(As you may have figured out, trailing , is ignored, i.e. { , } yields an empty array.)

Related questions:

Is there any reason EnumMap and EnumSet are not Navigable

15 votes

Enum is Comparable which means you can have

NavigableSet<AccessMode> modes = new TreeSet<>();
NavigableMap<AccessMode, Object> modeMap = new TreeMap<>();

These have O(ln N) access times.

The Enum collections have O(1) access times, but are not Navigable

NavigableSet<AccessMode> modes = EnumSet.noneOf(AccessMode.class); // doesn't compile
NavigableMap<AccessMode, Object> modeMap = new EnumMap<>(AccessMode.class);  // doesn't compile

I was wondering if there was a reason Enum collections were not Navigable (and Sorted). i.e Am I missing something?

My best guess is that navigability was not seen as a major use case for enum sets. There is nothing in the implementation that would prevent navigability. The rare use cases that combine the need for a set of enum members with navigability are covered by the TreeSet and TreeMap.

Automate import of Java (Android) projects into Eclipse workspace through commandline

11 votes

I'm trying to automate importing projects to an Eclipse workspace via commandline (using a bash script). I have seen many posts suggesting using the CDT headless build even for non-C/C++ projects, but I want to avoid having to download CDT as my projects are all Java/Android projects and I want to be able to automate this for many people without having to make them all download CDT. I have tried the following with the JDT headless build with no avail:

eclipse -nosplash \
    -application org.eclipse.jdt.apt.core.aptBuild \
    -data [absolute_path_to_desired_workspace] \
    -import [absolute_path_to_project_directories]

Output shows "Building workspace" and then "logout," but opening a session of Eclipse in the workspace shows nothing in the Package explorer.

Looking at the ./metadata/.log file in the workspace doesn't seem to show any errors with the import.

Is it not possible to automate the import of existing Java Eclipse projects into Eclipse without using the CDT headless build?

Unfortunately, JDT distribution doesn't have any application that would support -import argument, like CDT's org.eclipse.cdt.managedbuilder.core.headlessbuild. But you can easily write a simple one:

package test.myapp;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;

public class Application implements IApplication {

    public Object start(IApplicationContext context) throws Exception {

        String[] args = (String[]) context.getArguments().get(
                IApplicationContext.APPLICATION_ARGS);

        // Determine projects to import
        List<String> projects = new LinkedList<String>();
        for (int i = 0; i < args.length; ++i) {
            if ("-import".equals(args[i]) && i + 1 < args.length) {
                projects.add(args[++i]);
            }
        }

        if (projects.size() == 0) {
            System.out.println("No projects to import!");
        } else {
            for (String projectPath : projects) {
                System.out.println("Importing project from: " + projectPath);

                // Import project description:
                IProjectDescription description = ResourcesPlugin
                        .getWorkspace().loadProjectDescription(
                                new Path(projectPath).append(".project"));
                IProject project = ResourcesPlugin.getWorkspace().getRoot()
                        .getProject(description.getName());
                project.create(description, null);
                project.open(null);
            }
        }
        return null;
    }

    public void stop() {
    }
}

Your plugin.xml should contain something like:

<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <extension
         id="App"
         point="org.eclipse.core.runtime.applications">
      <application
            cardinality="singleton-global"
            thread="main"
            visible="true">
         <run
               class="test.myapp.Application">
         </run>
      </application>
   </extension>
</plugin>

Create, and export your plug-in as "test.myapp_1.0.0.jar". Then you can use it as follows:

  1. Copy test.myapp_1.0.0.jar to your Eclipse/dropins/ folder
  2. Copy all needed plug-ins to the target workspace directory:

    cp -r projects/* NewWorkspace/

  3. Import needed projects into the workspace:

    eclipse -nosplash -application test.myapp.App -data NewWorkspace -import /path/to/NewWorkspace/project1 -import /path/to/NewWorkspace/project2 etc...

  4. Now, you can safely remove test.myapp_1.0.0.jar from the Eclipse/dropins/ folder.

I've uploaded all the code, including the exported plug-in here: https://github.com/spektom/test.myapp

Andengine low FPS on certain phones

9 votes

My game runs well on most phones (56 FPS), but others run the game at ~25 FPS. In my game I have 3 particle systems and as far as I can tell the problem comes from here. My question: Is it a good idea to stop spawning particles if I detect FPS lower than, let's say 30? An if the FPS is higher just run normally. I'm not sure if this can cause any problems. Is there any other solution?

I can think of several things you can do to help alleviate this problem.

You could use your method to detect the fps and then drop the particle systems if necessary. However, you don't have to poll it every second - you could do it once every ten seconds or so. If you do have a low frame rate, then you know the phone is going to suffer every now and then, so then you dont need to poll any more - you can lower the particles and stop polling.

Or, you could use the polling method with several "levels" of particle effects, so if it cant handle the top level, drop the the next level of complexity, and so on.

Also, you could even allow the user to manually adjust the particle effects, ie in an option menu allow them to switch them to a low setting or something.

Perhaps you could also profile devies on runtime, ie how many cores, graphics chip etc and adjust accordingly.

Make sure your particles are optimized etc, so you dont have unecessary texture sizes when they could be smaller etc, but i'm sure you've probably done this!

Best practice to use Sprites in a game using AndEngine GLES2

9 votes

Currently I am having static reference to all my sprites and loading and initializing them in my OnCreateResource mthod of SimpleBaseGameActivity, But now I have to override onAreaTouched listener on spirtes and the way I can override it while Initializing the Sprite. But I have a static method creating Atlas and Texture Region for every sprite. And I am using these sprites in my scene class and I want to override onAreaTouched there. I can registerTouchArea for that specific sprite in my scene so that can be done But I want to Override OnAreaTouched in a way so that Code reusability can be done. Here is how I am currently creating and loading sprites.

defualtCageSprite = createAndLoadSimpleSprite("bg.png", this, 450, 444);

And this is my Method createAndLoadSimpleSprite.

public static Sprite createAndLoadSimpleSprite(String name,
        SimpleBaseGameActivity activity, int width, int height) {

    BitmapTextureAtlas atlasForBGSprite = new BitmapTextureAtlas(
            activity.getTextureManager(), width, height);
    TextureRegion backgroundSpriteTextureRegion = BitmapTextureAtlasTextureRegionFactory
            .createFromAsset(atlasForBGSprite, activity, name, 0, 0);
    Sprite sprite = new Sprite(0, 0, backgroundSpriteTextureRegion,
            activity.getVertexBufferObjectManager());
    activity.getTextureManager().loadTexture(atlasForBGSprite);

    return sprite;
}

Now How Can I override onAreaTouched for some sprites while not losing the code reusability.

Is there any reason you need to load the textures at runtime? The normal way is to load the required textures all onto a single atlas while loading the application so that you can then quickly use them later.

As for the code reusability, Todilo's idea about enums seems to be pretty much what you need. Say for example that you have two kinds of objects - objects that disappear when you touch them and objects that fly up when you touch them. You enumerate both categories and put a piece of code into the touch event handling code that checks whether the object should disappear or fly up.

If you don't know what the objects should be doing on touch before running the application, there is a more dynamic way of achieving the same result. Just create two lists at runtime and put a reference to the object in one of the lists according to what the object should do when touched. Then in touch event handling do something like this:

if (disappearList.contains(touchedObject)) {
    disappear(object)
}
if (flyUpList.contains(touchedObject)) {
    flyUp(object)
}

Too bad AndEngine does not allow users to set listeners on sprites, it would make things a bit easier.

EDIT: Added explanation of the use of BlackPawnTextureBuilder: Your Atlas must be of type BuildableBitmapTextureAtlas, then you add all textures like this

BitmapTextureAtlasTextureRegionFactory.createFromAsset(buildableAtlas, this, "image.png"));

and after that

try {
    this.buildableAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1));
} catch (final TextureAtlasSourcePackingException e) {
    Debug.e(e);
}

I don't know whether this will work for animated Sprites or not, you will have to try it. Also, there is no overriding onTouch, you will have to do that in the onAreaTouched method. One example of such condition is

if (pSceneMotionEvent.getAction() == MotionEvent.ACTION_DOWN && disappearList.contains(pTouchArea)) {disappear();}

Monitor MySQL inserts from different application

8 votes

I currently have a webservice which inserts information in a mysql database using Hibernate. Some of this information needs to be processed by another 'import' application. I would like to not have to trigger this application from the webservice. So the webservice doesn't have a dependency on the webservice and visa versa.

Is there a way to "listen" to changes (specifically: insert) in the database from the 'import' application and then start executing an action. I have looked at triggers but these seem to only work for changes in the application's Hibernate Session and not for 'external' changes.

Edit*

In short, the answer I would like to have; Is it possible to monitor changes to a mysql database/table (coming from any source) from a java application which does not alter the database/table itself

Bounty Update*

I will award the bounty to the person who can explain to me how to monitor changes made to a MySQL table/database using a Java application. The Java application monitoring the changes is not the application applying any changes. The source of the alterations can be anything.

You can read mysql binary log. Here you can find some information. There is a java parser and another one - but it is marked as unfinished) also you can look for similar parsers using another languages (for example, perl) and rewrite them in Java.
Also have a look at mysql-proxy.

java - Why replaceAll is not working?

6 votes

Im starting to learn regex and I don't know if I understand it correctly.

I have a problem with function replaceAll because it does not replace the character in a string that I want to replace.

Here is my code:

public class TestingRegex {
   public static void main (String args[]) {
      String string = "Hel%l&+++o_Wor_++l%d&#";

      char specialCharacters[] = {'%', '%', '&', '_'};

      for (char sc : specialCharacters) {
          if (string.contains(sc + ""))
              string = string.replaceAll(sc + "", "\\" + sc);
      }

      System.out.println("New String: " + string);
   }
}

The output is the same as the original. Nothing changed.

I want the output to be : Hel\%l\&+++o\_Wor\_++l\%d\&\#.

Please help. Thanks in advance.

The reason why it's not working: You need four backslashes in a Java string to create a single "real" backslash.

string = string.replaceAll(sc, "\\\\" + sc);

should work. But this is not the right way to do it. You don't need a for loop at all:

String string = "Hel%l&+++o_Wor_++l%d&#";
string = string.replaceAll("[%&_]", "\\\\$0");

and you're done.

Explanation:

  • [%&_] matches any of the three characters you want to replace
  • $0 is the result of the match, so
  • "\\\\$0" means "a backslash plus whatever was matched by the regex".

Caveat: This solution is obviously not checking whether any of those characters had already been escaped previously. So

Hello\%

would become

Hello\\%

which you would not want to happen. Could this be a problem?