구글 안드로이드 코드 스타일

Posted by epicdev Archive : 2011. 9. 21. 04:50
출처: https://sites.google.com/a/android.com/opensource/submit-patches/code-style-guide

Android Code Style Rules

The rules below are not guidelines or recommendations, but strict rules. You may not disregard the rules we list below except as approved on a need-to-use basis.

Not all existing code follows these rules, but all new code is expected to.

Java Language Rules

We follow standard Java coding conventions. We add a few rules:

  1. Exceptions: Never catch and ignore them without explanation.
  2. Exceptions: do not catch generic Exception, except in library code at the root of the stack.
  3. Finalizers: generally don't use them.
  4. Imports: Fully qualify imports

Java Library Rules

There are conventions for using Android's Java libraries and tools. In some cases, the convention has changed in important ways and older code might use a deprecated pattern or library. When working with such code, it's okay to continue the existing style (see Consistency). When creating new components never use deprecated libraries.

Java Style Rules

Programs are much easier to maintain when all files have a consistent style. We follow the standard Java coding style, as defined by Sun in their Code Conventions for the Java Programming Language, with a few exceptions and additions. This style guide is comprehensive and detailed and is in common usage in the Java community.

In addition, we enforce the following style rules:

  1. Comments/Javadoc: write it; use standard style
  2. Short methods: don't write giant methods
  3. Fields: should either be at the top of the file, or immediately before the methods that use them
  4. Local variables: limit the scope
  5. Imports: android; third party alphabetical; java(x)
  6. Indentation: 4 spaces, no tabs.
  7. Line length: 100 columns
  8. Field names: Non-public, non-static fields start with m. Static fields start s.
  9. Braces: Opening braces don't go on their own line.
  10. Annotations: Use the standard annotations.
  11. Acronyms are words: Treat acronyms as words in names, yielding XmlHttpRequestgetUrl(), etc.
  12. TODO style: "TODO: write this description"
  13. Consistency: Look at what's around you!
  14. Logging: Be careful with logging. It's expensive.

Javatests Style Rules

  1. Naming test methods: testMethod_specificCase is ok

Java Language Rules

Exceptions: do not ignore

Sometimes it is tempting to write code that completely ignores an exception like this:
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
}
}

You must never do this. While you may think that your code will never encounter this error condition or that it is not important to handle it, ignoring exceptions like above creates mines in your code for someone else to trip over some day. You must handle every Exception in your code in some principled way. The specific handling varies depending on the case.

Anytime somebody has an empty catch clause they should have a creepy feeling. There are definitely times when it is actually the correct thing to do, but at least you have to think about it. In Java you can't escape the creepy feeling.

