Best java questions in December 2011

Infinite loops in Java

61 votes

Look at the following infinite while loop in Java. It causes a compile-time error for the statement below it.

while(true)
{
     System.out.println("inside while");
}

System.out.println("while terminated"); //Unreachable statement - compiler-error.

The following same infinite while loop, however works fine and doesn't issue any errors in which I just replaced the condition with a boolean variable.

boolean b=true;

while(b)
{
     System.out.println("inside while");
}

System.out.println("while terminated"); //No error here.

In the second case also, the statement after the loop is obviously unreachable because the boolean variable b is true still the compiler doesn't complain at all. Why?


Edit : The following version of while gets stuck into an infinite loop as obvious but issues no compiler errors for the statement below it even though the if condition within the loop is always false and consequently, the loop can never return and can be determined by the compiler at the compile-time itself.

while(true)
{
    if(false)
    {
        break;
    }

    System.out.println("inside while");
}

System.out.println("while terminated"); //No error here.

while(true)
{
    if(false)  //if true then also
    {
        return;  //Replacing return with break fixes the following error.
    }

    System.out.println("inside while");
}

System.out.println("while terminated"); //Compiler-error - unreachable statement.

while(true)
{
    if(true)
    {
        System.out.println("inside if");
        return;
    }

    System.out.println("inside while"); //No error here.
}

System.out.println("while terminated"); //Compiler-error - unreachable statement.

Edit : Same thing with if and while.

if(false)
{
    System.out.println("inside if"); //No error here.
}

while(false)
{
    System.out.println("inside while"); //Compiler's complain - unreachable statement.
}

while(true)
{
    if(true)
    {
        System.out.println("inside if");
        break;
    }

    System.out.println("inside while"); //No error here.
}      

The following version of while also gets stuck into an infinite loop.

while(true)
{
    try
    {
        System.out.println("inside while");
        return;   //Replacing return with break makes no difference here.
    }
    finally
    {
        continue;
    }
}

This is because the finally block is always executed even though the return statement encounters before it within the try block itself.

The compiler can easily and unequivocally prove that the first expression always results in an infinite loop, but it's not as easy for the second. In your toy example it's simple, but what if:

  • the variable's contents were read from a file?
  • the variable wasn't local and could be modified by another thread?
  • the variable relied on some user input?

The compiler is clearly not checking for your simpler case because it's forgoing that road altogether. Why? Because it's much harder forbidden by the spec. See section 14.20:

(By the way, my compiler does complain when the variable is declared final.)

Anagram of a palindrome

49 votes

I just had a technical job interview and in this process I had to solve this problem:

A string is a palindrome if it has exactly the same sequence of characters when read left-to-right as it has when read right-to-left. For example, the following strings are palindromes:

"kayak",
"Rats live on no evil star",
"Able was I ere I saw Elba.

A string A is an anagram of a string B if A can be obtained from B by rearranging the characters. For example, in each of the following pairs one string is an anagram of the other:

"mary" and "army",
"rocketboys" and "octobersky",

Write a function:

class Solution { public int isAnagramOfPalindrome(String S); }

that, given a non-empty string S consisting of N characters, returns 1 if S is an anagram of some palindrome and returns 0 otherwise.

Assume that:

N is an integer within the range [1..100,000];
string S consists only of English lower-case letters (a-z).

For example, given S = "dooernedeevrvn", the function should return 1, because "dooernedeevrvn" is an anagram of the palindrome "neveroddoreven". Given S = "aabcba", the function should return 0.

Complexity:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1) (not counting the storage required for input arguments).

I totally failed the interview. I was not ready for those kind of questions but I still want to know the solution. My idea was to create 2 utility functions isAnagram which checks if String A is a anagram of String B and createPalindrom which creates a palindrom from a given String :

public class Solution {
      public int isAnagramofPalindrom(String s){
          if(isAnagram(s, createPalindrom(s))) return 1;
          return 0;     
      }

      public boolean isAnagram(String A, String B){
             boolean yes = false ;
             for( int i = 0; i < A.lenth(); i++){
                yes = yes && exist(A.chartAt(i), B); //I know this is not optimized
             }
          return yes;    
      }

