Java Core Technology Essentials Summary: Multithreading, Network and database

Source: Internet
Author: User
Tags deprecated prepare rollback savepoint semaphore thread class time limit volatile
Multithreading

A simple procedure for running a task in a separate thread:

1. Define a class that implements the Runnable interface, and the task code is written in the Run method

2. Create an instance of the class

3. Pass this instance to the constructor of the thread class, instantiate a Thread object

4. Opening a thread through the start method of the thread class

Threaded Thread: Threads will terminate when its Run method returns

Although there is no way to force a thread to terminate, a thread can be requested to terminate with the interrupt method; When the interrupt method is invoked on a thread object, the interrupt state bit of the thread is set to true; to find the interrupt state of a thread, You need to first call the static method of the thread class CurrentThread get the object of the current thread, and then call its Isinterrupt method for detection, but if a thread has been blocked, Call interrupt method on it is thrown interruptedexception

The thread requesting the interrupt does not necessarily need to be terminated, and after detecting that the interrupt state bit is set to true, it should be handled according to the actual situation

A better approach to interruptedexception is to throw it at a higher level of code processing, rather than suppressing it at a low-level

Thread state: A thread can have the following 4 states

1. NEW: After the thread object is created by new, the thread enters the "new" state and can perform some bookkeeping work before the thread begins to run

2. Runnable: Once the Start method is invoked, the thread goes into the "run" state, starts executing the code in the Run method, but whether it is actually running depends on the threading schedule of the operating system

3. Blocked: When any of the following occurs, the thread enters a "blocking" state:

1 The thread enters sleep by calling the sleeping method

2 The thread invokes an operation that is blocked on I/O

3 The thread is trying to get a lock that is being held by another thread

4 The thread is waiting for a trigger condition (see synchronized keyword)

5) (deprecated) Suspend method is called

In one of the following ways, a thread can return from a blocking state to an executable state:

1 The sleeping thread has passed the specified sleep time

2 The thread is waiting for the I/O operation has completed

3 Other threads release the lock that this thread is waiting for (or because the timeout thread is automatically unblocked)

4 other threads signal that the trigger condition that this thread is waiting for has changed (or because the timeout thread is automatically unblocked)

5) (deprecated, for suspend) when a thread is suspended, its resume method is invoked

4. Dead: The following conditions will cause the thread to "die":

1 Run method execution end, normal exit

2 because an unhandled exception causes the Run method to terminate

3) (OBSOLETE) Call stop method kill thread

4 Calling the Join method can cause the thread to wait until death

The IsAlive method of the calling thread detects whether the thread is alive: the Run-time and blocking states return true, and the new ecology and death returns false

Thread attributes: Thread Priority: Each thread has a priority, by default, the thread inherits the priority of its parent thread; The SetPriority method can set the thread priority, the minimum is min_priority (1), and the maximum is max_priority (10), The other constants are norm_priority (5); The thread scheduling of the operating system prioritizes the high-priority threads; The static method yield the current thread into a concession state so that the priority of the other threads not below it is scheduled

Daemon thread: Calling T.setdaemon (true) causes thread T to become a daemon; the only function of a daemon is to provide services to other threads; when only the daemon is left, the program terminates

Thread groups: Thread groups allow simultaneous manipulation of a set of threads

The string parameter in the constructor of the Threadgroup class is used to identify the group, must be unique, and the thread group is specified for it to be added to the thread group when a new thread is created; the Activecount of the Threadgroup class can check the number of threads that can run in that thread group ; The operation of a thread group can manipulate all threads inside it

Exception handler not caught: Thread's Run method cannot throw an exception; The exception is automatically passed to an unhandled exception handler before the thread dies because of an exception that is not caught ; The exception handler must be a class that implements the Thread.uncaughtexceptionhandler interface and is set by the Setuncaughtexceptionhandler method

Sync: There are two mechanisms in Java to protect blocks of code from parallel access:

1. Reentrantlock class: Structural shape such as:

Mylock.lock ();

try {

...

}

finally {

Mylock.unlock ();

}

Where Mylock is an instance of the Reentrantlock class, the code between the lock method and the Unlock method in the structure is synchronized, and the try/finally is used to execute the unlock even if the exception is thrown, in order to avoid deadlock, without exception

