SlideShare ist ein Scribd-Unternehmen logo
1 von 65
Downloaden Sie, um offline zu lesen
Typical Java Problems
                                           in the Wild

                                                                      Eberhard Wolff
                                                                       SpringSource




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
SpringSource Solution

                           Unifying the Application Lifecycle:
                            from Developer to Datacenter

 High Productivity Tools                                                                                             Lean Powerful Runtimes
      Spring Enterprise                                                                                              SpringSource tc Server
      Groovy and Grails                                                Build	
   Run	
                               SpringSource dm Server
SpringSource Tool Suite                                                                                              SpringSource http Server


                                                                               Manage	
  

                                           Application Infrastructure Management
                                                  SpringSource Hyperic HQ
                                                              SpringSource Hyperic IQ
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                            2
About me

•  Regional Director German speaking region and
   Principal Consultant
•  Author of several articles and books
•  First German Spring book
•  Speaker at national and international conferences

•  Eberhard.Wolff@springsource.com




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   3
Why this talk?

•  I do a lot of reviews
•  There are some common problems you see over and
   over again

•  So: Here are 10
         –  …not necessarily the most common
         –  ...but certainly with severe effects




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   4
#1
public class Service {	
	
      private CustomerDao customerDao;	
      private PlatformTransactionManager transactionManager;	
	
      public void performSomeService() {	
         TransactionStatus transactionStatus = transactionManager	
          .getTransaction(new DefaultTransactionDefinition());	
         customerDao.doSomething();	
         customerDao.doSomethingElse();	
         transactionManager.commit(transactionStatus);	
      }	
	
}	
  




 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   5
#1 Weak Transaction
Handling
public class Service {	
	
      private CustomerDao customerDao;	
      private PlatformTransactionManager transactionManager;	
	
      public void performSomeService() {	
         TransactionStatus transactionStatus = transactionManager	
          .getTransaction(new DefaultTransactionDefinition());	
         customerDao.doSomething();	
         customerDao.doSomethingElse();	
         transactionManager.commit(transactionStatus);	
      }	
	
    •  What happens to the transaction if the DAO
}	
  
       throws an exception?
    •  We might never learn...
    •  ...or learn the hard way
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   6
Weak Transaction Handling:
Impact
•  Hard to detect, has effects only if exception is
   thrown
•  …but then it can lead to wired behavior and data loss
   etc.
•  That is why you are using transactions in the first
   place




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   7
Solution

•  Declarative transactions
public class Service {	
	
      private CustomerDao customerDao;	
	
      @Transactional	
      public void performSomeService() {	
         customerDao.doSomething();	
         customerDao.doSomethingElse();	
      }	
	
}	
  
   •  Exception is caught, transaction is rolled back (if
      it is a RuntimeException)
   •  Exception handling can be customized

Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   8
A different solution…
 public void performSomeService() {	
   TransactionTemplate template = new TransactionTemplate(	
    transactionManager);	
   template.execute(new TransactionCallback() {	
 	
     public Object doInTransaction(TransactionStatus status) {	
        customerDao.doSomething();	
        customerDao.doSomethingElse();	
        return null;	
     }	
 	
    });	
 }
•  Allows for multiple transactions in one method
•  More code – more control
•  Rather seldom really needed
 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   9
#2 Exception Design

•  Get all the details from a system exception!
•  Each layer must only use its own exceptions!
•  Exceptions have to be checked – then they must be
   handled and the code is more secure.

•  Sounds reasonably, doesn't it?




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   10
public class OrderDao {	
   public void createOrder(Order order) throws SQLException {	
      // some ugly JDBC code	
      // that I am not going to show	
   }	
}	
                                                                    public class SomeService {	
                                                                       public void performService()	
Get all the details!                                                      throws ServiceException {	
Use checked                                                               try {	
exceptions!                                                                  orderDao.createOrder(new Order());	
                                                                          } catch (SQLException e) {	
                                                                             throw new ServiceException(e);	
Service must only                                                         }	
throw                                                                  }	
ServiceException!                                                   }	       public class SomeController {	
                                                                                              public void handleWebRequest() {	
                                                                                                 try {	
 What am I supposed to do                                                                           someService.performService();	
 now?                                                                                            } catch (Exception e) {	
 No real logging                                                                                    e.printStackTrace();	
                                                                                                 }	
 And I don t care about the                                                                   }	
 specific ServiceException                                                              }
 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.            11
Impact

•  Lots of useless exception handling code
•  Lots of exception types without specific handling of
   that type
•  In the end all you get is a log entry and lots of code

•  And what should the developer do?
         –  All he knows "Something went wrong"
         –  Does not really care and can not really handle it




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   12
Why is this commonplace?

•  Very few languages have checked exceptions (Java -
   CLU and Modula-3 had similar concepts)
•  Checked exception force developers to handle an
   exception – very rigid
•  How common is it that you can really handle an
   exception?
•  Checked exceptions are perceived to be more secure
•  Checked exceptions are overused – also in Java APIs

•  In many cases there are even no exception concepts
   in projects


Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   13
Solution

•  Use more unchecked exceptions aka
   RuntimeExceptions
•  Remember: A lot of languages offer only unchecked
   exceptions

•  Avoid wrap-and-rethrow – it does not add value
•  Don't write too many exception classes – they often
   don't add value
•  A specific exception classes is only useful if that
   exception should be handled differently



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   14
Solution

public class OrderDao {	
   public void createOrder(Order order) {	
      jdbcTemplate.update("INSERT INTO ORDER ...");	
   }	
}	


                                                            public class SomeService {	
Where is the                                                   public void performService() {	
exception                                                      }	
                                                                  orderDao.createOrder(new Order());	

handling?                                                   }	

                                                                                             public class SomeController {	
                                                                                               public void handleWebRequest() {	
                                                                                                  someService.performService();	
                                                                                               }	
                                                                                             }

 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.         15
AOP in one Slide

@Aspect	
public class AnAspect {	
	
   // do something before the method hello	
   // is executed	
   @Before("execution(void hello())")	
   public void doSomething() {	
   }	
	
  // in a specific class	
   // that ends in Service in any package or subpackage	
   @Before("execution(* com.springsource.MyService.hello())")	
   public void doSomethingElse2() {	
   }	
	
   // do something before any method in a class	
   // that ends in Service in any package or subpackage	
   @Before("execution(* *..*Service.*(..))")	
   public void doSomethingElse2() {	
   }	                                                        16
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Aspect for Logging

@Aspect	
public class ExceptionLogging {	
	
