Slightly unfamiliar keywords in Java

Source: Internet
Author: User

1, instance of

In Java, instance of is used to indicate whether an object is an instance of a particular class, and if it is to return a bool type, to indicate whether the object is an instance of a particular class or its subclasses

Resutl = Object instance of class

Interface A{}class B implements A{}class C extends B{}public class Instanceoftest {public static void main (string[] args) {//TODO auto-generated method Stuba a = null; b b = Null;boolean result; System.out.println ("Instanceoftest test Case 1:------------------"); result = a instanceof A;  System.out.println ("A instanceof A:" +result); result = b instanceof B;  System.out.println ("b instanceof B:" +result);  System.out.println ("/ninstanceoftest test Case 2:------------------"); A = new B ();  b = new B (); result = a instanceof A; System.out.println ("A instanceof A:" +result); result = a instanceof B;  System.out.println ("A instanceof B:" +result); result = b instanceof A; System.out.println ("b instanceof A:" +result); result = b instanceof B;   System.out.println ("b instanceof B:" +result);  System.out.println ("/ninstanceoftest test Case 3:------------------");  A b2 = new C ();  result = B2 instanceof A;  System.out.println ("B2 instanceof A:" +result);  result = B2 instanceof B; SystEm.out.println ("B2 instanceof B:" +result);  result = B2 instanceof C; System.out.println ("B2 instanceof C:" +result);}}

2, transient

What does the Q:transient keyword accomplish?

A: When the object is serialized (when the byte sequence is written to the target file), transient blocks those variables declared with this keyword persisted in the instance;

When an object is deserialized (a sequence of bytes is read from the source file), such an instance variable is not persisted and replied to. For example, when anti-

A serialized object----data stream (for example, a file) may not exist because a variable of type Java.io.InputStream exists in your object

, the input stream referenced by these variables cannot be opened when serializing.

Anyway, when you don't need a variable to be serialized, set the variable to the transient variable

3, native

The Java native method refers to a local method that is declared as the native method when calling code in a method that is not written by the Java language, or when invoking the Java language in a method directly manipulates computer hardware.

In Java, localization via JNI (Java Native Interface, Java local interface)

The native method is generally used in two situations:

1) invoke some code in the method that is not written by the Java language

2) Manipulate computer hardware directly in the Java language in the method

The writing procedure for JNI:

A. Java class for writing methods with native declarations

B. Java classes compiled with the Javac command

C. Use JAVA-JNI * * * to generate a header file with the suffix. h

D. Implementing local methods using other languages (c, C + +)

E. Generate a dynamic-link library of files written by local methods

4, synchronized

Q: Why use the Synchronized keyword

A: First look at an example