The lock is reentrant (the thread can repeatedly acquire the lock it already has); The lock object maintains a hold count to track nested calls to the Lock method (lock plus 1,unlock minus 1), and the lock is released when the hold count is 0 o'clock

A lock object can have one or more associated condition (Condition) objects, and a new conditional object can be obtained by the Newcondition method of the Reentrantlock class The conditional object calls the await method to cause the thread holding the lock to enter a blocking state and discard the lock, which remains blocked until another thread calls the Signalall method of the same condition object; The Signalall method will unblock all threads waiting for this condition, which will again compete for the lock. Once the lock is acquired, the thread continues to execute from the await and the signal method can randomly unblock one of the threads waiting for the condition

Once a thread has entered a blocking state because of await, it must wait for another thread to call the Signalall or signal method to unblock it, or it will never run again (deadlock), and if the last active thread calls the await method before unblocking another thread, The entire program will be suspended

Summarize:

1 locks are used to protect code fragments, allowing only one thread to execute protected code at any time

2 locks can manage threads that attempt to enter protected code segments

3 The lock can have one or more related condition objects

4 Each Condition object manages those threads that have entered the protected code snippet but cannot run

2. Synchronized keyword: implicit lock; thread obtains synchronized lock in two ways: calling a sync method or entering a synchronized block

Sync method: Modifying a method with the Synchronized keyword, the lock of an object protects the entire method; An implicit object lock has only one associated condition, and the wait method of the object class adds the thread to the waiting set. The Notify and Notifyall methods can unlock the blocking state of the waiting thread

Sync Block: Form:

Synchronized (obj) {

...

}

Where obj can be a meaningless object, or an object that the current method needs to manipulate (such as this)

The domain that the volatile keyword modifies will provide a "lock-free" mechanism when accessed synchronously, that is, both the compiler and the virtual machine know that the domain may be or is being updated concurrently by another thread (need to be checked synchronously)

Parallel access to a domain is thread-safe if one of the following conditions is true:

1. The domain is volatile

2. The domain is final and has been assigned a value

3. Access to the domain has lock protection

Fair Lock: When you create a reentrantlock, set its constructor argument to true, a fair lock object is created that favors the threads that wait for the longest time, but can significantly affect performance; The default locks are not fair

The Reentrantlock class provides a Trylock method to attempt a lock, returns true if it succeeds, or returns false to avoid thread blocking from times of lock methods; This method robs any available locks, Even if the current Reentrantlock object is set to be fair; Trylock and await overloads have the form of a timeout parameter, and the wait thread's blocking will be lifted after timeout

Read/write lock Reentrantreadwritelock is suitable for when multiple threads read data from a data structure and few threads modify it; the necessary steps to use it:

1. Create a Reentrantreadwritelock object

2. Extract the Read lock object (Readlock method) and write Lock (Writelock method) object

3. Add read lock or write lock to code section, similar to Reentrantlock structure

Where read locks Repel all writes, write locks repel all other read and write operations

Blocking queues: When you are working with multithreading, worker threads can periodically store intermediate results in a blocking queue, and other threads can remove and modify intermediate results while they are working, causing threads to block when trying to add new elements to a full blocking queue, or removing elements from an empty blocking queue

Blocking queues are automatically synchronized, thread-safe

The Java.util.concurrent package provides four types of blocking queues, which are generic classes that implement the Blockingqueue<e> interface:

1. Linkedblockingqueue<e>, the default capacity is not capped, but you can specify

2. Arrayblockingqueue<e> The capacity must be specified and whether fairness is required

3. Priorityblockingqueue<e>, with priority blocking queues, access in order of priority, capacity without limit

4. delayqueue<e Extendsdelayed> must contain an object that implements the delayed interface

Thread-Safe Collections: Concurrentlinkedqueue,concurrenthashmap

Copyonwritearraylist,copyonwritearrayset

Vector,hashtable