   @AfterThrowing(value="execution(* *..Service*.*(..))",	
    throwing="ex")	
   public void logRuntimeException(RuntimeException ex) {	
      System.out.println(ex);	
   }	
	
}	


•  Logs every exception – 100% guaranteed!




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   17
Handle only cases you really
want to handle

     public class SomeService {	
        public void performService() {	
           try {	
              orderDao.createOrder(new Order());	
           } catch (OptimisticLockingFailureException ex) {	
              orderDao.createOrder(new Order());	
           }	
        }	
     }	

•  Everything else will be handled somewhere else
•  Can handle specific error conditions using catch with
   specific types


Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   18
Generic Exception Handling

public class MyHandlerExceptionResolver	
  implements HandlerExceptionResolver {	
	
   public ModelAndView resolveException(	
    HttpServletRequest request,	
    HttpServletResponse response, Object handler, Exception ex) {	
      return new ModelAndView("exceptionView", "exception", ex);	
   }	
	
}

•  In the web layer
•  Handle all the (Runtime)Exceptions not handled
   elsewhere



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   19
#3 Exception Handling

    public void someMethod() {	
      try {	
    	
      } catch (Exception ex) {	                                                                    Exception is not logged
         ex.printStackTrace();	                                                                    just written to stdout
      }	
                                                                                                   operations might not notice
      try {	
    	
      } catch (Exception ex) {	
         // should never happen	                                                                   Exception is swallowed
      }	
    }




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.               20
Impact

•  Related to #2: If you have excessive checked
   exceptions this will occur more often
•  …as developers are forced to handle exceptions they
   can't really handle
•  In the end you just get a message on the console
   and the application continues.
•  All kinds of wired behavior
•  i.e. exception is swallowed
•  You will have a hard time finding problems in the
   code
•  Potentially a huge problem – so worth its own
   explanation
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   21
Solution

•  At least log exceptions
•  Rethink: Is it really OK to continue in this situation?
   If not - don't handle the exception. Might be better
   to let a generic handler handle it.
•  Introduce generic handling at least for
   RuntimeException (AOP, web front end, etc)
•  Enforce the logging using Findbugs, PMD etc.
•  And: Improve the
                               public void someMethod() {	
   exception design (#2)         try {	
                                                                                                   	
                                                                                                         } catch (Exception ex) {	
                                                                                                            log.error(ex);	
                                                                                                         }	
                                                                                                   }
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                   22
#4

•  Table of
   packages and
   the relations
   between them
•  Everything in
   red is part of a
   cycle
•  This is actual
   code from an
   Open Source
   project



 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   23
Dependency Graph

•  Overview




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   24
Dependency
Graph
•  Just a small part
•  Red line show
   circular references




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   25
What is Architecture?

•  Architecture is the decomposition of systems in parts

•  No large or complex parts
•  No cyclic dependencies




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   26
Normal Dependencies

•  B dependes on A, i.e. it uses
   classe, methods etc.
•  Changes in A impact B                                                                                             Component A
•  Changes in B do not impact A




                                                                                                                     Component B




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                 27
Cyclic Dependency

•  B depends on A and A on B
•  Changes in A impact B
•  Changes in B impact A                                                                                             Component A
•  A and B can only be changed
   as one unit
•  …even though they should be
   two separate units
                                                                                                                     Component B




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                 28
Bigger cyclic dependencies



                          Component A


                                                                                                                     Component B


                          Component C




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                 29
#4: Architecture Mess

•  This is effectively
   just one big
   unstructured pile
   of mud
•  Maintenance will
   be hard
•  Concurrent
   development will
   be hard
•  Changes will have
   unforeseeable
   results

 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   30
Solution

•  Very hard if you have this state
•  Therefore: Manage dependencies from the start
•  Otherwise you are looking at a major restructuring of
   your application
•  …which might not be worth it
•  Effort for restructuring pays off by lower effort for
   maintenance
•  …might take a long time to amortize

•  Throwing away + redevelopment means that you
   have to migrate to a new solution -> complex and
   risky
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   31
#5
public class ServiceAdaptor {	
   public void performService(OrderDTO orderDTO) {	
      logger.trace("Entering performService");	
      try {	
         if (orderDTO == null) {	
            throw new NullPointerException("order must not be null");	
         }	
         if (youAreNotAllowedToDoThis()) {	
            throw new IllegalStateException(	
             "You are not allowed to call this!");	
         }	
         OrderEntity order = new OrderEntity();	
         order.setCustomer(orderDTO.getCustomer()); // ...	
         service.performService(order);	
         commandLog.add(new Command("performService",	
          service,order));	
      } finally {	
         logger.trace("Leaving performanceService");	
      }	
   }	
}	                                                                 32
 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
#5: Adaptor Layer

•  Adds to a service:
         –  Security
         –  Tracing
         –  Check for null arguments
         –  Log for all commands (auditing, replay…)
         –  Conversion from DTO to internal representation
•  Lots of boilerplate for each service
•  Changes to tracing etc. hard: lots of methods to
   change




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   33
Solution: Tracing with AOP

•  …or use Spring's predefined TraceInterceptor,
   DebugInterceptor etc.
    @Aspect	
    public class TraceAspect {	
    	
      @Before("execution(* *..*Service.*(..))")	
      public void traceBegin(JoinPoint joinPoint) {	
        System.out.println("entering method "	
          + joinPoint.getSignature().getName());	
       }	
    	
       @After("execution(* *..*Service.*(..))")	
       public void traceEnd(JoinPoint joinPoint) {	
          System.out.println("leaving method "	
           + joinPoint.getSignature().getName());	
       }	
    }

Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   34
Solution:
Null Checks with AOP
@Aspect	
public class NullChecker {	
	
  @Before("execution(* *..*Service.*(..))")	
  public void checkForNull(JoinPoint joinPoint) {	
     for (Object arg : joinPoint.getArgs()) {	
        if (arg==null) {	
          throw new NullPointerException("Argument was null!");	
        } 	
     }	
  }	
	
}


•  Security can be handled with Spring Security or AOP
•  Command log also possible

Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   35
What is left…
public class ServiceAdaptor {	
	
  public void performService(OrderDTO orderDTO) {     	
     OrderEntity order = new OrderEntity();	
     order.setCustomer(orderDTO.getCustomer()); // ...	
     service.performService(order);	
  }	
	
}
  •  You should probably switch to Dozer
    •  http://dozer.sf.net
    •  Can externalize mapping rules
    •  i.e. the layer can be more or less eliminated
    •  Everything (mapping, security, tracing…) is now
       implemented in one place (DRY)
    •  Often services just delegate to DAOs –
        same issue
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   36
#6: No DAO
public class SomeService {	
	