      public boolean exist(char c, String b){
        boolean found = true;
        int i = 0;
        while( found = (b.chartAt(i) != c)){
          i++;
        }
        return found;
      }

      public String createPalindrom(String s){
        //?????
      }


   } 

My problem was how to create the palindrom. Maybe, I get this wrong or maybe I had a bad approach of this problem. What is your point and how should I solve this problem?

Thx for your advice

It's quite simple actually. If string has an even number of chars, just verify that every char in the string is present an even number of times, if string is odd, you're allowed one (and only one) unique char odd number of times (for the middle of the palindrome), rest of the characters should be even.

Enhanced FOR loops in C++

44 votes

I am switching from Java to C++ and I was wondering whether C++ contains the enhanced for loops that I used in java, in example:

int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
  System.out.println("Count is: " + item);
}

Is this same "shortcut" possible in C++?

In C++11, if your compiler supports it, yes it is. It's called range-based for.

std::vector<int> v;

// fill vector

for (const int& i : v) { std::cout << i << "\n"; }

It works for C style arrays and any type that has functions begin() and end() that return iterators. Example:

class test {
    int* array;
    size_t size;
public:
    test(size_t n) : array(new int[n]), size(n)
    {
        for (int i = 0; i < n; i++) { array[i] = i; }
    }
    ~test() { delete [] array; }
    int* begin() { return array; }
    int* end() { return array + size; }
};

int main()
{
    test T(10);
    for (auto& i : T) {
        std::cout << i;   // prints 0123456789
    }
}

Why does the Double.valueof javadoc say it caches values, when it doesn't?

39 votes

In OpenJDK, for the method:

public static Double valueOf(double d)

The javadoc says:

Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

Here's the actual code:

public static Double valueOf(double d) {
    return new Double(d);
}

The cache is a lie! What's going on here?

The method exists for many types: Integer, Long, BigDecimal and others and the documentation is always the same: Under some circumstances (which aren't defined), the method can return the same result.

AFAIK, the caching is only implemented for integer types and it returns cached instances for values between -128 and 127 (most common values). For BigDecimal, the cache currently works for values from 0 to 10.

Later versions of Java might extend this behavior to other values/more types. So it's smart to use this code today because it might make your code faster tomorrow (and the code won't be slower today).

The Java compiler, for example, uses this API when generating code for autoboxing.

Java merge 2 collections in O(1)

33 votes

I need to be able to merge 2 large collections into 1. Which collection type can I use best? I don't need random access to the individual elements. Usually I'd go for a linkedlist, however I can't merge 2 linkedlist in Java with a runtime of O(1), which could be done in many other languages, since I'll have to copy each element to the new list.

Edit: Thank you for all your answers. Your answers were all very helpful, and I managed to get the job done. Next time I will use my own implementation of a linked list to begin with.

You can create a concatenated Iterable view in O(1) using one of Guava's Iterables.concat methods:

Iterable<T> combined = Iterables.concat(list1, list2);

This will allow you to iterate over all the elements of both lists as one object without copying any elements.

Why can attributes in Java be public?

33 votes

As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the only interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?

I think it's possible because every rule has its exception, every best practice can be overridden in certain cases.

For example, I often expose public static final data members as public (e.g., constants). I don't think it's harmful.

I'll point out that this situation is true in other languages besides Java: C++, C#, etc.

Languages need not always protect us from ourselves.

In Oli's example, what's the harm if I write it this way?

public class Point {
   public final int x;
   public final int y;

   public Point(int p, int q) {
      this.x = p;
      this.y = q;
   } 
}

It's immutable and thread safe. The data members might be public, but you can't hurt them.

Besides, it's a dirty little secret that "private" isn't really private in Java. You can always use reflection to get around it.

So relax. It's not so bad.

Integer.parseInt("1") ++ - why doesn't this work in java?

23 votes

I've got the following line of code:

suffix = suffix.isEmpty() ? "1" : Integer.toString(Integer.parseInt(suffix)+1);

in a block where suffix has already been declared as an empty String (""). The block is looking for duplicate file names and adding a number on to any duplicates so they don't have the same name any more.

The line of code above compiles fine, but if I change it to this,