The callable and Future:callable interfaces are similar to the runnable, but it has a return value, which is a generic interface (CALLABL<V> where V is its only method call's return value type)

The future interface is also a generic interface; it has two get methods: The parameterless getting method is blocked until the calculation is complete, and a parameter get method can set the timeout time; there are also some methods for detecting states.

In practice, you can create a new object that combines the runnable and future interface functions simply by implementing the class of the callable interface, and then passing the object of that class to the constructor of the Futuretask wrapper class. The instance of the Futuretask class may replace the object in thread that implements the Runnable interface, and the Futuretask class also provides methods in the future interface

Actuator: If the program requires a large number of short lifetime threads, you should use a thread pool to reduce the overhead of creating new threads; The thread pool contains a large number of idle threads that are ready to run, and when the Runnable object is passed to the thread pool, a thread in the threads pool automatically invokes the Run method, and when the Run method exits, The thread returns to the thread pool to prepare for the next use

Another reason to use the thread pool is to reduce the number of concurrent threads by using a thread pool with a "fixed" number of threads to implement the

The Executor executor class has a large number of static factory methods used to build thread pools:

1. Newcachedthreadpool: Build a thread pool, for each task, if an idle thread is available, execute it immediately, or create a new thread; The idle thread will be kept for 60 seconds

2. Newfixedthreadpool: Create a fixed-size thread pool; If the number of tasks is greater than the number of idle threads, the tasks that are not executed will be placed in the queue waiting for other tasks to complete

3. Newsinglethreadexecutor: Create a 1-capacity thread pool where all tasks are executed serially

The above three methods return an object of the Threadpoolexecutor class that implements the Executorservice interface This object provides 3 overloaded submit methods to submit the runnable or callable object to the Executorservice and returns the future object

You need to invoke the Shutdown method after using the thread pool. This method launches the shutdown sequence of the pool so that the pool no longer receives new tasks and closes the pool after the existing threads have died; You can also call the Shutdownnow method, which cancels the task that has not yet started and attempts to break the running thread in the pool

4. Newscheduledthreadpool

5. Newsinglescheduledthreadexecutor

Both of these methods return an object that implements the Scheduledexecutorservice interface, which has a method designed to subscribe to or repeat a task, and can be scheduled to run only once after the initial delay of the runnable or callable. You can also schedule a Runnable object to run periodically; see Java API

Control Thread Group: The Invokeany and InvokeAll methods of the thread pool object that implements the Executorservice interface can handle tasks for a set of callable interfaces, as detailed in the Java API

Synchronizer: Synchronizer is a class that provides "out-of-the-box" functionality for common assembly points between threads; The aggregation point refers to a gathering place where the thread calls, where each thread brings the result together to form a complete result, and the thread set can reuse the appropriate class directly if it reaches one of the available collection points. Rather than manually maintaining a lock collection

1. Barrier: The Cyclicbarrier class implements a set of points called "barrier grids": When a large number of threads run in a different part of the calculation, all parts need to be consolidated after they have been processed; The barrier exists before the final integration, and after each thread completes its task, it runs to the barrier and waits, When all threads arrive at the barrier, the barrier is revoked and the thread can continue to run; Step:

1 Create a Barrier class Cyclicbarrier object, set the number of threads in the constructor parameters

2 at the end of each thread task (in the Runnable Run method), the barrier object calls its await method

2. Countdown Door BOLT: Countdownlatch class lets the thread set wait until the counter is reduced (Coutdown method) is 0, for multiple threads to wait until a specified number of results are available

3. Exchanger: The Exchanger class allows two threads to swap objects when the object being exchanged is ready, and can be used when two threads work on two instances of the same data structure

4. Synchronization queues: Synchronous queues are a mechanism for producer and consumer threading; When a thread calls the Synchronousqueue put method to pass an instance, it is blocked until another thread calls the Take method to take the instance

5. Semaphore: Semaphore Semaphore class manages a large number of licenses that can be either applied through the Acquire method or released via release (but not required for the thread to be released); The threading code that owns the license can be executed, otherwise the trip is blocked until a license is obtained ; The number of licenses is the number of threads that limit passing

In general, the class of the five Synchronizer is to add a specific waiting condition (rendezvous) in the thread's task code. If the condition is satisfied, the execution continues, otherwise the thread is blocked until the condition is satisfied, and each condition provides a way to update the current state (the way the thread converges to the collection point)

Network

Socket: Socket, an abstract concept in network software that is responsible for the communication between the inside and outside of the program; the socket class creates an object by passing in a remote address and port number

Server sockets: ServerSocket, creating an object by passing in the port number of the constructor, which listens for network data on that port

The ServerSocket class accept method can block the thread that calls this method until a client connects to the port, and the method returns a socket object that represents the client

Input output stream: The getInputStream method of the socket class and the Getoutputstream method can obtain the output stream that reads the data from the remote client and writes the data to the remote client; The print type method is more efficient than the Write method when writing data , as close as the end of the stream is to be used, it should be closed after the socket is finished

For multiple Client Services: Accept method each time a new connected client's socket object is returned, a new thread is opened to handle the data reading and writing of this socket object exclusively

Send email: The parameters for constructing the socket object are the address (String) of the mailbox server and the port number (int,25 is the system fixed port number of the SMTP protocol); The SMTP specification should be written to the message data in the output stream; JavaMail The API provides a static method Transport.send (String) that can be used to send an email

URIs and Url:uri (Uniform Resource Identifiers) are pure grammatical constructs that specify the different parts of a string that identifies a Web resource; a URL (Uniform Resource Locator) is a subset of the URI that contains enough information to locate a Web resource ; a URI that is not a URL is generally called a urn (the Uniform Resource name); it does not navigate to the exact location of the resource

In Java, the URI class does not contain any method for accessing the resource, its only function is to parse the URI string of the resource, and the URL class can open the resource that arrives at a Java class library that knows how to work (http:, https:, ftp:, File:, jar: , etc.) of the stream or connection

Establish a URL connection: the URL class Initializes an object by passing in a URL string, which can be opened directly by the OpenStream method in the URL class, which accesses the "content" of the resource.

If you need to obtain more information about the resource, you should create a URLConnection object using the OpenConnection method in the URL class, and then you can set the type of the access request through the set type method in URLConnection , then call the Connect method to connect the resource, after the connection is established, you can obtain various information of the resource through the URLConnection Get type method (where getinputstream can get the same content input stream as the OpenStream method of the URL class)

Submit form data: First create a URLConnection object from the URL; Set the Setdooutput method of the object to True (default to False), and then obtain the output stream that writes data to the server where the resource resides by using the Getoutputstream method ; calls the print method of the output stream, writes the data in the format of Name=urlencoder.encode (value, "UTF-8"), separates multiple data by "&", closes the output stream, and opens an input stream to read the server's response information

Socket timeout: The socket timeout can be set by calling the Setsotimeout (int) method of the socket class, and if the subsequent read and write operation exceeds the time limit before it is completed, the sockettimeoutexception is thrown. Processing that can respond to timeouts by capturing the exception

In addition, the default constructor socket (stringhost, int port) actually blocks the current thread until the connection is established; To avoid blocking, you can construct a connectionless socket and then use a time-out to connect, as follows:

Socket s = new socket ();

S.connect (New Inetsocketaddress (host, port), timeout);

Interruptible sockets: Threads cannot be interrupted by interrupt when they are blocked because of the inability to respond to socket length; The Java.nio package provides a Socketchannel class that creates a channel (channel) through a static method open binding Inetsocketaddress object, which is independent of the stream, but can be implemented from the Readablebytechannel interface and WRITABL The Read and write methods of the Ebytechannel interface call the buffer object to read and write data; At any moment, by close the channel, you can break this socket

Semi-closed: Indicates that the request data sent to the server has ended by closing a socket's output stream (Shutdownoutput method). However, keep the input stream open to read the response information returned by the server to tell the server that the request has ended but the socket has not been closed and is suitable for one-stop network service

Internet address: InetAddress class can convert host name and Internet IP Address, objects of this class can be created by static method Getbyname (String host)

Database Programming

To establish a JDBC connection:

1. Add the library that contains the database JDBC driver to the compilation environment (modify the CLASSPATH environment variable, or place the driver package in Jre/lib/ext)

2. Registering the driver in the driver manager can be done via System.setproperty ("Jdbc.drivers", "Com.mysql.jdbc.Driver"), or through Class.forName (" Com.mysql.jdbc.Driver ")

3. Open the connection via DriverManager: drivermanager.getconnection (URL, username, password); Where the URL is the database's url,username is the database's account name, Password is a password; Returns a Connection object

Execute SQL command: Connection object's method createstatement can create a statement object in which:

1. int executeupdate (String sql) method can perform insert, DELETE, update operations, and return the number of rows affected

2. The ResultSet executequery (Stringsql) method can perform a select operation, and the returned ResultSet object contains a table of query results

3. The Boolean execute (String sql) method can execute arbitrary SQL statements, but is typically used for interactive queries

ResultSet object: The ResultSet object can iterate through each row through the next method, and in each row, data from the corresponding column (starting at 1, not 0) can be accessed through getxxx (int) (such as getdouble (3))

Connection, Statement, resultset shutdown: When you run out of them, you should call the Close method to turn off

Exception handling: Typically, the following code style is used to ensure proper handling of exceptions:

Connection conn = ...;

try {

...

finally {

Conn.close ();

}

Preliminary statement: Prepare a query with a host variable, each time you need to fill in a different string for the variable to use the statement repeatedly, the host variable with "?" Before executing a preliminary statement, you must bind the variable to the correct value (such as setstring (1, "CHN") by using the appropriate setxxx (int position, XXX value) method, where the position value starts at 1

The preliminary statement PreparedStatement object is obtained through the connection Preparestatement (Stringsql) method, and it also contains the parameterless int executeupdate () and ResultSet ExecuteQuery () method performs SQL operations

Scrollable and updatable result sets: Query objects and prepared statement objects have an overloaded method of setting properties (createstatement (int type, int concurrency), and preparestatement when created by connection ( stringsql, int type, int concurrency), where the type sets the result set resultset can scroll, concurrency sets the result set to update the database, and both values are public constants in the ResultSet, as follows:

Type:type_forward_only: Default, result set cannot scroll

Type_scroll_insensitive: scrollable, but not changing with database changes

Type_scroll_sensitive: Scrollable and changes as the database changes

Concurrency:concur_read_only: Default, modify result set cannot update database

Concur_updatable: Modifying result sets to synchronize database modifications

Scrollable result set resultset in addition to the next method to traverse forward, there are previous methods to traverse backwards, there is a relative (int) method can be forward (positive) or backward (negative) to move several, have absolute (int) METHOD specifies to move to a row, as well as some other methods that are not available by default (such as the top, last, and so on)

A modifiable result set can invoke methods provided in the ResultSet class that modify the internal data of the current result set object, such as Updatestring, updatedouble, and so on, but it is important to note that the name or ordinal of the column must be specified (starting from 1). Finally, you need to call the Updaterow method to submit to the database; Similarly, insertrow and DeleteRow also commit the insert rows and delete rows to the database.

Metadata: The DatabaseMetaData object is obtained through the GetMetaData method of connection, which holds the structure information of the database, such as the name of all tables (Gettables method obtained) and so on, which is mainly used to build database management tools

Rowset: Result set resultset The program must be connected to the database (that is, connection cannot close), and ResultSet will not be available once connection is closed; the rowset is used for the same method and function as the result set. However, you do not always have to keep a connection to the database; The specific classes of the rowset are dependent on the library being implemented, slightly

Transaction: A set of SQL statement operations is built into a transaction, and when all statements are executed successfully, the transaction is committed, otherwise the transaction must be rolled back once the statement has been incorrectly

JDBC By default, the database is in autocommit mode (that is, automatic commit immediately after each SQL is executed), the transaction cannot be transacted, and the steps for transaction processing are:

1. Invoke Setautocommit (false) of the connection object to turn off autocommit mode

2. After a statement object or PreparedStatement object executes several times executeupdate methods

3. Call the Connection object's commit method and commit the transaction

4. Call the rollback method of the Connection object for rollback if there is an error or an exception (SQLException)

Typically, the rollback starts at the beginning of the transaction, after the last invocation of a commit, which can be set manually by setting the SavePoint SavePoint object (created by the Setsavepoint method of the Connection object) to roll back the starting point (called rollback ( SavePoint); After the operation is completed, you need to call the Connection object's Releasesavepoint (savepoint) to release the savepoint.

Batch processing: The Addbatch (String sql) method of the Statement object can add a set of SQL statements to a batch sequence, and after the addition completes, the call to the ExecuteBatch method can execute all the SQL statements in the sequence one at a time. and returns an integer value to record the number of rows affected by each statement; Note that if you perform a select operation in a batch, it throws an exception

Advanced Connection Management: If database connection management is integrated with Jndi, the DataManager is no longer used to create a database connection, and the connection object is created by Jdni the specified resource class, as in the following example:

Context Jndiconext = new InitialContext ();

DataSource Source = (DataSource) jndicontext.lookup (...);

Connection conn = Source.getconnection ();

Java EE environments that are commonly used to integrate database connections with Jndi

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.