  @PersistenceContext	
  private EntityManager entityManager;	
	
  public void performSomeService() {	
     List<Order> list = entityManager.	
      createQuery("select o from Order").getResultList();	
     for (Order o : list) {	
        // ...	
        if (o.shouldBeProcessed()) {	
           o.process();	
        }	
     }	
  }	
}
•  We don't need to abstract away from JPA – it's a
   standard, right?
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   37
#6: Even worse
public class SomeServiceJdbc {	
	
private OrderDao someDoa;	
	
  public void performSomeService() throws SQLException {	
     ResultSet rs = someDoa.getOrders();	
     while (rs.next()) {	
        //...	
     }	
  }	
	
}

•  Service depends on JDBC
•  …and throws SQLException
•  Persistence visible in the service layer and beyond

Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   38
Impact

•  Code is impossible to test without a database
•  …so no real unit tests possible

•  Service depends on persistence – cannot be ported

•  How do you add data dependent security?

•  No structure




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   39
Solution

•  Use a DAO (Data Access Object)
         –  Separate persistence layer
         –  Technical motivation


•  …or a Repository
         –  Interface to existing objects
         –  Non technical motivation: Domain Driven Design, Eric
            Evans


•  Basically the same thing



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   40
Solution

public class SomeServiceDAO {	
	
  public void performSomeService() {	
     List<Order> list = orderDao.getAllOrders();	
     for (Order o : list) {	
       // ...	
       if (o.shouldBeProcessed()) {	
          o.process();	
       }	
      }	
  }	
}

•  Clear separation
•  Tests easy


Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   41
Solution: Test

public class ServiceTest {	
  @Test	
  public void testService() {	
     SomeService someService = new SomeService();	
     someService.setOrderDao(new OrderDao() {	
	
       public List<Order> getAllOrders() {	
          List<Order> result = new ArrayList<Order>();	
          return result;	
       }	
     });	
     someService.performSomeService();	
     Assert.assertEquals(expected, result);	
  }	
	
}



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   42
#7

•  No Tests




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   43
#7 Or bad tests
•  No asserts       public class MyUnitTest {	
                      private Service service = new Service();	
•  System.out:      	
   results are        @Test	
   checked            public void testService() {	
   manually             Order order = new Order();	
                        service.performService(order);	
•  Tests commented      System.out.print(order.isProcessed());	
   out: They did not }	
   run any more     	
   and were not       // @Test	
                      // public void testOrderCreated() {	
   fixed              // Order order = new Order();	
•  No mocks, so no // service.createOrder(order);	
   real Unit Tests    // }	
                    	
•  No negative      }
   cases

 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   44
Impact

•  Code is not properly tested
•  Probably low quality – testable code is usually better
   designed
•  Code is hard to change: How can you know the
   change broke nothing?
•  Design might be bad: Testable usually mean better
   quality




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   45
Solution

 •  Write proper Unit Tests!
public class MyProperUnitTest {	
   private Service service = new Service();	
	
   @Test	
   public void testService() {	
      Order order = new Order();	
      service.performService(order);	
      Assert.assertTrue(order.isProcessed());	
   }	
	
   @Test(expected=IllegalArgumentException.class)	
   public void testServiceException() {	
      Order order = new BuggyOrder();	
      service.performService(order);	
   }	
	
}	
 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   46
Wow, that was easy!




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
The real problem…

•  The idea of Unit tests is over 10 years old
•  Not too many programmer actually do real unit tests
•  Even though it should greatly increased trust and
   confidence in your code
•  …and make you much more relaxed and therefore
   improve quality of life…

•  Original paper: Gamma, Beck: "Test Infected –
   Programmers Love Writing Tests"
•  Yeah, right.



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   48
BTW




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   49
Solution

•  Educate
         –  Show                   how to write Unit Test
         –  Show                   how to build Mocks
         –  Show                   aggressive Testing
         –  Show                   Test First / Test Driven Development
•  Coach / Review
•  Integrate in automatic build
•  Later on: Add integration testing, functional testing,
   FIT, Fitnesse etc.
•  …or even start with these



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   50
What does not really work

•  Measuring code coverage
         –  Can be sabotaged
         public class MyProperUnitTest {	
           private Service service = new Service();	
         	
           @Test	
           public void testService() {	
              Order order = new Order();	
              service.performService(order);	
           }	
         }

•  Let developers just write tests without education
         –  How should they know how to test properly?
         –  Test driven development is not obvious

Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   51
#8: Creating SQL statements


    public class OrderDAO {	
    	
      private SimpleJdbcTemplate simpleJdbcTemplate;	
    	
      public List<Order> findOrderByCustomer(String customer) {	
         return simpleJdbcTemplate.query(	
          "SELECT * FROM T_ORDER WHERE name='"	
          + customer + "'", new OrderRowMapper());	
      }	
    	
    }




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   52
Impact

•  Performance is bad:
         –  Statement is parsed every time
         –  Execution plan is re created etc.




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   53
Impact

•  Even worse: SQL injection
•  Pass in a' or 't'='t'
•  Better yet: a'; DROP TABLE T_ORDER; SELECT *
   FROM ANOTHER_TABLE

public class OrderDAO {	
	
  private SimpleJdbcTemplate simpleJdbcTemplate;	
	
  public List<Order> findOrderByCustomer(String customer) {	
     return simpleJdbcTemplate.query(	
      "SELECT * FROM T_ORDER WHERE name='"	
      + customer + "'", new OrderRowMapper());	
  }	
	
}
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   54
Solution

    public class OrderDAO {	
    	
      private SimpleJdbcTemplate simpleJdbcTemplate;	
    	
      public List<Order> findOrderByCustomer(String customer) {	
         return simpleJdbcTemplate.query(	
          "SELECT * FROM T_ORDER WHERE name=?",	
          new OrderRowMapper(), customer);	
      }	
    	
    }
•  … and white list the allowed characters in name




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   55
#9

•     "What about Performance?"
•     "Well, we figured the response time should be 2s."
•     "How many request do you expect?"
•     "…"
•     "What kind of requests do you expect?"
•     "..."




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   56
#9

•     The software is happily in the final functional test
•     Then the performance test start
•     Performance is too bad to be accepted
•     You can hardly do anything:
         –  Changes might introduce functional errors
         –  Too late for bigger changes anyway
•  The results might be wrong if the performance test is
   on different hardware than production.
•  You can't test on production hardware: Too
   expensive.



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   57
Impact

•  You have to get bigger hardware
         –  Prerequisite: The software is scalable


•  Worse: You can't go into production




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   58
Solution

•  Get information about the number of requests,
   expected types of requests, acceptable response
   times
•  Pro active performance management:
         –  Estimate the performance before implementation
         –  …by estimating the slow operations (access to other
            systems, to the database etc)
         –  Measure performance of these operation in production
•  Practice performance measurements and
   optimizations before performance test




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   59
#10
            public class SomeService {	
            	