suffix = suffix.isEmpty() ? "1" : Integer.toString(Integer.parseInt(suffix)++);

I get Invalid argument to operation ++/--. Since Integer.parseInt() returns and int, why can't I use the ++ operator?

The ++ operator should update the value of its argument, so the argument should be a variable (or, as it is most commonly called, an l-value, or an address value). In this case, the argument is Integer.parseInt(suffix), which is a "on the fly" value that cannot be updated.

Summing up, Integer.parseInt(suffix)++ is roughly equivalent to Integer.parseInt(suffix) = Integer.parseInt(suffix) + 1. But Integer.parseInt(suffix) is just an integer value, not associated to a fixed position in memory, so the code above is almost the same thing of, let us say, 32 = 32 + 1. Which does not make sense.

Java arrays - Why is the output '1' ?

22 votes

Why is the output in this example 1?

public static void main(String[] args){
 int[] a = { 1, 2, 3, 4 };   
 int[] b = { 2, 3, 1, 0 };   
 System.out.println( a [ (a = b)[3] ] );   
}

I thought it would be 2. i.e., the expression is evaluated as:

a[(a=b)[3]]
a[b[3]]    //because a is now pointing to b
a[0]   

Shouldn't a[0] be 2 because a is pointing to b?

Thanks in advance.

That weirded me out as well... however, check section 15.7.1 over here

Essentially, operands are evaluated from left to right. But also note this:

It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

Printing message on Console without using main() method

18 votes

I was asked this question in an interview.

How to print message on console without using main() method?

public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    } 
}

The System.exit(0) exits program before the jvm starts to look for main()

Ideone link

(Note: even if it compiles with JDK 7's javac it cannot be run with its java, because it expects a main(String[]) method.)

In Java, is the result of the addition of two chars an int or a char?

18 votes

When adding 'a' + 'b' it produces 195.

I asked on StackOverflow IRC channel they say the output datatype is char. I think it is int and some others do as well.

What is the correct answer?

The result of adding Java chars, shorts, or bytes is an int:

Java Language Specification on Binary Numeric Promotion:

  • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.6.2

But note what it says about compound assignment operators (like +=):

The result of the binary operation is converted to the type of the left-hand variable ... and the result of the conversion is stored into the variable.

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2

For example:

char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char, OK
x += y; // compound operation-assignment, also OK

Also note that the Java bytecode doesn't even have dedicated instructions for arithmetic with the smaller data types. For example, for adding, there are instructions iadd (for ints), ladd (for longs), fadd (for floats), dadd (for doubles), and that's it. It's left up to the JVM to optimize that if it's possible.

If you mean to concatenate characters as a String rather than interpreting them as a numeric type, there are lots of ways to do that, such as adding a char and a String, which results in a String. For example, 'a' + "" + 'b' or new String(new char[] { 'a', 'b' }) both give "ab".

Why does an empty Java program consume memory?

17 votes

I'm exploring memory usage in Java to understand why my program leaks memory. After stripping off code in my main while loop, I still get an increase of memory usage over time. Pondering the memory usage of an empty program:

class Nothing
{    public static void main(String[] args)
     {    while(true);    }
}

I still saw an increase of memory:

Image description here

So my question is: Why is there still a saw tooth pattern? Why when the GC runs does it not save all the memory (each time the gc runs (the valleys) the used memory increases by 10-20Kb (compared to the previous valley))?

EDIT:

java version "1.6.0_29"

Java(TM) SE Runtime Environment (build 1.6.0_29-b11)

Java HotSpot(TM) Client VM (build 20.4-b02, mixed mode, sharing)

OS: Windows 7 Enterprise-32 bit

Why is there still a saw tooth pattern?

If I'm not mistaken, part of the reason for this is that the monitor itself is forcing the application to create temporary objects that contain information about the state of garbage-collection and memory usage.

Why when the GC runs does it not save all the memory (each time the gc runs (the valleys) the used memory increases by 10-20Kb (compared to the previous valley))?

I believe the monitor does not instantly see the amount of used memory after garbage-collection, but rather, must poll frequently to see memory usage. Therefore, the perceived "valley" is necessarily somewhat higher than the true valley. I would guess that the perceived increase in memory usage at the valleys is just a random artifact of this discrepancy, and would be neutralized over time. (That is, I don't think that there's actually 10-20 KB of memory leak occurring in each cycle.)

Java Coding Style & Emacs cc-mode configuration

17 votes

I'm using GNU/Emacs HEAD with the included cc-mode (c-version 5.32.2) on a GNU/Linux Debian machine.

I'm trying to define a custom style to manage the Code Conventions for the Java Programming Language, Android's Code Style Guidelines for Contributors and some custom rules.

As a lisp beginner, it does not seem wise to start from scratch. As a consequence, I used google-c-style as a starting point and I managed to get the intended behavior for the most indenting rules, with an exception on nested condition (see the code snippet below).

From that post, I have defined (arglist-cont-nonempty . ++) in my custom style (full code: custom-java-style.el). Unfortunately, although most cases is indented as intended:

if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();

    someMethod(longExpression1, longExpression2, longExpression3,
            longExpression4, longExpression5);
}

