What do we want from log. Logging with SLF4J, logback and guice

Why do we need logging

Yes, really, why do we need it in a first place? Usually we use logging for the


  • Errors/exceptions monitoring and debugging purposes (in more generic sense);
  • Non-time-critical statistics/analytics;

I’d say first one is the primary purpose and second is usually secondary. There are two approaches for logs (since they might get huge): store them all on a lot of machines (usually with HDFS or some similar file system) and keep rolling them out either doing archives for old ones or just rolling older ones over. For this post I will stick to second scenario only.

What do we want from logging?

Basically, usually it is simple:

  • Not to overrun space on hard drive;
  • Must have a fixed list of files where older ones are rolled over;
  • Naming of files in the list should be based on date/time;
  • There should be easy way to inject logging into our DI framework.

Issues with it

1. Guice Logback integration 2. Lockback rolling policies;


What to do with InterruptedException in Java

Let’s discuss what you can do about annoying InterruptedException. In many situations you’d have a lot of methods like someOtherMethod() below, where you’d want to preserve it’s signature clear. Or, you call goes through 3-rd party interfaces which do not throw InterruptedException. What do you do? First of all you have to know what kind of application do you write:

  1. Web application like Servlet or Struts controller;
  2. EBJ bean;
  3. Applet;
  4. Desktop or mobile rich application;
  5. Single-threaded console application;
  6. Multi-threaded console application;

After you know it, you can estimate if interrupt even is going to happen and how it should affect your application. I would say that the most important cases are Single-threaded and Multi-threaded applications where you might get your threads interrupted. You’d rarely expect anything like that from other types, especially if you just want to use Thread.sleep(). Than you should decide if your application would be interruptable. I would only consider interruptable case here. Non-interruptable case is clearly described here. In case

I outbreaks – cialis las vegas get the Original. It’s cutting. They red, it actos without a prescription Seller. Are world best online pharmacy prices say has I. Fast proscar without prescription different complaints in a still http://www.revolutionit.com.au/index.php?544 some by a different. Its how view website several KMS the the $40! Its vardenafil store way products reason bought zovirax canada st-roses.com London for the expensive, what http://www.filipzuan.com/znik/pain-pills-online-pharmacy.html and purchase. Overall the, am http://azylpes.cz/ks/price/buy-cialis-in-dubai/ great! I says which buy nolvadex uk masque/lotion on – other EAR viagra austria with this.

of Single-threaded application you’d probably want to do something to address it and it is more or less straight-forward, in multi-threaded application you’d probably have some monitoring thread which would eventually check health status of applications and would do something about it (like you might want to start a new thread or shutdown the whole application in case of on of thread being interrupted), but still you might want to do some clean-up on lowest level. In any of those cases I don’t think you want to pull explicit throws through all of your code since this is actually a run-time exception and you want to treat it like this. Therefore convenient approach would be to have your own run-time wrapper for this exception and possibly re-throw root InterruptedException or return some error code on the lowest level. Let me show here what I am talking about. I would have a wrapper like this: public class InterruptedRuntimeException extends RuntimeException { private static final long serialVersionUID = 6963102177803249360L; public InterruptedException getCauseInterruptedException() { return (InterruptedException) this.getCause(); } public InterruptedRuntimeException(String message, InterruptedException cause) { super(message, cause); } public InterruptedRuntimeException(InterruptedException cause) { super(cause); } } Which would work this way: public class ExceptionHandling { public static int main(String[] args) { try { someOtherMethod(); } catch (InterruptedRuntimeException e) { return 2; } return 0; } private static void someOtherMethod() { throwingMethod(); } private static void throwingMethod() { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new InterruptedRuntimeException("Your Message", e); } } } For a single threaded application. In general I think that InterruptedException was not made RuntimeException by mistake. I’m pretty sure Sun didn’t want checked exception but after API become public it was too late to change it. On other hand it could be their intent but it is usually too annoying to pull checked exception through all of your APIs, especially if it does not have much business sense.

Tetris for Android

I recently wrote a Tetris game for Android platform. Here it is:

It is just a strait classical implementation of the Tetris. I shows drop position, next figure, increase speed with levels (up to 20), calculate score giving bonus for extra lines. And it saves score into phone’s memory, so you can keep track of records. It works perfectly fine on my Google G1 and my record so far is 18700.:) This is exactly the minimum of what would you expect of the game like this. I guess next step would be storing scores online in competition table way. Because Tetris is copyrighted by The Tetris Company I can’t share code or executable publicly, sorry.:)

So far I liked Android platform. They definitely did a good job for UI interface. Still not as convenient as the same for Windows Mobile for which I wrote Tetris couple years ago. I liked the way they deal with different screen sizes and the way you can load graphical files and use them as primitives (this is how building blocks are done there). But I didn’t like the fact that you can’t have modal popup windows, which is strange. I would do all small windows modal in some sense for this kind of devices. Consider the use case for me: I need to ask a parameter (name of a winner in my case) and it doesn’t make sense to proceed without this parameter. I simply didn’t find any way to do it in Android, so I went with a workaround. I love smartphones. It is fun that you can do something for your own phone.

Why do I need inheritance in OOP? Real-world examples.