            private Map cache = new HashMap();	
            private Customer customer;	
            	
              public Order performService(int i) { 	
                 if (cache.containsKey(i)) {	
                    return cache.get(i);	
                 }	
                 Order result;	
                 customer = null;	
                 cache.put(i, result);	
                 return result;	
              }	
            	
            }



Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   60
#10 Multiple threads, memory
leaks
public class SomeService {	
	                                                                                                                    The cache is filled –
  private Map<Integer,Order> cache =	                                                                                is it ever emptied?
   new HashMap<Integer, Order>();	
  private Customer customer;	                                                                                        HashMap is not
	
  public Order performService(int i) { 	
                                                                                                                     threadsafe
     if (cache.containsKey(i)) {	
        return (Ordercache.get(i);	
                                                                                                                     customer is an
     }	                                                                                                              instance variable –
     Order result;	                                                                                                  multi threading will
     customer = null;	
     ...	
                                                                                                                     be a problem
     cache.put(i, result);	
     return result;	
  }	
	
}

Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                           61
Impact

•  System working in small tests
•  In particular Unit tests work

•     But production fails
•     …probably hard to analyze / fix
•     Almost only by code reviews
•     …or extensive debugging using thread dumps




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   62
Solution
                            public class SomeServiceSolution {	
•     Use WeakHashMap to    	
      avoid memory leaks private Map<Integer, Order> cache =	
                               new WeakHashMap<Integer, Order>();	
•     Synchronize           	
•     Prefer local variables public Order performService(int i) {	
                                 synchronized (cache) {	
•     Usually services can          if (cache.containsKey(i)) {
      store most things in             return cache.get(i);	
                                    }	
      local variables            }	
                                 Order result = null;	
                                 Customer customer = null;	
                                 synchronized (cache) {	
                                    cache.put(i, result);	
                                 }	
                                 return result;	
                              }	
                            }
Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   63
Solution

•  Also consider ConcurrentHashMap
•  or http://sourceforge.net/projects/high-scale-lib




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   64
Sum Up

  •  #1 Weak Transaction                                                                             •  #8 Creating SQL
     Handling                                                                                           queries using String
  •  #2 Exception Design                                                                                concatenation
  •  #3 Exception Handling                                                                           •  #9 No performance
  •  #4 Architecture Mess                                                                               management
                                                                                                     •  #10 Multiple threads /
  •  #5 Adaptor Layer
                                                                                                        memory leaks
  •  #6 No DAO
  •  #7 No or bad tests




Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.               65

Weitere ähnliche Inhalte

Was ist angesagt?

Adopting Java for the Serverless world at Serverless Meetup Singapore
Adopting Java for the Serverless world at Serverless Meetup SingaporeAdopting Java for the Serverless world at Serverless Meetup Singapore
Adopting Java for the Serverless world at Serverless Meetup SingaporeVadym Kazulkin
 
FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...
FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...
FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...Vadym Kazulkin
 
Writing less code with Serverless on AWS at FrOSCon 2021
Writing less code with Serverless on AWS at FrOSCon 2021Writing less code with Serverless on AWS at FrOSCon 2021
Writing less code with Serverless on AWS at FrOSCon 2021Vadym Kazulkin
 
#JavaOne What's in an object?
#JavaOne What's in an object?#JavaOne What's in an object?
#JavaOne What's in an object?Charlie Gracie
 
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and MesosIguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and MesosColleen Lee
 
Serverless Java Challenges & Triumphs
Serverless Java Challenges & TriumphsServerless Java Challenges & Triumphs
Serverless Java Challenges & TriumphsDavid Delabassee
 
JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)jaxLondonConference
 
Immutable Infrastructure: the new App Deployment
Immutable Infrastructure: the new App DeploymentImmutable Infrastructure: the new App Deployment
Immutable Infrastructure: the new App DeploymentAxel Fontaine
 
Java in the Cloud : PaaS Platforms in Comparison
Java in the Cloud : PaaS Platforms in Comparison Java in the Cloud : PaaS Platforms in Comparison
Java in the Cloud : PaaS Platforms in Comparison Eberhard Wolff
 
ReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... YawnReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... Yawnozten
 
JavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor AppJavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor AppJoe Kutner
 
Whizlabs webinar - Deploying Portfolio Site with AWS Serverless
Whizlabs webinar - Deploying Portfolio Site with AWS ServerlessWhizlabs webinar - Deploying Portfolio Site with AWS Serverless
Whizlabs webinar - Deploying Portfolio Site with AWS ServerlessDhaval Nagar
 
Writing less code with Serverless on AWS at AWS User Group Nairobi
Writing less code with Serverless on AWS at AWS User Group NairobiWriting less code with Serverless on AWS at AWS User Group Nairobi
Writing less code with Serverless on AWS at AWS User Group NairobiVadym Kazulkin
 
Managing the Continuous Delivery of Code to AWS Lambda
Managing the Continuous Delivery of Code to AWS LambdaManaging the Continuous Delivery of Code to AWS Lambda
Managing the Continuous Delivery of Code to AWS LambdaAmazon Web Services
 
Java Serverless in Action - Voxxed Banff
Java Serverless in Action - Voxxed BanffJava Serverless in Action - Voxxed Banff
Java Serverless in Action - Voxxed BanffDavid Delabassee
 
DevOps Toolbox: Infrastructure as code
DevOps Toolbox: Infrastructure as codeDevOps Toolbox: Infrastructure as code
DevOps Toolbox: Infrastructure as codesriram_rajan
 

Was ist angesagt? (20)

Why akka
Why akkaWhy akka
Why akka
 
Adopting Java for the Serverless world at Serverless Meetup Singapore
Adopting Java for the Serverless world at Serverless Meetup SingaporeAdopting Java for the Serverless world at Serverless Meetup Singapore
Adopting Java for the Serverless world at Serverless Meetup Singapore
 
FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...
FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...
FaaS or not to FaaS. Visible and invisible benefits of the Serverless paradig...
 
Writing less code with Serverless on AWS at FrOSCon 2021
Writing less code with Serverless on AWS at FrOSCon 2021Writing less code with Serverless on AWS at FrOSCon 2021
Writing less code with Serverless on AWS at FrOSCon 2021
 
#JavaOne What's in an object?
#JavaOne What's in an object?#JavaOne What's in an object?
#JavaOne What's in an object?
 
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and MesosIguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
 
Serverless Java Challenges & Triumphs
Serverless Java Challenges & TriumphsServerless Java Challenges & Triumphs
Serverless Java Challenges & Triumphs
 
JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)
 