Nested condition are wrongly indented:

if (!(deviceRegistred.getAddress().equalsIgnoreCase(deviceAdress)
                && deviceRegistred.getName().equalsIgnoreCase(deviceName))) {
    doSomethingAboutIt();
}

Ctrl-c Ctrl+s report Syntactic analysis: ((arglist-cont-nonempty 2447 2450) (arglist-cont-nonempty 2447 2452)) on the second line and I obviously have a 16 spaces (2 times ++) indentation instead of 8 (++).

I'd like to get the following indentation:

if (!(deviceRegistred.getAddress().equalsIgnoreCase(deviceAdress)
        && deviceRegistred.getName().equalsIgnoreCase(deviceName))) {
    doSomethingAboutIt();
}

I tried to define a (,(when (fboundp …))) condition like the one used for statement-cont but without success (my lack of lisp knowledge don't help either).

Now, the question: Is my approach right or wrong? How could/should I implement the intended behavior (i.e. detect when i'm in a nested condition to get the right indentation)?

(I don't want to use malabar-mode or JDEE, so please don't tell me to use them.)

Cheers,

Renaud

Update 2011/12/06 (reacting to the comments)

Gentlemen, we wouldn't begin a holy war here. Those who want to use Emacs, for their own reasons, can stick to Emacs, the others will do as they want…

Saying that, I work within a team in which I'm the only one to use Emacs, the others are fond of Eclipse. Since I'm in charge of the coding rules, I have worked with my colleagues to get the right save actions and help to configure the Eclipse's formatter. All I could say is that: the Eclipse save actions and formatter are not easy to configure at all… The main difference is that you have a nice GUI with nice checkboxes but it doesn't help much to reduce the complexity.

I stick with Emacs…

I'd say, that Emacs does the right thing. Consider this case:

if (!(deviceRegistred.getAddress().equalsIgnoreCase(deviceAdress)
                && deviceRegistred.getName().equalsIgnoreCase(deviceName))
        || otherCondition) {
    doSomethingAboutIt();
}

If nested condition was indented 8 chars that would be a confusing variant:

if (!(deviceRegistred.getAddress().equalsIgnoreCase(deviceAdress)
        && deviceRegistred.getName().equalsIgnoreCase(deviceName))
        || otherCondition) {
    doSomethingAboutIt();
}

what is a good metric for deciding if 2 Strings are "similar enough"

16 votes

I'm working on a very rough, first-draft algorithm to determine how similar 2 Strings are. I'm also using Levenshtein Distance to calculate the edit distance between the Strings.

What I'm doing currently is basically taking the total number of edits and dividing it by the size of the larger String. If that value is below some threshold, currently randomly set to 25%, then they are "similar enough".

However, this is totally arbitrary and I don't think is a very good way to calculate similarity. Is there some kind of math equation or probability/statistics approach to taking the Levenshtein Distance data and using it to say "yes, these strings are similar enough based on the number of edits made and the size of the strings"?

Also, the key thing here is that I'm using an arbitrary threshold and I would prefer not to do that. How can I compute this threshold instead of assign it so that I can safely say that 2 Strings are "similar enough"?

UPDATE

I'm comparing strings that represent a Java stack trace. The reason I want to do this is to group a bunch of given stack traces by similarity and use it as a filter to sort "stuff" :) This grouping is important for a higher level reason which I can't exactly share publicly.


So far, my algorithm (pseudo code) is roughly along the lines of:

/*
 * The input lists represent the Strings I want to test for similarity. The
 * Strings are split apart based on new lines / carriage returns because Java
 * stack traces are not a giant one-line String, rather a multi-line String.
 * So each element in the input lists is a "line" from its stack trace.
 */
calculate similarity (List<String> list1, List<String> list2) {

    length1 = 0;
    length2 = 0;
    levenshteinDistance = 0;

    iterator1 = list1.iterator();
    iterator2 = list2.iterator();

    while ( iterator1.hasNext() && iterator2.hasNext() ) {

        // skip blank/empty lines because they are not interesting
        str1 = iterator1.next();    length1 += str1.length();
        str2 = iterator2.next();    length2 += str2.length();

        levensteinDistance += getLevenshteinDistance(str1, str2);
    }

    // handle the rest of the lines from the iterator that has not terminated

    difference = levenshteinDistance / Math.max(length1, length2);

    return (difference < 0.25) ? true : false; // <- arbitrary threshold, yuck!
}

How about using cosine similarity? This is a general technique to assess similarity between two texts. It works as follows:

Take all the letters from both Strings an build a table like this:

Letter | String1 | String2

This can be a simple hash table or whatever.

In the letter column put each letter and in the string columns put their frequency inside that string (if a letter does not appear in a string the value is 0).

It is called cosine similarity because you interpret each of the two string columns as vectors, where each component is the number associated to a letter. Next, compute the cosine of the "angle" between the vectors as:

C = (V1 * V2) / (|V1| * |V2|)

The numerator is the dot product, that is the sum of the products of the corresponding components, and the denominator is the product of the sizes of the vectors.

How close C is to 1 gives you how similar the Strings are.

It may seem complicated but it's just a few lines of code once you understand the idea.

Let's see an example: consider the strings

s1 = aabccdd
s2 = ababcd

The table looks like:

Letter a b c d
s1     2 1 2 2
s2     2 2 1 1

And thus:

C = (V1 * V2) / (|V1| * |V2|) = 
(2 * 2 + 1 * 2 + 2 * 1 + 2 * 1) / (sqrt(13) * sqrt(10)) = 0.877

So they are "pretty" similar.

Is Java's System.arraycopy() efficient for small arrays?

16 votes

Is Java's System.arraycopy() efficient for small arrays, or does the fact that it's a native method make it likely to be substantially less efficient than a simple loop and a function call?

Do native methods incur additional performance overhead for crossing some kind of Java-system bridge?

Expanding a little on what Sid has written, it's very likely that System.arraycopy is just a JIT intrinsic; meaning that when code calls System.arraycopy, it will most probably be calling a JIT-specific implementation (once the JIT tags System.arraycopy as being "hot") that is not executed through the JNI interface, so it doesn't incur the normal overhead of native methods.

In general, executing native methods does have some overhead (going through the JNI interface, also some internal JVM operations cannot happen when native methods are being executed). But it's not because a method is marked as "native" that you're actually executing it using JNI. The JIT can do some crazy things.

Easiest way to check is, as has been suggested, writing a small benchmark, being careful with the normal caveats of Java microbenchmarks (warm up the code first, avoid code with no side-effects since the JIT just optimizes it as a no-op, etc).

P in constant declaration

Asked on Thu, 22 Dec 2011 by Rich java
15 votes

In java.lang.Double, there are the following constant declarations:

public static final double MAX_VALUE = 0x1.fffffffffffffP+1023;
public static final double MIN_NORMAL = 0x1.0p-1022;

What is the P for? Is the difference in case important?

I am aware of the L, D and F used for Longs, Doubles and Floats, but have never seen a P before.

The P (or p) indicates a hexadecimal floating-point literal, where the significand is specified in hex.

The p is used instead of the e. The d and f suffixes that you've seen are orthogonal to this: both 0x1.0p+2f and 0x1.0p+2d are valid literals (one is of type float and the other is of type double).

At first glance it might seem that the 0x prefix is sufficient to identify a hex floating-point literal, so why have the Java designers chosen to change the letter from e to p? This has to do with e being a valid hex digit, so keeping it would give rise to parsing ambiguity. Consider:

0x1e+2

Is that a hex double or the sum of two integers, 0x1e and 2? When we change e to p, the ambiguity is resolved:

0x1p+2

Java regex anomaly?

13 votes

Can anyone tell me why

System.out.println("test".replaceAll(".*", "a"));

Results in

aa

Note that the following has the same result:

System.out.println("test".replaceAll(".*$", "a"));

I have tested this on java 6 & 7 and both seem to behave the same way. Am I missing something or is this a bug in the java regex engine?

This is not an anomaly: .* can match anything.

You ask to replace all occurrences:

  • the first occurrence does match the whole string, the regex engine therefore starts from the end of input for the next match;
  • but .* also matches an empty string! It therefore matches an empty string at the end of the input, and replaces it with a.

The same applies for .*$, which is really no different at all from .*. If you want what I think you want, use .+ instead (no need for the $), but in general, avoid .* or .+ at all costs, and .*? or .+? like the plague

No key.store and key.alias properties found in build.properties

11 votes

I am using ant-release to do a 1-step build of my Android app.

My build.properties looks like this:

application.package=xxxxx
key.store=sonr
key.alias=sonr labs
key.store.password=xxxx
key.alias.password=xxxx

When I run ant-release everything is fine except for application signing. I get the error:

-release-prompt-for-password:

-release-nosign:
     [echo] No key.store and key.alias properties found in build.properties.
     [echo] Please sign /Users/syalam/Documents/git/joeborn-sonr/sonr/bin/SONR-release-unsigned.apk manually
     [echo] and run zipalign from the Android SDK tools.
[propertyfile] Updating property file: /Users/syalam/Documents/git/joeborn-sonr/sonr/bin/build.prop
[propertyfile] Updating property file: /Users/syalam/Documents/git/joeborn-sonr/sonr/bin/build.prop
[propertyfile] Updating property file: /Users/syalam/Documents/git/joeborn-sonr/sonr/bin/build.prop
[propertyfile] Updating property file: /Users/syalam/Documents/git/joeborn-sonr/sonr/bin/build.prop

How can I resolve this?

PS. I followed this tutorial for getting my build process down http://www.androidengineer.com/2010/06/using-ant-to-automate-building-android.html

I had this problem too recently, I think that that tutorial is out of date...

The key.alias etc directives need to be in a file named ant.properties. There's no file called build.properties any more.

Java Dates - What's the correct class to use?

10 votes

So the whole Java Date/Calendar/GregorianCalendar thing is obviously a joke. What's the right Date class to use?

Edit: Building an SDK for third parties on Android where the application needs to provide a date

More Edit: Things that make this so obviously a joke:

  • 99% of Date is deprecated
  • Date's Year is offset from 1900
  • Date's Month is zero-indexed while day is one-indexed
  • Dates are mutable
  • You're supposed to use a Calendar to create a date...
  • ... except you really have to use a GregorianCalendar
    • Do a significant percent of developers want to use a different calendar?
  • Calendar.getTime() returns a Date
  • There's no Date math (like how far apart are two dates in years)
    • Messing with milliseconds since epoch doesn't count
  • You can't chain parts together to get an expression (like the date one year ago today)
  • Probably more stuff

Joda-Time. Even on Android.

If you want to stick to JSE classes, it depends on what you're trying to do.

Edit: You keep changing your question. Date and Calendar.

Make the plus sign a string in java

9 votes

So I want the plus sign to be stored as a string and displayed to the screen later; so in this case I have

 String plusSign = "+";

but when I display the above on screen, I get a weird plus sign that has a circle around it. I am using the variable in an app that I'm making so using android may have something to do with the strange format. Is this how the plus sign is supposed to look or is there a way to make it look like a normal plus(a cross with no circle)?

Let me add some alternatives I've tried. The first thing I did was see if the unicode version of the plus sign would look any different but nothing appeared when I displayed it(the code was \u002B). I, also, looked at the ascii version but I wasn't sure how to convert it to a string.

Here is the code I use to display the string onScreen

 Addition = new Text(PositionX, PositionY, standardFont, "Intergers" + plusSign + "Integers");
 mScene.attachChild(Addition); 

I use andEngine, so here is the Text class http://code.google.com/p/andengine/source/browse/src/org/anddev/andengine/entity/text/Text.java

It looks like it is related to android: http://www.droidforums.net/forum/droid-x-faq/65474-what-those-icons.html

So it seems like if you use a font that does not support a certain character, it defaults to what ever android uses.

It looks to me like the most likely culprit is the font you are using. I would double check that the plus symbol doesn't have a circle in that font. There is another symbol, the "xor" symbol ("\u2295") that is a plus with a circle around it. I can't think of a reason why the plus symbol would be replaced with this symbol, but you might try displaying this character specifically to see if it looks like what you are seeing in the font you are using.

Spring app losing connection to MySql after 8 hours. How to properly configure?

8 votes

I've got a Spring app that I believe uses DBCP connection pooling to connect to a MySql database. I say believe because this isn't an area I'm very strong in and I'm not positive if everything is set up correctly. I have no problems running the application and everything is working fine. The problem occurs overnight. The app is not heavily used and overnight it apparently loses it's connection to MySql. I looked into it and found out MySql has an 8 hour window and then it disconnects or whatever. I'm fine with this, but when a user attempts to log on in the morning, they get an error something like:

Communications link failure. The last packet successfully received 60,000,000ms ago. The last packet successfully setn 15ms ago.

This is the problem. I need them to be able to reconnect in the morning without running into this issue. The only way I seem to be able to fix it is by bouncing the Tomcat server. From looking into it, it seems that DBCP pooling should be able to prevent this somehow but I can't find a reliable source of info on how to configure it. I'm hoping someone here can provide me with some insight. Here is my current configuration, all done in a Spring xml file:

app-data.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config />
<context:component-scan base-package="com.vz.sts.domain" />
<context:component-scan base-package="com.vz.sts.persistence" />
<context:component-scan base-package="com.vz.sts.service" />

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="database" value="MYSQL" />
            <property name="showSql" value="true" />
        </bean>
    </property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/app" />
    <property name="username" value="root" />
    <property name="password" value="admin" />
    <property name="initialSize" value="5" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="jdbcUserService" class="org.springframework.security.provisioning.JdbcUserDetailsManager">
    <property name="dataSource" ref="dataSource"/>
    <property name="authenticationManager" ref="authenticationManager"/>
</bean>

<bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
    <property name="userPropertyToUse" value="username" />
</bean>

<tx:annotation-driven />
</beans>

I'm not sure what specific properties I need to add in order to allow the app to reconnect to the database. I don't mind if it closes the connection after a number of hours but it should automatically reconnect and not throw errors like this. Nor am I even positive it's actually set up to use connection pooling. So any help would be very much appreciated, thank you.

UPDATE

I found this page and I think that all I need to do is add the ValidationQuery property. Can anyone verify if this will have the desire affect while leaving everything else at default? I believe that will then make use of the testOnBorrow aspect of DBCP. I don't entirely understand what the explanation says testOnBorrow does, but I think this will do what I want. Anyone confirm? Thanks.

The short answer is it should be enough. DBCP supports testing the connection on borrowing from the connection pool (the default), but also supports test on return and test while idle.

It's also worth understanding what may be going wrong here. It sounds like something between your Tomcat server and the database is dropping the idle connection after a timeout (such as a router or firewall). The problem with this is that Tomcat thinks it still has a valid connection, tries to do some work with the connection and fails, but keeps the connection alive and returns it to the pool. Now any further attempt to talk to the database will fail if it is given the same broken connection from the pool.

I think it was Michael Nygard's excellent 'Release It!' book that described this scenario in one of his from-the-trenches stories.

You will also want to look into how MySQL cleans up dead connections as when Tomcat loses the connection after 8 hours the DB will also be unaware of the failed connection.

One final point, if you are using Tomcat 7 switch to their new connection pool as it offers better performance than DBCP.