Acceptable alternatives (in order of preference) are:

  • Throw the exception up to the caller of your method.
    void setServerPort(String value) throws NumberFormatException {
    serverPort = Integer.parseInt(value);
    }

  • Throw a new exception that's appropriate to your level of abstraction.
    void setServerPort(String value) throws ConfigurationException {
    try {
    serverPort = Integer.parseInt(value);
    } catch (NumberFormatException e) {
    throw new ConfigurationException("Port " + value + " is not valid.");
    }

  • Handle the error gracefully and substitute an appropriate value in the catch {} block.
    /** Set port. If value is not a valid number, 80 is substituted. */
    void setServerPort(String value) {
    try {
    serverPort = Integer.parseInt(value);
    } catch (NumberFormatException e) {
    serverPort = 80; // default port for server
    }
  • Catch the Exception and throw a new RuntimeException. This is dangerous: only do it if you are positive that if this error occurs, the appropriate thing to do is crash.
    /** Set port. If value is not a valid number, die. */
    void setServerPort(String value) {
    try {
    serverPort = Integer.parseInt(value);
    } catch (NumberFormatException e) {
    throw new RuntimeException("port " + value " is invalid, ", e);
    }
    Note that the original exception is passed to the constructor for RuntimeException. This wrapped exception paradigm is very useful but only works in Java 1.4. If your code must compile under Java 1.3, you will need to omit the exception that is the cause.

  • Last resort: if you are confident that actually ignoring the exception is appropriate then you may ignore it, but you must also comment why with a good reason:
    /** If value is not a valid number, original port number is used. */
    void setServerPort(String value) {
    try {
    serverPort = Integer.parseInt(value);
    } catch (NumberFormatException e) {
    // Method is documented to just ignore invalid user input.
    // serverPort will just be unchanged.
    }
    }

Exceptions: do not catch generic Exception

Sometimes it is tempting to be lazy when catching exceptions and do something like this:
try {
someComplicatedIOFunction(); // may throw IOException
someComplicatedParsingFunction(); // may throw ParsingException
someComplicatedSecurityFunction(); // may throw SecurityException
// phew, made it all the way
} catch (Exception e) { // I'll just catch all exceptions
handleError(); // with one generic handler!
}

You should not do this. In almost all cases it is inappropriate to catch generic Exception or Throwable, preferably not Throwable, because it includes Error exceptions as well. It is very dangerous. It means that Exceptions you never expected (including RuntimeExceptions like ClassCastException) end up getting caught in application-level error handling. It obscures the failure handling properties of your code. It means if someone adds a new type of Exception in the code you're calling, the compiler won't help you realize you need to handle that error differently. And in most cases you shouldn't be handling different types of exception the same way, anyway.

There are rare exceptions to this rule: certain test code and top-level code where you want to catch all kinds of errors (to prevent them from showing up in a UI, or to keep a batch job running). In that case you may catch generic Exception (or Throwable) and handle the error appropriately. You should think very carefully before doing this, though, and put in comments explaining why it is safe in this place.

Alternatives to catching generic Exception:

  • Catch each exception separately as separate catch blocks after a single try. This can be awkward but is still preferable to catching all Exceptions. Beware repeating too much code in the catch blocks.
  • Refactor your code to have more fine-grained error handling, with multiple try blocks. Split up the IO from the parsing, handle errors separately in each case.
  • Rethrow the exception. Many times you don't need to catch the exception at this level anyway, just let the method throw it.
Remember: exceptions are your friend! When the compiler complains you're not catching an exception, don't scowl. Smile: the compiler just made it easier for you to catch runtime problems in your code.

Finalizers

What it is: Finalizers are a way to have a chunk of code executed when an object is garbage collected.

Pros: can be handy for doing cleanup, particularly of external resources.

Cons: there are no guarantees as to when a finalizer will be called, or even that it will be called at all.

Decision: we don't use finalizers. In most cases, you can do what you need from a finalizer with good exception handling. If you absolutely need it, define a close() method (or the like) and document exactly when that method needs to be called. See InputStream for an example. In this case it is appropriate but not required to print a short log message from the finalizer, as long as it is not expected to flood the logs.

The one exception is it is OK to write a finalizer if all it does is make calls to X.assertTrue().

Imports

Wildcards in imports

What it is: When you want to use class Bar from package foo,there are two possible ways to import it:

  1. import foo.*;
  2. import foo.Bar;

Pros of #1: Potentially reduces the number of import statements.

Pros of #2: Makes it obvious what classes are actually used. Makes code more readable for maintainers.

Decision:Use style #2 for importing all Android code. An explicit exception is made for java standard libraries (java.util.*, java.io.*, etc.) and unit test code (junit.framework.*).

Comments/Javadoc

Every file should have a copyright statement at the top. Then a package statement and import statements should follow, each block separated by a blank line. And then there is the class or interface declaration. In the Javadoc comments, describe what the class or interface does.

/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.android.internal.foo;

import android.os.Blah;
import android.view.Yada;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
* Does X and Y and provides an abstraction for Z.
*/
public class Foo {
...
}

Every class and nontrivial public method you write must contain a Javadoc comment with at least one sentence describing what the class or method does. This sentence should start with a 3rd person descriptive verb. Examples:

/** Returns the correctly rounded positive square root of a double value. */
static double sqrt(double a) {
}

/**
* Constructs a new String by converting the specified array of
* bytes using the platform's default character encoding.
*/
public String(byte[] bytes) {
}

You do not need to write Javadoc for trivial get and set methods such as setFoo() if all your Javadoc would say is "sets Foo". If the method does something more complex (such as enforcing a constraint or having an important side effect), then you must document it. And if it's not obvious what the property "Foo" means, you should document it.

Every method you write, whether public or otherwise, would benefit from Javadoc. Public methods are part of an API and therefore require Javadoc.

Android does not currently enforce a specific style for writing Javadoc comments, but you should follow the Sun Javadoc conventions.

Short methods

To the extent that it is feasible, methods should be kept small and focused. It is, however, recognized that long methods are sometimes appropriate, so no hard limit is placed on method length. If a method exceeds 40 lines or so, think about whether it can be broken up without harming the structure of the program.

Local variables

The scope of local variables should be kept to a minimum (Effective Java Item 29). By doing so, you increase the readability and maintainability of your code and reduce the likelihood of error. Each variable should be declared in the innermost block that encloses all uses of the variable.

Local variables should be declared at the point they are first used. Nearly every local variable declaration should contain an initializer. If you don't yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do.

One exception to this rule concerns try-catch statements. If a variable is initialized with the return value of a method that throws a checked exception, it must be initialized inside a try block. If the value must be used outside of the try block, then it must be declared before the try block, where it cannot yet be sensibly initialized:

// Instantiate class cl, which represents some sort of Set
Set s = null;
try {
s = (Set) cl.newInstance();
} catch(IllegalAccessException e) {
throw new IllegalArgumentException(cl + " not accessible");
} catch(InstantiationException e) {
throw new IllegalArgumentException(cl + " not instantiable");
}

// Exercise the set
s.addAll(Arrays.asList(args));

But even this case can be avoided by encapsulating the try-catch block in a method:

Set createSet(Class cl) {
// Instantiate class cl, which represents some sort of Set
try {
return (Set) cl.newInstance();
} catch(IllegalAccessException e) {
throw new IllegalArgumentException(cl + " not accessible");
} catch(InstantiationException e) {
throw new IllegalArgumentException(cl + " not instantiable");
}
}
...
// Exercise the set
Set s = createSet(cl);
s.addAll(Arrays.asList(args));
Loop variables should be declared in the for statement itself unless there is a compelling reason to do otherwise:
for (int i = 0; i < n; i++) {
doSomething(i);
}

for (Iterator i = c.iterator(); i.hasNext(); ) {
doSomethingElse(i.next());
}


Imports

The ordering of import statements is:
  • Android imports
  • Imports from third parties (com, junit, net, org) 
  • java and javax

    To exactly match the IDE settings, the imports should be:

  • Alphabetical within each grouping.
        Capital letters are considered to come before lower case letter (e.g. Z before a).
  • There should be a blank line between each major grouping (android, com, junit, net, org, java, javax).

    Why?

    Originally there was no style requirement on the ordering. This meant that the IDE's were either always changing the ordering, or IDE developers had to disable the automatic import management features and maintain the imports by hand. This was deemed bad. When java-style was asked, the preferred styles were all over the map. It pretty much came down to our needing to "pick an ordering and be consistent." So we chose a style, updated the javaguide and made the IDE's obey it. We expect that as IDE users work on the code, the imports in all of the packages will end up matching this pattern without any extra engineering effort.

    The style chosen such that:

  • The imports people want to look at first tend to be at the top (android)
  • The imports people want to look at least tend to be at the bottom (java)
  • Humans can easily follow the style
  • The IDE's can follow the style

    What about static imports?

    The use and location of static imports have been mildly controversial issues. Some people would prefer static imports to be interspersed with the remaining imports, some would prefer them reside above or below all other imports. Additinally, we have not yet come up with a way to make all IDEs use the same ordering.

    Since most people consider this a low priority issue, just use your judgement and please be consistent.

    Indentation

    We use 4 space indents for blocks. We never use tabs. When in doubt, be consistent with code around you.

    We use 8 space indents for line wraps, including function calls and assignments. For example, this is correct:

    Instrument i
    = someLongExpression(that, wouldNotFit, on, one, line);
    and this is not correct:
    Instrument i
    = someLongExpression(that, wouldNotFit, on, one, line);

    Field Names

    • Non-public, non-static field names start with m.
    • Static field names start with s.
    • Other fields start with a lower case letter.
    • Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.

    For example:

    public class MyClass {
    public static final int SOME_CONSTANT = 42;
    public int publicField;
    private static MyClass sSingleton;
    int mPackagePrivate;
    private int mPrivate;
    protected int mProtected;
    }

    Braces

    Braces do not go on their own line; they go on the same line as the code before them. So:

    class MyClass {
    int func() {
    if (something) {
    // ...
    } else if (somethingElse) {
    // ...
    } else {
    // ...
    }
    }
    }

    We require braces around the statements for a conditional. Except, if the entire conditional (the condition and the body) fit on one line, you may (but are not obligated to) put it all on one line. That is, this is legal:

    if (condition) {
    body; // ok
    }
    if (condition) body; // ok

    but this is still illegal:

    if (condition)
    body; // bad

    Line length

    Each line of text in your code should be at most 100 characters long.

    There has been lots of discussion about this rule and the decision remains that 100 characters is the maximum.

    Exception: if a comment line contains an example command or a literal URL longer than 100 characters, that line may be longer than 100 characters for ease of cut and paste.

    Exception: import lines can go over the limit because humans rarely see them. This also simplifies tool writing.

    Java 1.5 Annotations

    Annotations should precede other modifiers for the same language element. Simple marker annotations (e.g. @Override) can be listed on the same line with the language element. If there are multiple annotations, or parameterized annotations, they should each be listed one-per-line in alphabetical order.

    Android -standard practices for the three predefined annotations in Java 1.5's are:

    @Deprecated
    The @Deprecated annotation must be used whenever the use of the annotated element is discouraged. If you use the @Deprecated annotation, you must also have a @deprecated Javadoc tag and it should name an alternate implementation. In addition, remember that a@Deprecated method is still supposed to work.

    If you see old code that has a @deprecated Javadoc tag, please add the @Deprecated annotation.

    @Override
    The @Override annotation must be used whenever a method overrides the declaration or implementation from a super-class.

    For example, if you use the {@inheritdocs} Javadoc tag, and derive from a class (not an interface), you must also annotate that the method @Overrides the parent class's method.

    @SuppressWarnings
    The @SuppressWarnings annotation should only be used under circumstances where it is impossible to eliminate a warning. If a warning passes this "impossible to eliminate" test, the @SuppressWarnings annotation must be used, so as to ensure that all warnings reflect actual problems in the code.

    When a @SuppressWarnings annotation is necessary, it must be prefixed with a TODO comment that explains the "impossible to eliminate" condition. This will normally identify an offending class that has an awkward interface. For example:

    // TODO: The third-party class com.third.useful.Utility.rotate() needs generics
    @SuppressWarnings({"generic-cast"})
    List<String> blix = Utility.rotate(blax);
    When a @SuppressWarnings annotation is required, the code should be refactored to isolate the software elements where the annotation applies.

    Acronyms in names

    Treat acronyms and abbreviations as words. The names are much more readable:

    Good Bad
    XmlHttpRequest  XMLHTTPRequest
    getCustomerId  getCustomerID

    This style rule also applies when an acronym or abbreviation is the entire name:

    Good Bad
    class Html  class HTML
    String url;  String URL;
    long id;  long ID;

    Both the JDK and the Android code bases are very inconsistent with regards to acronyms, therefore, it is virtually impossible to be consistent with the code around you. Bite the bullet, and treat acronyms as words.

    For further justifications of this style rule, see Effective Java Item 38 and Java Puzzlers Number 68.

    TODO style

    Use TODO comments for code that is temporary, a short-term solution, or good-enough but not perfect.

    TODOs should include the string TODO in all caps, followed by a colon:

      // TODO: Remove this code after the UrlTable2 has been checked in.

    // TODO: Change this to use a flag instead of a constant.

    If your TODO is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2005") or a very specific event ("Remove this code after all production mixers understand protocol V7.").

    Consistency

    Our parting thought: BE CONSISTENT. If you're editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around their if clauses, you should too. If their comments have little boxes of stars around them, make your comments have little boxes of stars around them too.

    The point of having style guidelines is to have a common vocabulary of coding, so people can concentrate on what you're saying, rather than on how you're saying it. We present global style rules here so people know the vocabulary. But local style is also important. If code you add to a a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it. Try to avoid this.

    Logging

    While logging is necessary it has a significantly negative impact on performance and quickly loses its usefulness if it's not kept reasonably terse. The logging facilities provides five different levels of logging. Below are the different levels and when and how they should be used.

    • ERROR: This level of logging should be used when something fatal has happened, i.e. something that will have user-visible consequences and won't be recoverable without explicitly deleting some data, uninstalling applications, wiping the data partitions or reflashing the entire phone (or worse). This level is always logged. Issues that justify some logging at the ERROR level are typically good candidates to be reported to a statistics-gathering server.
    • WARNING: This level of logging should used when something serious and unexpected happened, i.e. something that will have user-visible consequences but is likely to be recoverable without data loss by performing some explicit action, ranging from waiting or restarting an app all the way to re-downloading a new version of an application or rebooting the device. This level is always logged. Issues that justify some logging at the WARNING level might also be considered for reporting to a statistics-gathering server.
    • INFORMATIVE: This level of logging should used be to note that something interesting to most people happened, i.e. when a situation is detected that is likely to have widespread impact, though isn't necessarily an error. Such a condition should only be logged by a module that reasonably believes that it is the most authoritative in that domain (to avoid duplicate logging by non-authoritative components). This level is always logged.
    • DEBUG: This level of logging should be used to further note what is happening on the device that could be relevant to investigate and debug unexpected behaviors. You should log only what is needed to gather enough information about what is going on about your component. If your debug logs are dominating the log then you probably should be using verbose logging. This level will be logged, even on release builds, and is required to be surrounded by an if (LOCAL_LOG) or if (LOCAL_LOGD) block, where LOCAL_LOG[D] is defined in your class or subcomponent, so that there can exist a possibility to disable all such logging. There must therefore be no active logic in an if (LOCAL_LOG) block. All the string building for the log also needs to be placed inside the if (LOCAL_LOG) block. The logging call should not be re-factored out into a method call if it is going to cause the string building to take place outside of the if (LOCAL_LOG) block. There is some code that still says if (localLOGV). This is considered acceptable as well, although the name is nonstandard.
    • VERBOSE: This level of logging should be used for everything else. This level will only be logged on debug builds and should be surrounded by if (LOCAL_LOGV) block (or equivalent) so that it can be compiled out by default. Any string building will be stripped out of release builds and needs to appear inside the if (LOCAL_LOGV) block.

    Note: Within a given module, other than at the VERBOSE level, an error should only be reported once if possible: within a single chain of function calls within a module, only the innermost function should return the error, and callers in the same module should only add some logging if that significantly helps to isolate the issue.

    Note: In a chain of modules, other than at the VERBOSE level, when a lower-level module detects invalid data coming from a higher-level module, the lower-level module should only log this situation to the DEBUG log, and only if logging provides information that is not otherwise available to the caller. Specifically, there is no need to log situations where an exception is thrown (the exception should contain all the relevant information), or where the only information being logged is contained in an error code. This is especially important in the interaction between the framework and applications, and conditions caused by third-party applications that are properly handled by the framework should not trigger logging higher than the DEBUG level. The only situations that should trigger logging at the INFORMATIVE level or higher is when a module or application detects an error at its own level or coming from a lower level.

    Note: When a condition that would normally justify some logging is likely to occur many times, it can be a good idea to implement some rate-limiting mechanism to prevent overflowing the logs with many duplicate copies of the same (or very similar) information.

    Note: Losses of network connectivity are considered common and fully expected and should not be logged gratuitously. A loss of network connectivity that has consequences within an app should be logged at the DEBUG or VERBOSE level (depending on whether the consequences are serious enough and unexpected enough to be logged in a release build).

    Note: A full filesystem on a filesystem that is acceessible to or on behalf of third-party applications should not be logged at a level higher than INFORMATIVE.

    Note: Invalid data coming from any untrusted source (including any file on shared storage, or data coming through just about any network connections) is considered expected and should not trigger any logging at a level higher then DEBUG when it's detected to be invalid (and even then logging should be as limited as possible).

    Note: Keep in mind that the '+' operator, when used on Strings, implicitly creates a StringBuilder with the default buffer size (16 characters) and potentially quite a few other temporary String objects, i.e. that explicitly creating StringBuilders isn't more expensive than relying on the default '+' operator (and can be a lot more efficient in fact). Also keep in mind that code that calls Log.v() is compiled and executed on release builds, including building the strings, even if the logs aren't being read.

    Note: Any logging that is meant to be read by other people and to be available in release builds should be terse without being cryptic, and should be reasonably understandable. This includes all logging up to the DEBUG level.

    Note: When possible, logging should be kept on a single line if it makes sense. Line lengths up to 80 or 100 characters are perfectly acceptable, while lengths longer than about 130 or 160 characters (including the length of the tag) should be avoided if possible.

    Note: Logging that reports successes should never be used at levels higher than VERBOSE.

    Note: Temporary logging that is used to diagnose an issue that's hard to reproduce should be kept at the DEBUG or VERBOSE level, and should be enclosed by if blocks that allow to disable it entirely at compile-time.

    Note: Be careful about security leaks through the log. Private information should be avoided. Information about protected content must definitely be avoided. This is especially important when writing framework code as it's not easy to know in advance what will and will not be private information or protected content.

    Note: System.out.println() (or printf() for native code) should never be used. System.out and System.err get redirected to /dev/null, so your print statements will have no visible effects. However, all the string building that happens for these calls still gets executed.

    Note: The golden rule of logging is that your logs may not unnecessarily push other logs out of the buffer, just as others may not push out yours.

    Javatests Style Rules

    Naming test methods

    When naming test methods, you can use an underscore to seperate what is being tested from the specific case being tested. This style makes it easier to see exactly what cases are being tested.

    Example:

        testMethod_specificCase1 
    testMethod_specificCase2
    void testIsDistinguishable_protanopia() {
    ColorMatcher colorMatcher = new ColorMatcher(PROTANOPIA)
    assertFalse(colorMatcher.isDistinguishable(Color.RED, Color.BLACK))
    assertTrue(colorMatcher.isDistinguishable(Color.X, Color.Y))
    }
  •  
      

    표준 Java 코드 스타일

    Posted by epicdev Archive : 2011. 9. 21. 04:48
    코딩할때 지키도록 노력하자

    http://java.sun.com/docs/codeconv/CodeConventions.pdf

    'Archive' 카테고리의 다른 글

    블록킹 소켓 vs 논 블록킹 소켓  (0) 2011.09.21
    구글 안드로이드 코드 스타일  (0) 2011.09.21
    Static 메소드에서 Synchronized 사용하는 방법  (0) 2011.09.21
    HashMap 과 Hashtable의 차이  (0) 2011.09.21
    Fail-Fast란?  (0) 2011.09.21
      

    Static 메소드에서 Synchronized 사용하는 방법

    Posted by epicdev Archive : 2011. 9. 21. 04:35
    class Foo {
      public static synchronized void bar() {
          // Foo.class의 monitor를 사용한다
      }
    
      public static void bar2() {
          synchronized(Foo.class) {
              // Foo.class의 monitor를 사용한다
          }
    }
    

    'Archive' 카테고리의 다른 글

    구글 안드로이드 코드 스타일  (0) 2011.09.21
    표준 Java 코드 스타일  (0) 2011.09.21
    HashMap 과 Hashtable의 차이  (0) 2011.09.21
    Fail-Fast란?  (0) 2011.09.21
    안드로이드에서의 Multithreading 예제  (0) 2011.09.21
      

    HashMap 과 Hashtable의 차이

    Posted by epicdev Archive : 2011. 9. 21. 03:06
    출처: http://stackoverflow.com/questions/40471/java-hashmap-vs-hashtable

     There are several differences between HashMap and Hashtable in Java:
    1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
    2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
    3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

    'Archive' 카테고리의 다른 글

    표준 Java 코드 스타일  (0) 2011.09.21
    Static 메소드에서 Synchronized 사용하는 방법  (0) 2011.09.21
    Fail-Fast란?  (0) 2011.09.21
    안드로이드에서의 Multithreading 예제  (0) 2011.09.21
    Java Heap에 대한 10가지 사항  (0) 2011.09.20
      

    Fail-Fast란?

    Posted by epicdev Archive : 2011. 9. 21. 03:00
    출처: http://cafe.naver.com/ccjmaster/354

    자바 2 이전 버전에서 사용되던 Vector, Hashtable의 뷰 객체인 Enumeration은 fail-fast 방식이 아니었으나, 자바 2의 콜렉션 프레임워크에서 콜렉션 뷰인 Iterator, ListIterator 객체는 fail-fast 방식이라는 점이다.

    콜렉션 뷰는 콜렉션 객체에 저장된 객체들에 대한 순차적 접근을 제공한다. 그러나, 뷰 객체인 Enumeration 또는 Iterator 객체를 얻고 나서 순차적 접근이 끝나기 전에 뷰 객체를 얻은 하부 콜렉션 객체에 변경이 일어날 경우, 순차적 접근에 실패하게 된다. 여기서 변경이라는 것은 콜렉션에 객체가 추가되거나 제거되는 것과 같이 콜렉션 구조의 변경이 일어나는 경우를 말한다.

    이런 상황은 멀티쓰레드 구조와 이벤트 구동 모델에서 일어날 수 있으며, 개발자가 혼자 테스트할 경우 발견하기 어려운 문제이다. 따라서 정확한 이해와 예상이 필요하며, 이에 대한 대처 방안을 마련해야 한다.

    하부 콜렉션 객체에 변경이 일어나 순차적 접근에 실패하면 Enumeration 객체는 실패를 무시하고 순차적 접근을 끝까지 제공한다. Iterator 객체는 하부 콜렉션 객체에 변경이 일어나 순차적 접근에 실패하면 ConcurrentModificationException 예외를 발생한다. 이처럼 순차적 접근에 실패하면 예외를 발생하도록 되어 있는 방식을 fail-fast라고 한다.

    Iterator는 fail-fast 방식으로 하부 콜렉션에 변경이 발생했을 경우, 신속하고 결함이 없는 상태를 만들기 위해 Iterator의 탐색을 실패한 것으로 하여 예외를 발생하며, 이렇게 함으로써 안전하지 않을지도 모르는 행위를 수행하는 위험을 막는다. 왜냐하면 이러한 위험은 실행 중 불특정한 시간에 멋대로 결정되지 않은 행위를 할 가능성이 있기 때문에 안전하지 않다고 할 수 있기 때문이다.


    아래는 Wikipedia
     

    Fail-fast

    From Wikipedia, the free encyclopedia
     
    Fail-fast is a property of a system or module with respect to its response to failures. A fail-fast system is designed to immediately report at its interface any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system's state at several points in an operation, so any failures can be detected early. A fail-fast module passes the responsibility for handling errors, but not detecting them, to the next-higher system design level.

    Fail-fast systems or modules are desirable in several circumstances:

    • When building a fault-tolerant system by means of redundant components, the individual components should be fail-fast to give the system enough information to successfully tolerate a failure.
    • Fail-fast components are often used in situations where failure in one component might not be visible until it leads to failure in another component.
    • Finding the cause of a failure is easier in a fail-fast system, because the system reports the failure with as much information as possible as close to the time of failure as possible. In a fault-tolerant system, the failure might go undetected, whereas in a system that is neither fault-tolerant nor fail-fast the failure might be temporarily hidden until it causes some seemingly unrelated problem later.
    • A fail-fast system that is designed to halt as well as report the error on failure is less likely to erroneously perform an irreversible or costly operation.

    From the field of software engineering, a Fail Fast Iterator is an iterator that attempts to raise an error if the sequence of elements processed by the iterator is changed during iteration.

     

      

    안드로이드에서의 Multithreading 예제

    Posted by epicdev Archive : 2011. 9. 21. 02:37
    출처: http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
    번역글: http://nom3203.egloos.com/2675253

    Multithreading For Performance

    [This post is by Gilles Debunne, an engineer in the Android group who loves to get multitasked. — Tim Bray]

    A good practice in creating responsive applications is to make sure your main UI thread does the minimum amount of work. Any potentially long task that may hang your application should be handled in a different thread. Typical examples of such tasks are network operations, which involve unpredictable delays. Users will tolerate some pauses, especially if you provide feedback that something is in progress, but a frozen application gives them no clue.

    In this article, we will create a simple image downloader that illustrates this pattern. We will populate a ListView with thumbnail images downloaded from the internet. Creating an asynchronous task that downloads in the background will keep our application fast.

    An Image downloader

    Downloading an image from the web is fairly simple, using the HTTP-related classes provided by the framework. Here is a possible implementation:

    static Bitmap downloadBitmap(String url) {
       
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
       
    final HttpGet getRequest = new HttpGet(url);

       
    try {
           
    HttpResponse response = client.execute(getRequest);
           
    final int statusCode = response.getStatusLine().getStatusCode();
           
    if (statusCode != HttpStatus.SC_OK) {
               
    Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
               
    return null;
           
    }
           
           
    final HttpEntity entity = response.getEntity();
           
    if (entity != null) {
               
    InputStream inputStream = null;
               
    try {
                    inputStream
    = entity.getContent();
                   
    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                   
    return bitmap;
               
    } finally {
                   
    if (inputStream != null) {
                        inputStream
    .close();  
                   
    }
                    entity
    .consumeContent();
               
    }
           
    }
       
    } catch (Exception e) {
           
    // Could provide a more explicit error message for IOException or IllegalStateException
            getRequest
    .abort();
           
    Log.w("ImageDownloader", "Error while retrieving bitmap from " + url, e.toString());
       
    } finally {
           
    if (client != null) {
                client
    .close();
           
    }
       
    }
       
    return null;
    }

    A client and an HTTP request are created. If the request succeeds, the response entity stream containing the image is decoded to create the resulting Bitmap. Your applications' manifest must ask for the INTERNET to make this possible.

    Note: a bug in the previous versions of BitmapFactory.decodeStream may prevent this code from working over a slow connection. Decode a newFlushedInputStream(inputStream) instead to fix the problem. Here is the implementation of this helper class:

    static class FlushedInputStream extends FilterInputStream {
       
    public FlushedInputStream(InputStream inputStream) {
           
    super(inputStream);
       
    }

       
    @Override
       
    public long skip(long n) throws IOException {
           
    long totalBytesSkipped = 0L;
           
    while (totalBytesSkipped < n) {
               
    long bytesSkipped = in.skip(n - totalBytesSkipped);
               
    if (bytesSkipped == 0L) {
                     
    int byte = read();
                     
    if (byte < 0) {
                         
    break;  // we reached EOF
                     
    } else {
                          bytesSkipped
    = 1; // we read one byte
                     
    }
               
    }
                totalBytesSkipped
    += bytesSkipped;
           
    }
           
    return totalBytesSkipped;
       
    }
    }

    This ensures that skip() actually skips the provided number of bytes, unless we reach the end of file.

    If you were to directly use this method in your ListAdapter's getView method, the resulting scrolling would be unpleasantly jaggy. Each display of a new view has to wait for an image download, which prevents smooth scrolling.

    Indeed, this is such a bad idea that the AndroidHttpClient does not allow itself to be started from the main thread. The above code will display "This thread forbids HTTP requests" error messages instead. Use the DefaultHttpClient instead if you really want to shoot yourself in the foot.

    Introducing asynchronous tasks

    The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. Let's create an ImageDownloader class which will be in charge of creating these tasks. It will provide a download method which will assign an image downloaded from its URL to an ImageView:

    public class ImageDownloader {

       
    public void download(String url, ImageView imageView) {
               
    BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
                task
    .execute(url);
           
    }
       
    }

       
    /* class BitmapDownloaderTask, see below */
    }

    The BitmapDownloaderTask is the AsyncTask which will actually download the image. It is started using execute, which returns immediately hence making this method really fast which is the whole purpose since it will be called from the UI thread. Here is the implementation of this class:

    class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
       
    private String url;
       
    private final WeakReference<ImageView> imageViewReference;

       
    public BitmapDownloaderTask(ImageView imageView) {
            imageViewReference
    = new WeakReference<ImageView>(imageView);
       
    }

       
    @Override
       
    // Actual download method, run in the task thread
       
    protected Bitmap doInBackground(String... params) {
             
    // params comes from the execute() call: params[0] is the url.
             
    return downloadBitmap(params[0]);
       
    }

       
    @Override
       
    // Once the image is downloaded, associates it to the imageView
       
    protected void onPostExecute(Bitmap bitmap) {
           
    if (isCancelled()) {
                bitmap
    = null;
           
    }

           
    if (imageViewReference != null) {
               
    ImageView imageView = imageViewReference.get();
               
    if (imageView != null) {
                    imageView
    .setImageBitmap(bitmap);
               
    }
           
    }
       
    }
    }

    The doInBackground method is the one which is actually run in its own process by the task. It simply uses the downloadBitmap method we implemented at the beginning of this article.

    onPostExecute is run in the calling UI thread when the task is finished. It takes the resulting Bitmap as a parameter, which is simply associated with the imageView that was provided to download and was stored in the BitmapDownloaderTask. Note that this ImageView is stored as a WeakReference, so that a download in progress does not prevent a killed activity's ImageView from being garbage collected. This explains why we have to check that both the weak reference and the imageView are not null (i.e. were not collected) before using them in onPostExecute.

    This simplified example illustrates the use on an AsyncTask, and if you try it, you'll see that these few lines of code actually dramatically improved the performance of the ListView which now scrolls smoothly. Read Painless threading for more details on AsyncTasks.

    However, a ListView-specific behavior reveals a problem with our current implementation. Indeed, for memory efficiency reasons, ListView recycles the views that are displayed when the user scrolls. If one flings the list, a given ImageView object will be used many times. Each time it is displayed the ImageView correctly triggers an image download task, which will eventually change its image. So where is the problem? As with most parallel applications, the key issue is in the ordering. In our case, there's no guarantee that the download tasks will finish in the order in which they were started. The result is that the image finally displayed in the list may come from a previous item, which simply happened to have taken longer to download. This is not an issue if the images you download are bound once and for all to given ImageViews, but let's fix it for the common case where they are used in a list.

    Handling concurrency

    To solve this issue, we should remember the order of the downloads, so that the last started one is the one that will effectively be displayed. It is indeed sufficient for each ImageView to remember its last download. We will add this extra information in the ImageView using a dedicated Drawable subclass, which will be temporarily bind to the ImageView while the download is in progress. Here is the code of our DownloadedDrawable class:

    static class DownloadedDrawable extends ColorDrawable {
       
    private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;

       
    public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
           
    super(Color.BLACK);
            bitmapDownloaderTaskReference
    =
               
    new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);
       
    }

       
    public BitmapDownloaderTask getBitmapDownloaderTask() {
           
    return bitmapDownloaderTaskReference.get();
       
    }
    }

    This implementation is backed by a ColorDrawable, which will result in the ImageView displaying a black background while its download is in progress. One could use a “download in progress” image instead, which would provide feedback to the user. Once again, note the use of a WeakReference to limit object dependencies.

    Let's change our code to take this new class into account. First, the download method will now create an instance of this class and associate it with the imageView:

    public void download(String url, ImageView imageView) {
         
    if (cancelPotentialDownload(url, imageView)) {
             
    BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
             
    DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
             imageView
    .setImageDrawable(downloadedDrawable);
             task
    .execute(url, cookie);
         
    }
    }

    The cancelPotentialDownload method will stop the possible download in progress on this imageView since a new one is about to start. Note that this is not sufficient to guarantee that the newest download is always displayed, since the task may be finished, waiting in its onPostExecute method, which may still may be executed after the one of this new download.

    private static boolean cancelPotentialDownload(String url, ImageView imageView) {
       
    BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);

       
    if (bitmapDownloaderTask != null) {
           
    String bitmapUrl = bitmapDownloaderTask.url;
           
    if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
                bitmapDownloaderTask
    .cancel(true);
           
    } else {
               
    // The same URL is already being downloaded.
               
    return false;
           
    }
       
    }
       
    return true;
    }

    cancelPotentialDownload uses the cancel method of the AsyncTask class to stop the download in progress. It returns true most of the time, so that the download can be started in download. The only reason we don't want this to happen is when a download is already in progress on the same URL in which case we let it continue. Note that with this implementation, if an ImageView is garbage collected, its associated download is not stopped. ARecyclerListener might be used for that.

    This method uses a helper getBitmapDownloaderTask function, which is pretty straigthforward:

    private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) {
       
    if (imageView != null) {
           
    Drawable drawable = imageView.getDrawable();
           
    if (drawable instanceof DownloadedDrawable) {
               
    DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable;
               
    return downloadedDrawable.getBitmapDownloaderTask();
           
    }
       
    }
       
    return null;
    }

    Finally, onPostExecute has to be modified so that it will bind the Bitmap only if this ImageView is still associated with this download process:

    if (imageViewReference != null) {
       
    ImageView imageView = imageViewReference.get();
       
    BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
       
    // Change bitmap only if this process is still associated with it
       
    if (this == bitmapDownloaderTask) {
            imageView
    .setImageBitmap(bitmap);
       
    }
    }

    With these modifications, our ImageDownloader class provides the basic services we expect from it. Feel free to use it or the asynchronous pattern it illustrates in your applications to ensure their responsiveness.

    Demo

    The source code of this article is available online on Google Code. You can switch between and compare the three different implementations that are described in this article (no asynchronous task, no bitmap to task association and the final correct version). Note that the cache size has been limited to 10 images to better demonstrate the issues.

    Future work

    This code was simplified to focus on its parallel aspects and many useful features are missing from our implementation. The ImageDownloader class would first clearly benefit from a cache, especially if it is used in conjuction with a ListView, which will probably display the same image many times as the user scrolls back and forth. This can easily be implemented using a Least Recently Used cache backed by a LinkedHashMap of URL to BitmapSoftReferences. More involved cache mechanism could also rely on a local disk storage of the image. Thumbnails creation and image resizing could also be added if needed.

    Download errors and time-outs are correctly handled by our implementation, which will return a null Bitmap in these case. One may want to display an error image instead.

    Our HTTP request is pretty simple. One may want to add parameters or cookies to the request as required by certain web sites.

    The AsyncTask class used in this article is a really convenient and easy way to defer some work from the UI thread. You may want to use the Handlerclass to have a finer control on what you do, such as controlling the total number of download threads which are running in parallel in this case. 
      

    Java Heap에 대한 10가지 사항

    Posted by epicdev Archive : 2011. 9. 20. 23:37
    출처: http://javarevisited.blogspot.com/2011/05/java-heap-space-memory-size-jvm.html

    When I startedjava programmingI didn't know what is java heap or what is heap space in Java, I was even not aware of where does object in Java gets created, it’s when I started doing professional programming I came across error java.lang.outofmemoryerror then I realized What is Heap in Java or Java Heap Space. Its happens with most of programmer because learning language is easy but learning basics is difficult since there is no formal process which can teach you every basics of programming its experience and work which reveals the secret of programming. For Java developer knowledge of Heap in Java, setting size of java heap space, dealing with java heap space outofmemoryerror, analyzing heap dumps is very importantThis Java Heap tutorial is for my beginner brothers who are new in programming and learning it. It makes too much difference if you know the basics and underlying, until you know that object is created in heap, you won't be able to think why OutOfMemoryErroroccurs in Heap. I am trying to provide as much information about Heap in Java as I know but would like you guys to contribute and share your knowledge about Heap in Java to benefit all.

    What is Heap space in Java?

    When a Java program started Java Virtual Machine gets some memory from Operating System. Java Virtual Machine or JVM uses this memory for all its need and part of this memory is call java heap memory. Heap in Java generally located at bottom of address space and move upwards. whenever we create object using new operator or by any another means object is allocated memory from Heap and When object dies or garbage collected ,memory goes back to Heap space in Java, to learn more about garbage collection see how garbage collection works in Java.

    How to increase size of Java Heap

    Default size of Heap in Java is 128MB on most of 32 bit Sun's JVM but its highly varies from JVM to JVM  e.g. default maximum and start heap size for the 32-bit Solaris Operating System (SPARC Platform Edition) is -Xms=3670K and -Xmx=64M and Default values of heap size parameters on 64-bit systems have been increased up by approximately 30%. Also if you are using throughput garbage collector in Java 1.5 default maximum heap size of JVM would be Physical Memory/4 and  default initial heap size would be Physical Memory/16. Another way to find default heap size of JVM is to start an application with default heap parameters and monitor in using JConsole which is available on JDK 1.5 onwards, on VMSummary tab you will be able to see maximum heap size.

    By the way you can increase size of java heap space based on your application need and I always recommend this to avoid using default JVM heap values. if your application is large and lots of object created you can change size of heap space by using JVM command lineoptions -Xms and -Xmx. Xms denotes starting size of Heap while Xmx denotes maximum size of Heap in Java. There is another parameter called -Xmn which denotes Size of new generation of Java Heap Space. Only thing is you can not change the size of Heap in Java dynamically, you can only provide Java Heap Size parameter while starting JVM.
     

    Java Heap and Garbage Collection

    As we know objects are created inside heap memory  and Garbage collection is a process which removes dead objects from Java Heap space and returns memory back to Heap in Java. For the sake of Garbage collection Heap is divided into three main regions named as New Generation, Old or Tenured Generation and Perm space. New Generation of Java Heap is part of Java Heap memory where newly created object allocated memory, during the course of application object created and died but those remain live they got moved to Old or Tenured Generation by Java Garbage collector thread on Major collection. Perm space of Java Heap is where JVM stores Meta data about classes and methods, String pool and Class level details. You can see How Garbage collection works in Java for more information on Heap in Java and Garbage collection.

    OutOfMemoryError in Java Heap

    When JVM starts JVM heap space is the initial size of Heap specified by -Xms parameter, as application progress objects creates and JVM expands Heap space in Java to accommodate new objects. JVM also run garbage collector to reclaim memory back from dead objects. JVM expands Heap in Java some where near to Maximum Heap Size specified by -Xmx and if there is no more memory left for creating new object in java heap , JVM throws  java.lang.outofmemoryerror and  your application dies. Before throwing OutOfMemoryError No Space in Java Heap, JVM tries to run garbage collector to free any available space but even after that not much space available on Heap in Java it results into OutOfMemoryError. To resolve this error you need to understand your application object profile i.e. what kind of object you are creating, which objects are taking how much memory etc. you can use profiler or heap analyzer to troubleshoot OutOfMemoryError in Java. "java.lang.OutOfMemoryError: Java heap space" error messages denotes that Java heap does not have sufficient space and cannot be expanded further while "java.lang.OutOfMemoryError: PermGen space" error message comes when the permanent generation of Java Heap is full, the application will fail to load a class or to allocate an interned string.

    Java Heap dump

    Java Heap dump is a snapshot of Java Heap Memory at a particular time. This is very useful to analyze or troubleshoot any memory leak in Java or any Java.lang.outofmemoryerror. There is tools available inside JDK which helps you to take heap dump and there are heap analyzer available tool which helps you to analyze java heap dump. You can use "jmap" command to get java heap dump, this will create heap dump file and then you can use "jhat - Java Heap Analysis Tool" to analyze those heap dumps.

    10 Points about Java Heap Space

    1. Java Heap Memory is part of Memory allocated to JVM by Operating System.

    2. Whenever we create objects they are created inside Heap in Java.

    3. Java Heap space is divided into three regions or generation for sake of garbage collection called New Generation, Old or tenured Generation or Perm Space.

    4. You can increase or change size of Java Heap space by using JVM command line option -Xms, -Xmx and -Xmn. don't forget to add word "M" or "G" after specifying size to indicate Mega or Giga. for example you can set java heap size to 258MB by executing following command java -Xmx256m HelloWord.

    5. You can use either JConsole or Runtime.maxMemory(), Runtime.totalMemory(), Runtime.freeMemory() to query about Heap size programmatic in Java.

    6. You can use command "jmap" to take Heap dump in Java and"jhat" to analyze that heap dump.

    7. Java Heap space is different than Stack which is used to store call hierarchy and local variables.

    8. Java Garbage collector is responsible for reclaiming memory from dead object and returning to Java Heap space.

    9. Don’t panic when you get java.lang.outofmemoryerror, sometimes its just matter of increasing heap size but if it’s recurrent then look for memory leak in Java.

    10. Use Profiler and Heap dump Analyzer tool to understand Java Heap space and how much memory is allocated to each object.

    This article is in continuation of my previous articles How Classpath works in Java , How to write Equals method in java , How HashMap works in Java  and difference between HashMap and Hashtable in Java and How Synchronization works in Java if you haven’t read already you may find some useful information based on my experience in Java .




    How to increase Java heap space on Maven and ANT

    Many times we need to increase heap size of Maven or ANT because once number of classes increases build tool requires more memory to process and build and often throw OutOfMemoryError which we can avoid by changing or increase heap memory of JVM. For details see my post How to increase java heap memory for Ant or Maven
      

    출처: http://googlekoreablog.blogspot.com/2008/04/robotstxt.html

    robots.txt를 현명하게 사용하는 방법

    Search Quality팀 석인혁, Chao Ma


    검색엔진
     자신의 사이트를 많은 사람에게 알릴 수 있는 가장 좋은 방법 중 하나입니다이를 활용하기에 앞서 고려해야 할 것은 여러분들의 사이트에 있는 정보를 얼마 만큼 외부에 제공할 것인가를 설정하는 일입니다. 

    만약 여러분의 사이트에 검색엔진을 통해 색인이 생성되지 않도록 하려는 콘텐츠가 있다면,robots.txt 파일을 사용하여 웹을 색인하는 검색엔진 로봇(이하 "검색봇")을 차단하거나 필요한 부분만을 검색엔진에 나타나게 할 수 있습니다. 검색봇은 자동으로 작동하며한 사이트의 하위 페이지에 접근하기 전에 먼저 특정 페이지에 대한 접근을 차단하는 robots.txt 파일이 있는지 여부를 확인합니다. 이번 기회를 통하여 여러분들에게 올바르게 robots.txt를 사용하는 방법을 제공하고자 합니다.

    robots.txt 의 배치

    robots.txt는 HTML 파일이 아닌 일반 텍스트 파일로 도메인의 root에 있어야 하며 반드시 'robots.txt'로 저장되야 합니다. 검색봇은 도메인의 root에 있는 robots.txt 파일만을 체크하기 때문에 하위 디렉토리에 있는 파일은 유효하지 않습니다.

    예를 들어 http://www.example.com/robots.txt는 유효한 위치이지만,http://www.example.com/mysite/robots.txt는 유효하지 않습니다.

    robots.txt 사용 예제:
    User-agent: *
    Disallow: /cgi-bin/
    Disallow: /tmp/

    Disallow: /~name/

    robots.txt 파일을 사용하여 전체 웹사이트를 허용/차단하기 


    전체 웹사아트를 검색엔진이 색인하도록 허용하고자 할 때에는 다음과 같이 robots.txt 
    일을 추가합니다.
    User-agent: *
    Disallow:

    또 다른 해결 방법으로는 단순하게 robots.txt를 사이트로부터 제거 하는 것입니다.

    검색엔진에서 사이트를 삭제하고 향후 어떤 검색봇도 접근하지 못하게 하려면 robots.txt 파일에 다음 내용을 추가합니다. 
    User-agent: *
    Disallow: /

    주의) 이 경우 검색봇이 차단되어 사이트가 더이상 검색엔진에 나타나지 않게 됨으로 검색엔진을 통 들어오게 되는 사용자들에게 불이익을 제공하게 됩니다.

    각 포트에는 전용 robots.txt 파일이 있어야 합니다. 특히 http와 https 모두를 통해 사용자들에콘텐츠를 제공하려면 이 두 가지 프로토콜에 대해 각각의 robots.txt 파일이 있어야 합니다.

    예를 들어 검색봇을 통해 https 페이지를 제외한 모든 http 페이지에 대한 수집을 허용하려면 다음 robots.txt 파일들을 각의 프로토콜에 사용해야 합니다.

    http 프로토콜의 경우
    (http://yourserver.co.kr/robots.txt): 
    User-agent: *
    DIsallow:

    https 프로토콜의 경우
    (https://yourserver.co.kr/robots.txt): 

    User-agent: *
    Disallow: /

    robots.txt 파일을 사용하여 페이지 차단하기

    예를 들어검색봇이 특정 디렉토리(: board )의 모든 페이지를 검색하지 않도록 차단하려면 다음과 같이 robots.txt를 사용 하시면 됩니다.
    User-agent: *
    Disall
    ow: /board/

    Googlebot이 특정 형식(: .gif)의 파일을 모두 검색하지 않도록 차단하려면 다음과 같이robots.txt를 사용 하시면 됩니다.
    User-Agent: Googlebot
    Disallow: /*.gif$

    Googlebot이 ?가 포함된 URL 즉, 도메인 이름으로 시작되거나 임의의 문자열 또는 물음표로 구성된URL 검색을 차단하려면 다음과 같이 하시면 됩니다. 
    User-agent: Googlebot
    Disallow: /*?

    구글은 웹마스터 도구의 일원으로 robots.txt 분석 도구를 사용자들에게 제공하고 있습니다. robots.txt 분석도구는 여러분의 robots.txt 화일을 검색봇이 읽는 그대로 인식하여 그 결과를 여러분들께 제공하고 있습니다. robots.txt의 올바른 사용으로 사이트 방문자에게 보다 쉬운 접근 방법을 제공하는 동시에 필요한 부분을 보호, 차단할 수 있기 바랍니다.

      

    Avoiding Memory Leaks

    Android applications are, at least on the T-Mobile G1, limited to 16 MB of heap. It's both a lot of memory for a phone and yet very little for what some developers want to achieve. Even if you do not plan on using all of this memory, you should use as little as possible to let other applications run without getting them killed. The more applications Android can keep in memory, the faster it will be for the user to switch between his apps. As part of my job, I ran into memory leaks issues in Android applications and they are most of the time due to the same mistake: keeping a long-lived reference to a Context.

    On Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of ContextActivity and Application. It's usually the first one that the developer passes to classes and methods that need a Context:

    @Override
    protected void onCreate(Bundle state) {
     
    super.onCreate(state);
     
     
    TextView label = new TextView(this);
      label
    .setText("Leaks are bad");
     
      setContentView
    (label);
    }

    This means that views have a reference to the entire activity and therefore to anything your activity is holding onto; usually the entire View hierarchy and all its resources. Therefore, if you leak the Context ("leak" meaning you keep a reference to it thus preventing the GC from collecting it), you leak a lot of memory. Leaking an entire activity can be really easy if you're not careful.

    When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application's UI from the resources. Now imagine you wrote an application with a large bitmap that you don't want to load on every rotation. The easiest way to keep it around and not having to reload it on every rotation is to keep in a static field:

    private static Drawable sBackground;
     
    @Override
    protected void onCreate(Bundle state) {
     
    super.onCreate(state);
     
     
    TextView label = new TextView(this);
      label
    .setText("Leaks are bad");
     
     
    if (sBackground == null) {
        sBackground
    = getDrawable(R.drawable.large_bitmap);
     
    }
      label
    .setBackgroundDrawable(sBackground);
     
      setContentView
    (label);
    }

    This code is very fast and also very wrong; it leaks the first activity created upon the first screen orientation change. When a Drawable is attached to a view, the view is set as a callback on the drawable. In the code snippet above, this means the drawable has a reference to theTextView which itself has a reference to the activity (the Context) which in turns has references to pretty much anything (depending on your code.)

    This example is one of the simplest cases of leaking the Context and you can see how we worked around it in the Home screen's source code (look for the unbindDrawables() method) by setting the stored drawables' callbacks to null when the activity is destroyed. Interestingly enough, there are cases where you can create a chain of leaked contexts, and they are bad. They make you run out of memory rather quickly.

    There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().

    In summary, to avoid context-related memory leaks, remember the following:

    • Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
    • Try using the context-application instead of a context-activity
    • Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
    • A garbage collector is not an insurance against memory leaks

      출처:  http://developer.android.com/resources/articles/avoiding-memory-leaks.html
      

    Java의 9가지 네이밍 관습들

    Posted by epicdev Archive : 2011. 9. 8. 23:49

    9 - Naming Conventions

    Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.


    Identifier Type


    Rules for Naming


    Examples


    Packages


    The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

    Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.

    com.sun.eng

    com.apple.quicktime.v2

    edu.cmu.cs.bovik.cheese


    Classes


    Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).


    class Raster; 
    class ImageSprite;


    Interfaces


    Interface names should be capitalized like class names.


    interface RasterDelegate; 
    interface Storing;


    Methods


    Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.


    run(); 
    runFast(); 
    getBackground();


    Variables


    Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.

    Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are ijkm, and n for integers; cd, and e for characters.


    int             i;
    char            c;
    float           myWidth;
    



    Constants


    The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)


    static final int MIN_WIDTH = 4;

    static final int MAX_WIDTH = 999;

    static final int GET_THE_CPU = 1;



    출처: 
    http://www.oracle.com/technetwork/java/codeconventions-135099.html
      
     «이전 1 ··· 12 13 14 15 16 17  다음»