Immutable Infrastructure: the new App Deployment
Immutable Infrastructure: the new App DeploymentImmutable Infrastructure: the new App Deployment
Immutable Infrastructure: the new App Deployment
 
Java in the Cloud : PaaS Platforms in Comparison
Java in the Cloud : PaaS Platforms in Comparison Java in the Cloud : PaaS Platforms in Comparison
Java in the Cloud : PaaS Platforms in Comparison
 
ReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... YawnReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... Yawn
 
JavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor AppJavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor App
 
Whizlabs webinar - Deploying Portfolio Site with AWS Serverless
Whizlabs webinar - Deploying Portfolio Site with AWS ServerlessWhizlabs webinar - Deploying Portfolio Site with AWS Serverless
Whizlabs webinar - Deploying Portfolio Site with AWS Serverless
 
Writing less code with Serverless on AWS at AWS User Group Nairobi
Writing less code with Serverless on AWS at AWS User Group NairobiWriting less code with Serverless on AWS at AWS User Group Nairobi
Writing less code with Serverless on AWS at AWS User Group Nairobi
 
Beyond AEM Curl Commands
Beyond AEM Curl CommandsBeyond AEM Curl Commands
Beyond AEM Curl Commands
 
Managing the Continuous Delivery of Code to AWS Lambda
Managing the Continuous Delivery of Code to AWS LambdaManaging the Continuous Delivery of Code to AWS Lambda
Managing the Continuous Delivery of Code to AWS Lambda
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
AWS Simple Work Flow
AWS Simple Work FlowAWS Simple Work Flow
AWS Simple Work Flow
 
Java Serverless in Action - Voxxed Banff
Java Serverless in Action - Voxxed BanffJava Serverless in Action - Voxxed Banff
Java Serverless in Action - Voxxed Banff
 
DevOps Toolbox: Infrastructure as code
DevOps Toolbox: Infrastructure as codeDevOps Toolbox: Infrastructure as code
DevOps Toolbox: Infrastructure as code
 

Ähnlich wie 10 Typical Java Problems in the Wild

10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java ApplicationsEberhard Wolff
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java ProblemsEberhard Wolff
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIelliando dias
 
JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)Hendrik Ebbers
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)William Farrell
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocationelliando dias
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aopDror Helper
 
How to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyHow to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyIordanis (Jordan) Giannakakis
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarYonni Mendes
 
081107 Sammy Eclipse Summit2
081107   Sammy   Eclipse Summit2081107   Sammy   Eclipse Summit2
081107 Sammy Eclipse Summit2mkempka
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Dropwizard and Friends
Dropwizard and FriendsDropwizard and Friends
Dropwizard and FriendsYun Zhi Lin
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 

Ähnlich wie 10 Typical Java Problems in the Wild (20)

10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMI
 
JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)
 
Extending and scripting PDT
Extending and scripting PDTExtending and scripting PDT
Extending and scripting PDT
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
How to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyHow to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happy
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinar
 
081107 Sammy Eclipse Summit2
081107   Sammy   Eclipse Summit2081107   Sammy   Eclipse Summit2
081107 Sammy Eclipse Summit2
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Dropwizard and Friends
Dropwizard and FriendsDropwizard and Friends
Dropwizard and Friends
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 

Mehr von Eberhard Wolff

Architectures and Alternatives
Architectures and AlternativesArchitectures and Alternatives
Architectures and AlternativesEberhard Wolff
 
The Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryThe Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryEberhard Wolff
 
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncFour Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncEberhard Wolff
 
Microservices - not just with Java
Microservices - not just with JavaMicroservices - not just with Java
Microservices - not just with JavaEberhard Wolff
 
Deployment - Done Right!
Deployment - Done Right!Deployment - Done Right!
Deployment - Done Right!Eberhard Wolff
 
Data Architecture not Just for Microservices
Data Architecture not Just for MicroservicesData Architecture not Just for Microservices
Data Architecture not Just for MicroservicesEberhard Wolff
 
How to Split Your System into Microservices
How to Split Your System into MicroservicesHow to Split Your System into Microservices
How to Split Your System into MicroservicesEberhard Wolff
 
Microservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileMicroservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileEberhard Wolff
 
How Small Can Java Microservices Be?
How Small Can Java Microservices Be?How Small Can Java Microservices Be?
How Small Can Java Microservices Be?Eberhard Wolff
 
Data Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesData Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesEberhard Wolff
 
Microservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityMicroservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityEberhard Wolff
 
Self-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesSelf-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesEberhard Wolff
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology StackEberhard Wolff
 
Software Architecture for Innovation
Software Architecture for InnovationSoftware Architecture for Innovation
Software Architecture for InnovationEberhard Wolff
 