Package Com.lost.syn;import Java.awt.geom.flatteningpathiterator;class account{string name;float amount;public Account (String name, float amount) {this.name = Name;this.amount = Amount;} public void deposit (float amt) {float TMP = amount;tmp + = amt;try {System.out.println ("Deposit 100"); Thread.Sleep (100);} catch (Exception e) {//Todo:handle exception}this.amount = tmp;} public void Withdraw (float amt) {float TMP = this.amount;tmp-= amt;try {System.out.println ("Remove 100"); Thread.Sleep (100);} catch (Exception e) {//Todo:handle exception}this.amount = tmp;} public float GetBalance () {return this.amount;}} public class Syndemo {public static int num_of_thread = 5000;static thread[] threads = new Thread[num_of_thread];p Ublic St atic void Main (String args[]) {Final account cc =new account ("John", 1000.0f); for (int i=0;i<num_of_thread; i++) { Threads[i] = new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubcc.deposit (100.0f); c C.withdraw (100.0f);}}); Threads[i].start ();} For (int i=0; i<num_of_thread; i++) {try {threads[i].join ();} catch (Exception e) {//Todo:handle exception}}system.out. println ("Finally John ' s Balance is" +cc.getbalance ());}}

  

Finally John ' s Balance is 1200.0

Finally John ' s Balance is 1400.0

Line Cheng and line Cheng at the same time the initial balance is 1000

Thread A saving line Cheng also save money at the same time the base is 1000 after the base program 1100 instead of 1200 at this time if the same time to withdraw money and then become 1000 if not at the same time to get the words will become 900

Each time the result is not necessarily the same, because there are many threads at the same time access. If you get 1000 each time you run, congratulations, your computer configuration is relatively high, so you can turn the number of threads slightly larger.

This is the problem of synchronization in multiple threads, in our program, the account is accessed by multiple threads at the same time, which is a competing resource, often called a race condition. For such multiple threads to share resources we have to synchronize to avoid the change of one thread being overwritten by another thread. In our program, the amount in account is a race condition, so all modifications to amount are synchronized, and we synchronize the deposit and withdraw methods

Public synchronized void deposit (float amt) {float TMP = amount;tmp + = amt;try {System.out.println ("Deposit 100"); Thread.Sleep (100);} catch (Exception e) {//Todo:handle exception}this.amount = tmp;} Public synchronized void Withdraw (float amt) {float TMP = this.amount;tmp-= amt;try {System.out.println ("Remove 100"); Thread.Sleep (100);} catch (Exception e) {//Todo:handle exception}this.amount = tmp;}

Synchronizing locks are objects instead of code snippets

If you have a synchronization method in your class, this method can be executed by two different threads at the same time, as long as each thread creates an instance of the class itself.

Class Foo extends Thread{private int val;public Foo (int v) {val = v;} Public synchronized void Printval (int v) {while (true) {System.out.println (v);}} public void Run () {Printval (val);}}

Synchronization of Classes

To achieve a true section, you must synchronize a global object or synchronize the class.

Class Foo extends Thread{private string name;private string val;//private static Object lock = new Object ();p ublic Foo (Str ing name, String v) {this.name = Name;this.val = v;} Public  void Printval () {synchronized (Foo.class) {while (true) {System.out.println (name+val);}}} public void Run () {printval ();}}

  

For String types The following example has a JVM optimization mechanism "" saves only one copy in memory unless the object is re-created with new string

Class Foo extends Thread{private string name;private string val;//private static Object lock = new Object ();p ublic Foo (Str ing name, String v) {this.name = Name;this.val = v;} Public  void Printval () {synchronized (val) {while (true) {System.out.println (name+val);}}} public void Run () {printval ();}}

  

String value = "Printval" in the Main method; Foo f1 = new Foo ("Foo 1:", New String ("Foo 1"); F1.start (); Foo F2 = new foo ("Foo 2:", New String ("Foo 2"); F2.start (); Foo f1 = new Foo ("Foo 1:", value); F1.start (); Foo F2 = new foo ("Foo 2:", value); F2.start ();

The above two types of use in main are not the same

Summary:

There are two scopes of synchronized keywords:

1, is within an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the object's synchronized method at the same time (if an object has multiple synchronized methods, As long as one thread accesses one of the synchronized methods, the other thread cannot access any of the synchronized methods in the object at the same time. At this point, the different synchronized methods of the thrown instances are not interfering. That is, other threads can still access the Synchronized method in another object instance of the same class at the same time.

2, in addition to using the Synchronized keyword before the method, the Synchronized keyword can also be used in a chunk of the method, indicating that only the resources of this block are mutually exclusive access. The usage is: synchronized (this) {/* block */}, which is scoped to the current object;

3, synchronized keyword is not inherited, that is, the method of the base class synchronized F () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. Inheriting a class requires that you display a method that specifies it as the synchronized method.

The Java language keyword that, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time.

First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) block of code in the object.

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to many other synchronized synchronous blocks of code in object.

The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized synchronous block of code for object, it obtains the object lock for that object. As a result, the other threads ' access to all the synchronized code portions of the object is temporarily set

The above rules apply to other object locks as well.

(You cannot define global variables outside of a class in Java, you can only implement a global variable by defining a common, static variable in a class)

The Synchronized method Controls access to class member variables: Each class instance corresponds to a lock, and each synchronized method must obtain a lock on the class instance that invokes the method to execute, otherwise the owning thread is blocked, and once the method executes, the lock is exclusive until the lock is released from the method return , serving the blocked thread to obtain the lock and re-enter the executable state. This mechanism ensures that at the same time for each class instance, at most one of its member functions declared as synchronized is in an executable state (since at most one can obtain the corresponding lock for that class instance), This effectively avoids access violations of class member variables (as long as all methods that may access the class member variable are declared as synchronized). (The first time you add synchronized)

In Java, not only class instances, each class also corresponds to a lock, so that we can declare the class's member functions as synchronized to control its access to static member variables of the class.

The flaw of the Synchronized method: Declaring a large method as synchronized will greatly affect efficiency, typically, if the method run of the thread class is declared as synchronized, because he is running throughout the entire declaration cycle of the threads, As a result, the call to any synchronized method in this class will never succeed. When we can put the code that accesses the class member variable into a specialized method, declare it as synchronized, and use it in the main method to solve the problem, Java provides us with a better solution, that is, the synchronized block.

2, synchronized block: Declare synchronized block by synchronized keyword.

It can be used for arbitrary blocks of code, and can arbitrarily specify locked objects, so the flexibility is higher.

First, when two concurrent threads access the same object in the synchronized synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

Second, however, when a thread accesses one of the synchronized synchronous blocks of object, another thread can still sample the non-synchronized synchronous block of code in that object.

Third, when a thread accesses an synchronized synchronous code block of object, other threads still have access to all other synchronized (this) synchronization blocks of code in that object will be blocked.

5, strictfp (strict float point)

If you want to make your floating-point arithmetic more precise and not inconsistent with the results of different hardware platforms, you can use the keyword STRICTFP

Slightly unfamiliar keywords in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.