{{theTime}}

Search This Blog

Total Pageviews

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

java.util.MissingFormatArgumentException: Format specifier '%s'

java.util.MissingFormatArgumentException: Format specifier '%s'
at java.util.Formatter.format(Formatter.java:2519)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2928)

Fix: 
   Check number of %s specifiers in the String and make sure all arguments added in String.format() method.

For example:  String output= "<html><title>%s</title><body>%s</body></html>" ;
String.format(output,"programmersstack","Welcome") ;

Java 8 HashMap Streaming Example

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class JavaStreamExample {

    public static void main(String[] args) {

        Map<Integer, String> countryMap = new HashMap<>();
        countryMap.put(1, "USA");
        countryMap.put(2, "UK");
        countryMap.put(3, "AUSTRALIA");
        countryMap.put(4, "BRAZIL");

         for (Map.Entry<Integer, String> entry : countryMap.entrySet()) {
            if ("BRAZIL".equals(entry.getValue())) {
                System.out.println( " Before Java 8 : " +entry.getValue());
            }
        }
         String streamResult = countryMap.entrySet().stream()
                .filter(map -> "BRAZIL".equals(map.getValue()))
                .map(map -> map.getValue())
                .collect(Collectors.joining());

        System.out.println("Sreaming example : " + streamResult );

    }
}

IdentityHashMap Implementation

/**
 * IdentifyHashMap  - 
 *   - Implements Map Interface with a hash table using reference-equality instead of object-equality when comparing keys.
 *    Eg:  if ( k1 == k2 ) unlike HashMap equality if( K1 == null ? k2 ==null : k1.equals(k2)).
 *   - It's not a general purpose implementation and designed to use only in rare cases where reference-equality semantics are required
 *   - Use cases like topology-preserving object graph, deep-copying, adding application shutdown hook.
 *   - This Map is not synchronized.  To synchronize use Collections SynchronizedMap
 *       Map identifyHashMap = Collections.synchronizedMap( new IdentifyHashMap(..)) ; 

 *
 */


import java.util.Collection;
import java.util.IdentityHashMap;

public class ApplicationDaemons
{
    private static IdentityHashMap<Thread, Thread> applicationdaemons = new IdentityHashMap<>();

    public synchronized void runDaemonsInSeperateThread() {
        new Runnable()
        {
            public void run()
            {
                runDaemons() ;
            }
        } ;    
    }

    private ApplicationDaemons() {}

    static synchronized void add(Thread hook) {
        if(applicationdaemons != null)
            applicationdaemons.put(hook, hook);
    }

    static synchronized boolean remove(Thread hook) {
        return applicationdaemons.remove(hook) != null;
    }

    static void runDaemons() {
        Collection<Thread> threads;
        synchronized(ApplicationDaemons.class) {
            threads = applicationdaemons.keySet();
            applicationdaemons = null;
        }

        for (Thread hook : threads) {
            hook.start();
        }
        for (Thread hook : threads) {
            try {
                hook.join();
            } catch (InterruptedException x) { }
        }
    }
}

How to fix Unhandled Exception type SQLException


3 Quick Fixes.
Add throws declaration
Surround with try/multi-catch
Surround with try/catch

assertThat(T, Matcher) in the type Assert is not applicable for the arguments (long, Matcher)

This exception is thrown when assert compares different primitive types. 
  -- Change the expected value to be long.


assertThat(1L, equalTo(1))



assertThat(1L, equalTo(1L))

java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

The * is a reserved character in RegEx. Escape the * using \\. Example: String [] linesplitter = line.split("\\*");

Useful Java Runtime Commands and Executable Sizes (In bytes)


List of Commands and Size in Bytes.

Useful Java Run time Options


How to Print Garbage Collection Output with Time Stamp?

set -XX:PrintGCCompilation

How to use Performance tuning flags to optimize throughput Faster?

    java -d64 -server -XX:+AggressiveOpts -XX:+UseLargePages -Xmn10g -Xms26g -Xmx26g

How to use Performance tuning flags to optimize throughput Lower?

    java -d64 -XX:+UseG1GC -Xms26g Xmx26g -XX:MaxGCPauseMillis=500 -XX:+PrintGCTimeStamps

How to get Stack Trace of all Java Threads?

  bin>jstack.exe -l PID

   -- Used to troubleshoot hangs and crashes

How to connect to a Hung Process?
   bin> jstack.exe -F -m -l <PID>

How to set GC Threads?

Set Java Run Time Argument:
-XX:ParallelGCThreads=n


How to set GC Pause time?

Set JVM Runtime Argument:
-XX:MaxGCPauseMillis=n



How to use Java VisualVM to find Memory Leaks

Run Java command line tool to connect to running JVM.

    Command : jdk\bin\jvisualvm.exe




What is java.util.concurrent.ExecutionException?

This is an Exception thrown when trying to retrieve the result of a task that aborted by throwing an exception.   Throwable.getCause() can be inspected for further trouble shooting.

Java 8 is Here! - Last Call to REGISTER for the Webcast


View this message in a web browser
Create the Future with Java 8. Register for the Launch Webcast.

Join Oracle and 9 Million Developers

Java 8 is a revolutionary release of the world's #1 development platform. It is the single largest upgrade ever to the programming model, with coordinated core code evolution of the virtual machine, core language, and libraries. With Java 8, developers are uniquely positioned to extend innovation through the largest, open, standards-based, community-driven platform.

Featured Presenters

Mark Reinhold

Mark Reinhold