Five (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryFive (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryEberhard Wolff
 
Nanoservices and Microservices with Java
Nanoservices and Microservices with JavaNanoservices and Microservices with Java
Nanoservices and Microservices with JavaEberhard Wolff
 
Microservices: Architecture to Support Agile
Microservices: Architecture to Support AgileMicroservices: Architecture to Support Agile
Microservices: Architecture to Support AgileEberhard Wolff
 
Microservices: Architecture to scale Agile
Microservices: Architecture to scale AgileMicroservices: Architecture to scale Agile
Microservices: Architecture to scale AgileEberhard Wolff
 
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsMicroservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsEberhard Wolff
 

Mehr von Eberhard Wolff (20)

Architectures and Alternatives
Architectures and AlternativesArchitectures and Alternatives
Architectures and Alternatives
 
Beyond Microservices
Beyond MicroservicesBeyond Microservices
Beyond Microservices
 
The Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryThe Frontiers of Continuous Delivery
The Frontiers of Continuous Delivery
 
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncFour Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, Async
 
Microservices - not just with Java
Microservices - not just with JavaMicroservices - not just with Java
Microservices - not just with Java
 
Deployment - Done Right!
Deployment - Done Right!Deployment - Done Right!
Deployment - Done Right!
 
Data Architecture not Just for Microservices
Data Architecture not Just for MicroservicesData Architecture not Just for Microservices
Data Architecture not Just for Microservices
 
How to Split Your System into Microservices
How to Split Your System into MicroservicesHow to Split Your System into Microservices
How to Split Your System into Microservices
 
Microservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileMicroservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale Agile
 
How Small Can Java Microservices Be?
How Small Can Java Microservices Be?How Small Can Java Microservices Be?
How Small Can Java Microservices Be?
 
Data Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesData Architecturen Not Just for Microservices
Data Architecturen Not Just for Microservices
 
Microservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityMicroservices: Redundancy=Maintainability
Microservices: Redundancy=Maintainability
 
Self-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesSelf-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to Microservices
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology Stack
 
Software Architecture for Innovation
Software Architecture for InnovationSoftware Architecture for Innovation
Software Architecture for Innovation
 
Five (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryFive (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous Delivery
 
Nanoservices and Microservices with Java
Nanoservices and Microservices with JavaNanoservices and Microservices with Java
Nanoservices and Microservices with Java
 
Microservices: Architecture to Support Agile
Microservices: Architecture to Support AgileMicroservices: Architecture to Support Agile
Microservices: Architecture to Support Agile
 
Microservices: Architecture to scale Agile
Microservices: Architecture to scale AgileMicroservices: Architecture to scale Agile
Microservices: Architecture to scale Agile
 
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsMicroservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
 

Kürzlich hochgeladen

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Kürzlich hochgeladen (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

10 Typical Java Problems in the Wild

  • 1. Typical Java Problems in the Wild Eberhard Wolff SpringSource Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
  • 2. SpringSource Solution Unifying the Application Lifecycle: from Developer to Datacenter High Productivity Tools Lean Powerful Runtimes Spring Enterprise SpringSource tc Server Groovy and Grails Build   Run   SpringSource dm Server SpringSource Tool Suite SpringSource http Server Manage   Application Infrastructure Management SpringSource Hyperic HQ SpringSource Hyperic IQ Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2
  • 3. About me •  Regional Director German speaking region and Principal Consultant •  Author of several articles and books •  First German Spring book •  Speaker at national and international conferences •  Eberhard.Wolff@springsource.com Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3
  • 4. Why this talk? •  I do a lot of reviews •  There are some common problems you see over and over again •  So: Here are 10 –  …not necessarily the most common –  ...but certainly with severe effects Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4
  • 5. #1 public class Service { private CustomerDao customerDao; private PlatformTransactionManager transactionManager; public void performSomeService() { TransactionStatus transactionStatus = transactionManager .getTransaction(new DefaultTransactionDefinition()); customerDao.doSomething(); customerDao.doSomethingElse(); transactionManager.commit(transactionStatus); } }   Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5
  • 6. #1 Weak Transaction Handling public class Service { private CustomerDao customerDao; private PlatformTransactionManager transactionManager; public void performSomeService() { TransactionStatus transactionStatus = transactionManager .getTransaction(new DefaultTransactionDefinition()); customerDao.doSomething(); customerDao.doSomethingElse(); transactionManager.commit(transactionStatus); } •  What happens to the transaction if the DAO }   throws an exception? •  We might never learn... •  ...or learn the hard way Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6
  • 7. Weak Transaction Handling: Impact •  Hard to detect, has effects only if exception is thrown •  …but then it can lead to wired behavior and data loss etc. •  That is why you are using transactions in the first place Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7
  • 8. Solution •  Declarative transactions public class Service { private CustomerDao customerDao; @Transactional public void performSomeService() { customerDao.doSomething(); customerDao.doSomethingElse(); } }   •  Exception is caught, transaction is rolled back (if it is a RuntimeException) •  Exception handling can be customized Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8
  • 9. A different solution… public void performSomeService() { TransactionTemplate template = new TransactionTemplate( transactionManager); template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { customerDao.doSomething(); customerDao.doSomethingElse(); return null; } }); } •  Allows for multiple transactions in one method •  More code – more control •  Rather seldom really needed Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9
  • 10. #2 Exception Design •  Get all the details from a system exception! •  Each layer must only use its own exceptions! •  Exceptions have to be checked – then they must be handled and the code is more secure. •  Sounds reasonably, doesn't it? Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10
  • 11. public class OrderDao { public void createOrder(Order order) throws SQLException { // some ugly JDBC code // that I am not going to show } } public class SomeService { public void performService() Get all the details! throws ServiceException { Use checked try { exceptions! orderDao.createOrder(new Order()); } catch (SQLException e) { throw new ServiceException(e); Service must only } throw } ServiceException! } public class SomeController { public void handleWebRequest() { try { What am I supposed to do someService.performService(); now? } catch (Exception e) { No real logging e.printStackTrace(); } And I don t care about the } specific ServiceException } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11
  • 12. Impact •  Lots of useless exception handling code •  Lots of exception types without specific handling of that type •  In the end all you get is a log entry and lots of code •  And what should the developer do? –  All he knows "Something went wrong" –  Does not really care and can not really handle it Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12
  • 13. Why is this commonplace? •  Very few languages have checked exceptions (Java - CLU and Modula-3 had similar concepts) •  Checked exception force developers to handle an exception – very rigid •  How common is it that you can really handle an exception? •  Checked exceptions are perceived to be more secure •  Checked exceptions are overused – also in Java APIs •  In many cases there are even no exception concepts in projects Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13
  • 14. Solution •  Use more unchecked exceptions aka RuntimeExceptions •  Remember: A lot of languages offer only unchecked exceptions •  Avoid wrap-and-rethrow – it does not add value •  Don't write too many exception classes – they often don't add value •  A specific exception classes is only useful if that exception should be handled differently Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14
  • 15. Solution public class OrderDao { public void createOrder(Order order) { jdbcTemplate.update("INSERT INTO ORDER ..."); } } public class SomeService { Where is the public void performService() { exception } orderDao.createOrder(new Order()); handling? } public class SomeController { public void handleWebRequest() { someService.performService(); } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15
  • 16. AOP in one Slide @Aspect public class AnAspect { // do something before the method hello // is executed @Before("execution(void hello())") public void doSomething() { } // in a specific class // that ends in Service in any package or subpackage @Before("execution(* com.springsource.MyService.hello())") public void doSomethingElse2() { } // do something before any method in a class // that ends in Service in any package or subpackage @Before("execution(* *..*Service.*(..))") public void doSomethingElse2() { } 16 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
  • 17. Aspect for Logging @Aspect public class ExceptionLogging { @AfterThrowing(value="execution(* *..Service*.*(..))", throwing="ex") public void logRuntimeException(RuntimeException ex) { System.out.println(ex); } } •  Logs every exception – 100% guaranteed! Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17
  • 18. Handle only cases you really want to handle public class SomeService { public void performService() { try { orderDao.createOrder(new Order()); } catch (OptimisticLockingFailureException ex) { orderDao.createOrder(new Order()); } } } •  Everything else will be handled somewhere else •  Can handle specific error conditions using catch with specific types Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18
  • 19. Generic Exception Handling public class MyHandlerExceptionResolver implements HandlerExceptionResolver { public ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { return new ModelAndView("exceptionView", "exception", ex); } } •  In the web layer •  Handle all the (Runtime)Exceptions not handled elsewhere Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19
  • 20. #3 Exception Handling public void someMethod() { try { } catch (Exception ex) { Exception is not logged ex.printStackTrace(); just written to stdout } operations might not notice try { } catch (Exception ex) { // should never happen Exception is swallowed } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20
  • 21. Impact •  Related to #2: If you have excessive checked exceptions this will occur more often •  …as developers are forced to handle exceptions they can't really handle •  In the end you just get a message on the console and the application continues. •  All kinds of wired behavior •  i.e. exception is swallowed •  You will have a hard time finding problems in the code •  Potentially a huge problem – so worth its own explanation Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21
  • 22. Solution •  At least log exceptions •  Rethink: Is it really OK to continue in this situation? If not - don't handle the exception. Might be better to let a generic handler handle it. •  Introduce generic handling at least for RuntimeException (AOP, web front end, etc) •  Enforce the logging using Findbugs, PMD etc. •  And: Improve the public void someMethod() { exception design (#2) try { } catch (Exception ex) { log.error(ex); } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22
  • 23. #4 •  Table of packages and the relations between them •  Everything in red is part of a cycle •  This is actual code from an Open Source project Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23
  • 24. Dependency Graph •  Overview Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24
  • 25. Dependency Graph •  Just a small part •  Red line show circular references Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25
  • 26. What is Architecture? •  Architecture is the decomposition of systems in parts •  No large or complex parts •  No cyclic dependencies Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26
  • 27. Normal Dependencies •  B dependes on A, i.e. it uses classe, methods etc. •  Changes in A impact B Component A •  Changes in B do not impact A Component B Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27
  • 28. Cyclic Dependency •  B depends on A and A on B •  Changes in A impact B •  Changes in B impact A Component A •  A and B can only be changed as one unit •  …even though they should be two separate units Component B Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28
  • 29. Bigger cyclic dependencies Component A Component B Component C Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29
  • 30. #4: Architecture Mess •  This is effectively just one big unstructured pile of mud •  Maintenance will be hard •  Concurrent development will be hard •  Changes will have unforeseeable results Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30
  • 31. Solution •  Very hard if you have this state •  Therefore: Manage dependencies from the start •  Otherwise you are looking at a major restructuring of your application •  …which might not be worth it •  Effort for restructuring pays off by lower effort for maintenance •  …might take a long time to amortize •  Throwing away + redevelopment means that you have to migrate to a new solution -> complex and risky Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31
  • 32. #5 public class ServiceAdaptor { public void performService(OrderDTO orderDTO) { logger.trace("Entering performService"); try { if (orderDTO == null) { throw new NullPointerException("order must not be null"); } if (youAreNotAllowedToDoThis()) { throw new IllegalStateException( "You are not allowed to call this!"); } OrderEntity order = new OrderEntity(); order.setCustomer(orderDTO.getCustomer()); // ... service.performService(order); commandLog.add(new Command("performService", service,order)); } finally { logger.trace("Leaving performanceService"); } } } 32 Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
  • 33. #5: Adaptor Layer •  Adds to a service: –  Security –  Tracing –  Check for null arguments –  Log for all commands (auditing, replay…) –  Conversion from DTO to internal representation •  Lots of boilerplate for each service •  Changes to tracing etc. hard: lots of methods to change Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33
  • 34. Solution: Tracing with AOP •  …or use Spring's predefined TraceInterceptor, DebugInterceptor etc. @Aspect public class TraceAspect { @Before("execution(* *..*Service.*(..))") public void traceBegin(JoinPoint joinPoint) { System.out.println("entering method " + joinPoint.getSignature().getName()); } @After("execution(* *..*Service.*(..))") public void traceEnd(JoinPoint joinPoint) { System.out.println("leaving method " + joinPoint.getSignature().getName()); } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34
  • 35. Solution: Null Checks with AOP @Aspect public class NullChecker { @Before("execution(* *..*Service.*(..))") public void checkForNull(JoinPoint joinPoint) { for (Object arg : joinPoint.getArgs()) { if (arg==null) { throw new NullPointerException("Argument was null!"); } } } } •  Security can be handled with Spring Security or AOP •  Command log also possible Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35
  • 36. What is left… public class ServiceAdaptor { public void performService(OrderDTO orderDTO) { OrderEntity order = new OrderEntity(); order.setCustomer(orderDTO.getCustomer()); // ... service.performService(order); } } •  You should probably switch to Dozer •  http://dozer.sf.net •  Can externalize mapping rules •  i.e. the layer can be more or less eliminated •  Everything (mapping, security, tracing…) is now implemented in one place (DRY) •  Often services just delegate to DAOs – same issue Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36
  • 37. #6: No DAO public class SomeService { @PersistenceContext private EntityManager entityManager; public void performSomeService() { List<Order> list = entityManager. createQuery("select o from Order").getResultList(); for (Order o : list) { // ... if (o.shouldBeProcessed()) { o.process(); } } } } •  We don't need to abstract away from JPA – it's a standard, right? Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37
  • 38. #6: Even worse public class SomeServiceJdbc { private OrderDao someDoa; public void performSomeService() throws SQLException { ResultSet rs = someDoa.getOrders(); while (rs.next()) { //... } } } •  Service depends on JDBC •  …and throws SQLException •  Persistence visible in the service layer and beyond Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38
  • 39. Impact •  Code is impossible to test without a database •  …so no real unit tests possible •  Service depends on persistence – cannot be ported •  How do you add data dependent security? •  No structure Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39
  • 40. Solution •  Use a DAO (Data Access Object) –  Separate persistence layer –  Technical motivation •  …or a Repository –  Interface to existing objects –  Non technical motivation: Domain Driven Design, Eric Evans •  Basically the same thing Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40
  • 41. Solution public class SomeServiceDAO { public void performSomeService() { List<Order> list = orderDao.getAllOrders(); for (Order o : list) { // ... if (o.shouldBeProcessed()) { o.process(); } } } } •  Clear separation •  Tests easy Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41
  • 42. Solution: Test public class ServiceTest { @Test public void testService() { SomeService someService = new SomeService(); someService.setOrderDao(new OrderDao() { public List<Order> getAllOrders() { List<Order> result = new ArrayList<Order>(); return result; } }); someService.performSomeService(); Assert.assertEquals(expected, result); } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42
  • 43. #7 •  No Tests Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 43
  • 44. #7 Or bad tests •  No asserts public class MyUnitTest { private Service service = new Service(); •  System.out: results are @Test checked public void testService() { manually Order order = new Order(); service.performService(order); •  Tests commented System.out.print(order.isProcessed()); out: They did not } run any more and were not // @Test // public void testOrderCreated() { fixed // Order order = new Order(); •  No mocks, so no // service.createOrder(order); real Unit Tests // } •  No negative } cases Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 44
  • 45. Impact •  Code is not properly tested •  Probably low quality – testable code is usually better designed •  Code is hard to change: How can you know the change broke nothing? •  Design might be bad: Testable usually mean better quality Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 45
  • 46. Solution •  Write proper Unit Tests! public class MyProperUnitTest { private Service service = new Service(); @Test public void testService() { Order order = new Order(); service.performService(order); Assert.assertTrue(order.isProcessed()); } @Test(expected=IllegalArgumentException.class) public void testServiceException() { Order order = new BuggyOrder(); service.performService(order); } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 46
  • 47. Wow, that was easy! Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
  • 48. The real problem… •  The idea of Unit tests is over 10 years old •  Not too many programmer actually do real unit tests •  Even though it should greatly increased trust and confidence in your code •  …and make you much more relaxed and therefore improve quality of life… •  Original paper: Gamma, Beck: "Test Infected – Programmers Love Writing Tests" •  Yeah, right. Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 48
  • 49. BTW Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 49
  • 50. Solution •  Educate –  Show how to write Unit Test –  Show how to build Mocks –  Show aggressive Testing –  Show Test First / Test Driven Development •  Coach / Review •  Integrate in automatic build •  Later on: Add integration testing, functional testing, FIT, Fitnesse etc. •  …or even start with these Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 50
  • 51. What does not really work •  Measuring code coverage –  Can be sabotaged public class MyProperUnitTest { private Service service = new Service(); @Test public void testService() { Order order = new Order(); service.performService(order); } } •  Let developers just write tests without education –  How should they know how to test properly? –  Test driven development is not obvious Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 51
  • 52. #8: Creating SQL statements public class OrderDAO { private SimpleJdbcTemplate simpleJdbcTemplate; public List<Order> findOrderByCustomer(String customer) { return simpleJdbcTemplate.query( "SELECT * FROM T_ORDER WHERE name='" + customer + "'", new OrderRowMapper()); } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 52
  • 53. Impact •  Performance is bad: –  Statement is parsed every time –  Execution plan is re created etc. Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 53
  • 54. Impact •  Even worse: SQL injection •  Pass in a' or 't'='t' •  Better yet: a'; DROP TABLE T_ORDER; SELECT * FROM ANOTHER_TABLE public class OrderDAO { private SimpleJdbcTemplate simpleJdbcTemplate; public List<Order> findOrderByCustomer(String customer) { return simpleJdbcTemplate.query( "SELECT * FROM T_ORDER WHERE name='" + customer + "'", new OrderRowMapper()); } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 54
  • 55. Solution public class OrderDAO { private SimpleJdbcTemplate simpleJdbcTemplate; public List<Order> findOrderByCustomer(String customer) { return simpleJdbcTemplate.query( "SELECT * FROM T_ORDER WHERE name=?", new OrderRowMapper(), customer); } } •  … and white list the allowed characters in name Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 55
  • 56. #9 •  "What about Performance?" •  "Well, we figured the response time should be 2s." •  "How many request do you expect?" •  "…" •  "What kind of requests do you expect?" •  "..." Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 56
  • 57. #9 •  The software is happily in the final functional test •  Then the performance test start •  Performance is too bad to be accepted •  You can hardly do anything: –  Changes might introduce functional errors –  Too late for bigger changes anyway •  The results might be wrong if the performance test is on different hardware than production. •  You can't test on production hardware: Too expensive. Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 57
  • 58. Impact •  You have to get bigger hardware –  Prerequisite: The software is scalable •  Worse: You can't go into production Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 58
  • 59. Solution •  Get information about the number of requests, expected types of requests, acceptable response times •  Pro active performance management: –  Estimate the performance before implementation –  …by estimating the slow operations (access to other systems, to the database etc) –  Measure performance of these operation in production •  Practice performance measurements and optimizations before performance test Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 59
  • 60. #10 public class SomeService { private Map cache = new HashMap(); private Customer customer; public Order performService(int i) { if (cache.containsKey(i)) { return cache.get(i); } Order result; customer = null; cache.put(i, result); return result; } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 60
  • 61. #10 Multiple threads, memory leaks public class SomeService { The cache is filled – private Map<Integer,Order> cache = is it ever emptied? new HashMap<Integer, Order>(); private Customer customer; HashMap is not public Order performService(int i) { threadsafe if (cache.containsKey(i)) { return (Ordercache.get(i); customer is an } instance variable – Order result; multi threading will customer = null; ... be a problem cache.put(i, result); return result; } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 61
  • 62. Impact •  System working in small tests •  In particular Unit tests work •  But production fails •  …probably hard to analyze / fix •  Almost only by code reviews •  …or extensive debugging using thread dumps Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 62
  • 63. Solution public class SomeServiceSolution { •  Use WeakHashMap to avoid memory leaks private Map<Integer, Order> cache = new WeakHashMap<Integer, Order>(); •  Synchronize •  Prefer local variables public Order performService(int i) { synchronized (cache) { •  Usually services can if (cache.containsKey(i)) { store most things in return cache.get(i); } local variables } Order result = null; Customer customer = null; synchronized (cache) { cache.put(i, result); } return result; } } Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 63
  • 64. Solution •  Also consider ConcurrentHashMap •  or http://sourceforge.net/projects/high-scale-lib Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 64
  • 65. Sum Up •  #1 Weak Transaction •  #8 Creating SQL Handling queries using String •  #2 Exception Design concatenation •  #3 Exception Handling •  #9 No performance •  #4 Architecture Mess management •  #10 Multiple threads / •  #5 Adaptor Layer memory leaks •  #6 No DAO •  #7 No or bad tests Copyright 2009 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 65