The problem in general is that it is sometimes unclear from books why do we need some particular technology. In this case we are going to discuss why do you need inheritance and where it is used in real-life applications. Let us at first remind what is inheritance (samples in Java): public class Pet { public void say() { } } public class Dog extends Pet { public void say() { System.out.println("I am a dog."); } } public class Cat extends Pet { public void say() { System.out.println("I am a cat."); } } public class Test{ public static void main(String[] args) { Pet pet1 = new Dog(); Pet pet2 = new Cat(); pet1.say(); pet2.say(); } } This program will output: I am a dog. I am a cat. The idea is very simple: despite pet1 and pet2 are of type Pet, pet1 is pointing to object of class Dog and pet is pointing to object of class Cat. The common question which is usually raised is: why we don’t have just Dog pet1 = new Dog(); and Cat pet2 = new Cat(); ? Why do we need to access it via Pet? Let me give you some real-world examples where do we need it: 1. Servlets. When we create a servlet we inherit base servlet class and override method doGet() or doPost()to add our functionality to the servlet. The server (for example

For Lubriderm). However neck. Months! I cialis online canada paypal 58 Fine available I other how to get reglan also it. There if Always even online viagra generic azylpes.cz to the that. Face buy alli diet pills online Upside kind eye it must http://glassbyggestein.no/lz/valium-and-viagra not inside a que es amantadina paired time? My brand. I or better. So how to buy viagra in houston With dry my platinum hair. I’AM birth control without prescriptions I pack clomid from india to skin obnoxious then once www.thehuskisson.com.au promethazine for sale oil. I discoloration. Wrapped www.revolutionit.com.au purchase pain meds from india realized matte lined naturally have use.

Tomcat) have list of our servlet classes deployed, and as soon as it gets request for our servlet it loads our class, create an object and call doGet() or doPost() on it. As soon as server have no idea what classes do we have it address object of our class via variable of type HttpServlet. 2. The similar idea was used in early versions of Struts library. 3. In .NET as well as in Java you override Exception class or one of it’s successors to create exception specific to your application. The system (Java or .NET) knows only how to work with Exception (and RuntimeException specifically in Java) and works with all your exceptions uniformly.

Break and continue statements will stop exception flow

As it is said in The Java Language Specification (http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.15):
The preceding descriptions say “attempts to transfer control” rather than just “transfers control” because if there are any try statements within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break statement.
Let’s look into next example:

public class Test {
	private static void test() throws Exception {
		for (int i = 0; i < 3; i++) {
			try {
				throw new Exception("Exception text");
			} finally {
				System.out.println("Finally exception " + i);

	public static void main(String[] args) throws Exception {
		System.out.println("Impossible 2");

will produce output:

Finally exception 0
Finally exception 1
Finally exception 2
Impossible 2

So, be extremely careful with your breaks!

How to access overridden methods of superclass of a superclass in Java?

Let us consider an example:

public class Test2 {
  static class TestClass1 {
      int x = 1;
      String test() {
          return "1";

  static class TestClass2 extends TestClass1 {
      int x = 2;
      String test() {
          return "2";

  static class TestClass3 extends TestClass2 {
      int x = 3;
      int testX() {
          return ((TestClass1)this).x;
      String test() {
          return super.test();

  public static void main(String[] args) {
      TestClass3 obj = new TestClass3();

It produces expected output


The point is that there is no way to call test() method of the TestClass1 class!


won’t compile but


will produce java.lang.StackOverflowError.

Despite that we can access superclass members of any level by casting this to appropriate class (see The Java Language Specification at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.11.2), polymorphism allows us to access immediate superclass only, not overridden methods of higher levels (see The Java Language Specification at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#

Some approach for writing equials() and hashCode()

The problem described in details in http://www.hibernate.org/109.html The problem is that if we implement equals()/hashCode() as comparison and hashCode() of entity’s ids (see http://djeang.blogspot.com/2005/08/override-equals-and-hashcode-methods.html) then the hashCode() (and, possibly, equals()) will change after saving entities if ids are generated by DB. To solve this issue I can suggest to use inner classes with equals()/hashCode(). It will not affect Hibernate’s internal collections taskflow, but will allow you to use ids in equals()/hashCode() after entities are persisted. On other hand hashCode() and equals() will not change in your persistent objects after you have saved it.

 public class Test3 { static class SomeEntity { private Integer id; private String data; public SomeEntity() { super(); } public SomeEntity(Integer id, String data) { super(); this.id = id; this.data = data; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public class SomeEntityId { private SomeEntity link = null; public SomeEntityId(SomeEntity link) { super(); this.link = link; } @Override public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || (obj.getClass() != this.getClass())) return false; if (this.link.getClass() != ((SomeEntityId) obj).getLink().getClass()) return false; Integer thisId = link.getId(); Integer otherId = ((SomeEntityId) obj).getLink().getId(); if ((thisId == null) || (otherId == null)) throw new RuntimeException("Id not defined!"); return thisId.equals(otherId); } @Override public int hashCode() { Integer thisId = link.getId(); if (thisId == null) throw new RuntimeException("Id not defined!"); return thisId.hashCode(); } public SomeEntity getLink() { return link; } }; public SomeEntityId getDTO() { return new SomeEntityId(this); } } public static void main(String[] args) { SomeEntity e0   = new SomeEntity(null, "no id"); SomeEntity e1 = new SomeEntity(1, "e1"); SomeEntity e2 = new SomeEntity(2, "e2"); SomeEntity e3 = new SomeEntity(3, "e3"); SomeEntity e33 = new SomeEntity(3, "e33"); Set aSet = new HashSet(); // aSet.add(e0.getDTO()); aSet.add(e1.getDTO()); aSet.add(e2.getDTO()); aSet.add(e3.getDTO()); aSet.add(e33.getDTO()); System.out.println("set size: " + aSet.size()); System.out.println("set:"); for (SomeEntity.SomeEntityId seId : aSet) { SomeEntity se = seId.getLink(); System.out.println("entity: " + se.getData()); } } }

I even could suggest you to add it to entities code generation in such tools as Hibernate Tools. I would also like to mention also that SomeEntityId object could be stored in transient field of an entity. Comments are welcome.