Chief Architect, Java Platform Group, Oracle

Peter Utzschneider

Peter Utzschneider

Vice President, Product Management, Oracle

Community Members

Brian Goetz

Java Language Architect, Oracle

Robert Vandette

Consulting Member of Technical Staff, Oracle

Roger Riggs

Consulting Member of Technical Staff,
Oracle

Richard Bair

Java Client Architect, Oracle

Jim Gough

Associate Leader,
London Java Community

LJC

 

Bruno Souza

Founding Member, SouJava

SouJava

John Rose

Java VM Architect, Oracle

Oracle Partner

Adam Messinger

Chief Technology Officer, Twitter

Twitter

 

Launch Webcast: Create the Future with Java 8

Tuesday, March 25, 2014    10 a.m. PT / 1 p.m. ET

Register now to hear from the experts.
Facebook  Twitter  Blog  LinkedIn  YouTube  GooglePlus

Get in on the conversation: #Java8

Join Oracle and participants from the Java community to learn how Java 8 can help you:

  • Deliver better application performance and simpler parallel programming models with Project Lambda while providing enhanced developer productivity
  • Maximize application flexibility through a choice of runtime for more-efficient deployments with Java SE 8 Compact Profiles and Java ME 8
  • Implement new Internet of Things services on a common Java platform while creating robust and highly performant embedded and enterprise applications

Register now for the Java 8 keynote address and more than 35 deep-dive technical sessions.

Use #Java8QA to tweet questions for the Oracle Java Architect Team in advance of and during the webcast.

Join the discussion on the OTN Java 8 Forums.

Oracle
Facebook  Twitter  Blog  LinkedIn  YouTube  GooglePlus
Hardware and Software Engineered to Work Together

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Contact Us | Legal Notices and Terms of Use | Privacy Statement

SEV100289408_LRT100289406


Oracle Corporation - Worldwide Headquarters, 500 Oracle Parkway, OPL - E-mail Services, Redwood Shores, CA 94065, United States

Your privacy is important to us. You can login to your account to update your e-mail subscriptions or you can opt-out of all Oracle Marketing e-mails at any time.

Please note that opting-out of Marketing communications does not affect your receipt of important business communications related to your current relationship with Oracle such as Security Updates, Event Registration notices, Account Management and Support/Service communications.


Fibonacci Series Java Program

/**
 * Print first 10 Fibonacci numbers.
 * --The sequence has been used in the design of a building
 * -- Used in Sprint Planning in Agile Practice
 *
 */
public class TestFibonacci
{
        public static void main(String[] args) {          
           int fib = 0, nextFib = 1;

           for (int i = 1; i <= 10; i++) {
              fib = fib + nextFib;
              nextFib = fib - nextFib;
              System.out.println(fib);
           }
        }
}

File to File Copy Using Java Streams

  1. package com.dev.concurrent;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. /**
  6.  * File to File Copy using Java Streams.
  7.  *
  8.  */
  9. public class StreamExample
  10. {      
  11.     public void byteStreamExample() {       
  12.         try(FileInputStream in = new FileInputStream("samplein.txt")) {
  13.             try (FileOutputStream out = new FileOutputStream("sampleout.txt")) {           
  14.                 int c;
  15.                 while ((c = in.read()) != -1) {
  16.                     out.write(c);
  17.                 }
  18.             }catch (IOException e) {
  19.                 e.printStackTrace();
  20.             }
  21.         } catch (IOException e) {
  22.             e.printStackTrace();
  23.         }
  24.     }
  25.      
  26.     public static void main(String[] args)
  27.     {   
  28.         StreamExample se = new StreamExample() ;
  29.         se.byteStreamExample() ;
  30.     }
  31. }

Immutable Objects in Java

Immutable objects
        - Objects consider immutable if its state cannot change after it is constructed.
- Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
- Make all fields final and private.
- Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
- If the instance fields include references to mutable objects, don't allow those objects to be changed:
- Don't provide methods that modify the mutable objects.
- Don't share references to the mutable objects. 
- Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

How to filter the file names in a directory using Java.

 
public String[] filterFileNames() throws IOException
   String pattern = "Today";
   final Pattern p = Pattern.compile(pattern);
   FilenameFilter filter = new FilenameFilter() {
   public boolean accept(File fdir, String fname)
   {
       Matcher m = p.matcher(fname);
       return m.matches();
   }};
   File dirFile = new File( "directory path" );
   String[] filteredFiles = dirFile.list(filter); 
   return filteredFiles ;
}



How to thread safe public static methods using locks

How to thread safe public static methods:
If any third party public methods which are not thread safe, create global locks.

Sample Code:
static Object internalLock = new Object() ;
synchronize(internalLock){
  call public API;
}

How to create temp file in Java

File temp = File.createTempFile(_prefix, _suffix, _tempDir)

String.split(String regex, int limit)


split

public String[] split(String regex,
                      int limit)
Splits this string around matches of the given regular expression.The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at mostn - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
The string "boo:and:foo", for example, yields the following results with these parameters:
RegexLimitResult
:2{ "boo", "and:foo" }
:5{ "boo", "and", "foo" }
:-2{ "boo", "and", "foo" }
o5{ "b", "", ":and:f", "", "" }
o-2{ "b", "", ":and:f", "", "" }
o0{ "b", "", ":and:f" }

It is equal as Pattern.compile(regex).split(str, n) 

Optimizing Java Applications for Low-Latency Microservices

Introduction Microservices architecture has become a go-to for building scalable, modular systems, but achieving low latency in Java-based...