Download essential classes

Document related concepts
no text concepts found
Transcript
Essential Java classes
mainly classes in the java.lang and
java.io packages
Contents
•
•
•
•
•
Handling errors using exceptions
Multi-threading
I/O
Setting program attributes
Accessing system resources
Exceptions
• The Java programming language uses exceptions to
provide error-handling capabilities for its programs
• An exception is an event that occurs during the
execution of a program that disrupts the normal flow of
instructions
• When an error occurs within a method, the method
creates an object and hands it off to the runtime system
• The object, called an exception object, contains
information about the error, including its type and the
state of the program when the error occurred
• Creating an exception object and handing it to the
runtime system is called throwing an exception
Exception handling
• //Note: This class won't compile by design!
import java.io.*;
import java.util.Vector;
public class ListOfNumbers {
private Vector victor;
private static final int SIZE = 10;
public ListOfNumbers () {
victor = new Vector(SIZE);
for (int i = 0; i < SIZE; i++) {
victor.addElement(new Integer(i)); } }
public void writeList() {
PrintWriter out = new PrintWriter(
new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = "
+ victor.elementAt(i)); }
out.close(); } }
• private Vector victor;
private static final int SIZE = 10;
PrintWriter out = null;
try {
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = "
+ victor.elementAt(i));
}
}
catch and finally statements . . .
Catch exceptions
• try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: "
+ e.getMessage());
throw new SampleException(e);
} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
}
Finally
• finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
Specify exceptions thrown by
methods
• public void writeList() throws IOException {
PrintWriter out = new PrintWriter(
new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = "
+ victor.elementAt(i));
}
out.close();
}
Throw exceptions
• public Object pop() throws EmptyStackException {
}
Object obj;
if (size == 0) {
throw new EmptyStackException();
}
obj = objectAt(SIZE - 1);
setObjectAt(SIZE - 1, null);
size--;
return obj;
Exception classes
Chained exceptions
• Relevant constructor and methods
–
–
–
–
Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)
• try { }
catch (IOException e) {
throw new SampleException("Other
IOException", e); }
Accessing stack trace
• catch (Exception cause) {
StackTraceElement elements[] =
cause.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
}
System.err.println(elements[i].getFileName()
+ ":" + elements[i].getLineNumber()
+ ">> "
+ elements[i].getMethodName()
+ "()");
}
Logging API
• try {
Handler handler = new
FileHandler("OutFile.log");
Logger.getLogger("").addHandler(handler);
} catch (IOException e) {
Logger logger =
Logger.getLogger("package.name");
StackTraceElement elements[] =
e.getStackTrace();
for (int i = 0; n = elements.length; i < n; i++) {
logger.log(Level.WARNING,
Contents
•
•
•
•
•
Handling errors using exceptions
Multi-threading
I/O
Setting program attributes
Accessing system resources
Thread
• A thread — sometimes called an execution context
or a lightweight process — is a single sequential
flow of control within a program
• A thread is similar to a real process in that both have
a single sequential flow of control. However, a
thread is considered lightweight because it runs
within the context of a full-blown program and takes
advantage of the resources allocated for that
program
• As a sequential flow of control, a thread must carve
out some resources within a running program. For
example, a thread must have its own execution stack
and program counter
A timer
• import java.util.Timer; // Simple demo that uses java.util.Timer
to
// schedule a task to execute once 5 seconds have
passed
import java.util.TimerTask;
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000); }
class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
timer.cancel(); //Terminate the timer thread }
}
public static void main(String args[]) {
Steps of implementing timer
• Implement a custom subclass of TimerTask. The
run method contains the code that performs the task.
• Create a thread by instantiating the Timer class.
• Instantiate the TimerTask object.
• Schedule the timer task for execution.
• //Get the Date corresponding to 11:01:00 pm today.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();
timer = new Timer();
timer.schedule(new RemindTask(), time);
Stopping timer thread
• Invoke cancel on the timer. You can do this from
anywhere in the program, such as from a timer task's
run method.
• Make the timer's thread a "daemon" by creating the
timer like this: new Timer(true). If the only threads
left in the program are daemon threads, the program
exits.
• After all the timer's scheduled tasks have finished
executing, remove all references to the Timer
object. Eventually, the timer's thread will terminate.
• Invoke the System.exit method, which makes the
entire program (and all its threads) exit.
• public class ReminderBeep {
...
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000); }
class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
toolkit.beep();
//timer.cancel(); //Not necessary because
//we call System.exit.
System.exit(0); //Stops the AWT thread
//(and everything else).
} }
...
}
Periodic task
• public class AnnoyingBeep {
Toolkit toolkit;
Timer timer;
public AnnoyingBeep() {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(),
0,
//initial delay
1*1000);
//subsequent rate }
class RemindTask extends TimerTask {
int numWarningBeeps = 3;
public void run() {
if (numWarningBeeps > 0) {
toolkit.beep(); numWarningBeeps--; }
System.exit(0); } } }
Implementing a thread
• Subclassing Thread class and overriding run method
• public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.format("%d %s%n", i, getName());
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.format("DONE! %s%n", getName());
}
• public class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
• Implement the Runnable interface and its run method and
then create a thread with itself as the Thread's target.
• public class Clock extends java.applet.Applet
implements Runnable {
private volatile Thread clockThread = null;
public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start(); } }
public void run() {
Thread myThread = Thread.currentThread();
while (clockThread == myThread) {
repaint();
try { Thread.sleep(1000); }
catch (InterruptedException e){ } }
}
public void stop() { clockThread = null; }
Life cycle of a thread
Life cycle of a thread
• A thread is started by its start() method
• A thread enters Not Runnable state when one of the
following events occurs:
– Its sleep method is invoked.
– The thread calls the wait method to wait for a specific condition to
be satisifed.
– The thread is blocking on I/O
• A thread should arrange for its own death by having a run
method that terminates naturally
• Thread.getState() method returns Thread.State values
that include: NEW, RUNNABLE, BLOCKED , WAITING,
TIMED_WAITING, TERMINATED
• The Thread.isAlive() method returns true if the thread has
been started and not stopped
Scheduling
• The Java runtime environment supports a very
simple, deterministic algorithm called fixedpriority scheduling
• This algorithm schedules threads on the basis of
their priority relative to other Runnable threads
• When a thread is created, it inherits its priority
from the thread that created it.
• In addition, by using the setPriority method, you
can modify a thread's priority at any time after its
creation.
• Thread priorities are integers that range between
MIN_PRIORITY and MAX_PRIORITY
(constants defined in the Thread class).
Relinquishing the CPU
• Writing CPU-intensive code can have negative
repercussions on other threads running in the same
process.
• In general, try to write well-behaved threads that
voluntarily relinquish the CPU periodically and
give other threads an opportunity to run.
• A thread can voluntarily yield the CPU by calling
the yield method, which gives other threads of the
same priority a chance to run. If no equal-priority
threads are Runnable, yield is ignored.
Synchronizing threads
• public class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(number, i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { } } } }
• public class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get(number);
}
}
}
Locking an object
• public class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get(int who) {
//CubbyHole locked by the Producer.
...
//CubbyHole unlocked by the Producer }
public synchronized void put(int who, int value) {
//CubbyHole locked by the Consumer.
...
//CubbyHole unlocked by the Consumer.
}
Reentrant lock
• The same thread can call a synchronized method
on an object for which it already holds the lock,
thereby reacquiring the lock
• The Java runtime environment allows a thread to
reacquire a lock because the locks are reentrant
• Reentrant locks are important because they
eliminate the possibility of a single thread having
to wait for a lock that it already holds
notify and wait methods
• public synchronized int get() { //Won't work!
if (available == true) {
available = false;
return contents;
}
}
public synchronized void put(int value) {
work!
if (available == false) {
available = true;
contents = value; }
}
//Won't
• public synchronized int get() {
while (available == false) {
try { //Wait for Producer to put value.
wait();
} catch (InterruptedException e) { }
}
available = false;
notifyAll(); //Notify Producer that value has been retrieved.
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try { //Wait for Consumer to get value.
wait();
} catch (InterruptedException e) { }
}
contents = value; available = true;.
notifyAll(); //Notify Consumer that value has been set
Running the consumer/producer
• public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p = new Producer(c, 1);
Consumer c = new Consumer(c, 1);
p.start();
c.start();
}
}
Explicit lock
• An explicit lock is more flexible than using the
synchronized keyword because the lock can span a few
statements in a method or multiple methods in addition to
the scopes (block and method) supported by synchronized
• To create an explicit lock, instantiate an implementation of
the Lock interface, usually ReentrantLock. To grab the
lock, invoke the lock method; to release the lock, invoke the
unlock method. You should wrap the lock and unlock
methods in a try/finally clause
• To wait on an explicit lock, create a condition variable (an
object that supports the Condition interface) using the
Lock.newCondition method. Condition variables provide
the methods await — to wait for the condition to be true,
and signal and signalAll — to notify all waiting threads
that the condition has occurred
• import java.util.concurrent.locks.*;
public class CubbyHole2 {
private int contents;
private boolean available = false;
private Lock aLock = new ReentrantLock();
private Condition condVar = aLock.newCondition();
public int get(int who) {
aLock.lock();
try { while (available == false) {
try { condVar.await(); }
catch (InterruptedException e) { }
}
available = false;
condVar.signalAll();
} finally { aLock.unlock(); }
return contents;
}
public void put(int who, int value) {
aLock.lock();
try {
while (available == true) {
try { condVar.await(); }
catch (InterruptedException e) { }
}
contents = value;
available = true;
System.out.format("Producer %d put: %d%n",
who, contents);
condVar.signalAll();
} finally { aLock.unlock(); }
}
Synchronized data structure
• In your programs, you probably will want to
take advantage of the java.util.concurrent
package's data structures that hide all the
synchronization details
• import java.util.concurrent.*;
public class Producer3 extends Thread {
private BlockingQueue cubbyhole;
private int number;
public Producer3(BlockingQueue c, int num) {
cubbyhole = c;
number = num;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
cubbyhole.put(i);
System.out.format("Producer #%d put:
%d%n",
number, i);
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
• import java.util.concurrent.*;
public class ProducerConsumerTest3 {
public static void main(String[] args) {
ArrayBlockingQueue c = new
ArrayBlockingQueue(1);
Producer3 p = new Producer3(c, 1);
Consumer3 c = new Consumer3(c, 1);
p.start();
c.start();
}
}
Thread pool
• A thread pool is a managed collection of threads that
are available to perform tasks. Thread pools usually
provide the following:
– Improved performance when executing large numbers of
tasks as a result of reduced per-task invocation overhead.
– A way of bounding the resources, including threads,
consumed when executing a collection of tasks
• In addition, thread pools relieve you from having to
manage the life cycle of threads.
• They allow to take advantage of threading, but focus
on the tasks that you want the threads to perform
instead of thread mechanics
Thread pool
• To use thread pools, instantiate an implementation of the
ExecutorService interface and hand it a set of tasks.
• The choices of configurable thread pool implementations are
ThreadPoolExecutor and ScheduledThreadPoolExecutor.
• Recommend using the more convenient factory methods of the
Executors class listed in the following table.
Factory Methods in the Executors Class
newFixedThreadPool(int) Creates a fixed-size thread pool.
newCachedThreadPool
Creates an unbounded thread pool
with automatic thread reclamation.
newSingleThreadExecutor Creates a single background thread.
• public class WorkerThread implements Runnable {
private int workerNumber;
WorkerThread(int number) {
workerNumber = number;
}
public void run() {
for (int i=0;i<=100;i+=20) { //Perform some work...
System.out.format("Worker number: %d,
percent complete: %d%n",
workerNumber, i);
try { Thread.sleep((int)(Math.random() *
1000));
} catch (InterruptedException e) { }
}
}
}
• import java.util.concurrent.*;
public class ThreadPoolTest {
public static void main(String[ ] args) {
int numWorkers = Integer.parseInt(args[0]);
int threadPoolSize = Integer.parseInt(args[1]);
ExecutorService tpes =
Executors.newFixedThreadPool
(threadPoolSize);
WorkerThread[ ] workers =
new WorkerThread[numWorkers];
for (int i = 0; i < numWorkers; i++) {
workers[i] = new WorkerThread(i);
tpes.execute(workers[i]);
}
tpes.shutdown();
}
}
• import java.util.concurrent.*;
public class CallableWorkerThread implements
Callable<Integer> {
private int workerNumber;
CallableWorkerThread(int number) {
workerNumber = number;
}
public Integer call() {
for (int i = 0; i <= 100; i += 20) { //Perform some work...
System.out.format("Worker number: %d,
percent complete: %d%n", workerNumber, i);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
return(workerNumber);
}
}
• public class ThreadPoolTest2 {
public static void main(String[] args) {
int numWorkers = Integer.parseInt(args[0]);
ExecutorService tpes =
Executors.newCachedThreadPool();
CallableWorkerThread workers[] = new
CallableWorkerThread[numWorkers];
Future<Integer> futures[] = new
Future[numWorkers];
for (int i = 0; i < numWorkers; i++) {
workers[i] = new CallableWorkerThread(i);
futures[i]=tpes.submit(workers[i]); }
for (int i = 0; i < numWorkers; i++) {
try { System.out.format("Ending
worker:
%d%n", futures[i].get());
} catch (Exception e) {}
}
Contents
•
•
•
•
•
Handling errors using exceptions
Multi-threading
I/O
Setting program attributes
Accessing system resources
I/O streams
I/O algorithms
Reading
Writing
1. open a stream
1. open a stream
2. while more information 2. while more
read information
information write
information
3. close the stream
3. close the stream
Class hierarchies in java.io
• The java.io package contains two
independent hierarchies of classes:
– one for reading / writing bytes
– the other for reading / writing characters.
Character Streams
• Subclasses of Reader and Writer has two categories:
– those that read from or write to data sinks and
– those that perform some sort of processing
Character Streams
• Subclasses of Reader and Writer has two categories:
– those that read from or write to data sinks and
– those that perform some sort of processing
Byte streams
• InputStream and OutputStream provide the API
and partial implementation for input streams
(streams that read 8-bit bytes) and output streams
(streams that write 8-bit bytes).
• These streams are typically used to read and write
binary data such as images and sounds.
• Two of the byte stream classes,
ObjectInputStream and ObjectOutputStream,
are used for object serialization
• As with Reader and Writer, subclasses of InputStream
and OutputStream provide specialized I/O of two
categories, : data sink streams (shaded), processing streams
(unshaded)
• As with Reader and Writer, subclasses of InputStream
and OutputStream provide specialized I/O of two
categories, : data sink streams (shaded), processing streams
(unshaded)
I/O super-classes
• Reader and InputStream define similar APIs but
for different data types. For example, Reader
contains these methods for reading characters and
arrays of characters.
– int read()
– int read(char cbuf[])
– int read(char cbuf[], int offset, int length)
• InputStream defines the same methods but for
reading bytes and arrays of bytes:
– int read()
– int read(byte cbuf[])
– int read(byte cbuf[], int offset, int length)
I/O super-classes
• Writer and OutputStream are similarly parallel.
Writer defines these methods for writing characters
and arrays of characters:
– int write(int c)
– int write(char cbuf[])
– int write(char cbuf[], int offset, int length)
• OutputStream defines the same methods for bytes:
– int write(int c)
– int write(byte cbuf[])
– int write(byte cbuf[], int offset, int length)
I/O streams
• All of the streams — readers, writers, input
streams, and output streams — are
automatically opened when created.
• Close a stream by calling its close method.
A program should close a stream as soon as
it is done with it, in order to free up system
resources.
Using the streams
Memory
Pipe
File
Concatenate
Serialize
Conversion
Counting
Lookahead
Printing
Buffering
Filtering
Conversion
CharArrayReader(Writer),
ByteArrayInput(Output)Stream
StringReader(Writer), StringBufferInputStream
PipedReader(Writer), PipedInput(Output)Stream
FileReader(Writer), FileInput(Output)Stream
SequenceInputStream
ObjectInput(Output)Stream
DataInput(Output)Stream
LineNumberReader(InputStream)
PushbackReader(InputStream)
PrintWriter(Stream)
BufferedReader(Writer), BufferedInput(Output)Stream
FilterReader(Writer), FilterInput(Output)Stream
InputStreamReader, OutputStreamWriter
File stream
• import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close(); }
}
• FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile);
Use pipe stream
• FileReader words = new FileReader("words.txt");
Reader rhymingWords = reverse(sort(reverse(words)));
public static Reader reverse(Reader src) throws IOException {
BufferedReader in = new BufferedReader(src);
PipedWriter pipeOut = new PipedWriter();
PipedReader pipeIn = new PipedReader(pipeOut);
PrintWriter out = new PrintWriter(pipeOut);
new ReverseThread(out, in).start();
return pipeIn;
}
• public class ReverseThread extends Thread {
private PrintWriter out;
private BufferedReader in;
public ReverseThread(PrintWriter out, BufferedReader in) {
this.out = out;
this.in = in; }
public void run() {
if (out != null && in != null) {
String input;
while ((input = in.readLine()) != null) {
out.println(reverseIt(input));
out.flush();
} out.close();
}
}
private String reverseIt(String source) { … }
}
Wrap a stream
• BufferedReader in = new BufferedReader(source);
...
PrintWriter out = new PrintWriter(pipeOut);
• The program reads from the BufferedReader, which in
turn reads from source. The program does this so that
it can use BufferedReader's convenient readLine
method
• The PipedWriter is wrapped in a PrintWriter so that the
program can use PrintWriter's convenient println
method
Concatenate files
• import java.io.*;
public class Concatenate {
public static void main(String[] args) throws IOException {
ListOfFiles mylist = new ListOfFiles(args);
SequenceInputStream s =
new SequenceInputStream(mylist);
int c;
while ((c = s.read()) != -1)
System.out.write(c);
s.close();
}
}
public class ListOfFiles implements
Enumeration<FileInputStream> {
private String[] listOfFiles;
private int current = 0;
public ListOfFiles(String[] listOfFiles) {
this.listOfFiles = listOfFiles;
}
public boolean hasMoreElements() {
if (current < listOfFiles.length) return true; else return false;
}
public FileInputStream nextElement() {
FileInputStream in = null;
if (!hasMoreElements()) throw new Exception("No more
files.");
else { String nextElement = listOfFiles[current];
current++;
try { in = new FileInputStream(nextElement); }
Using filter streams
BufferedReader d = new BufferedReader(
new
InputStreamReader(System.in));
String input;
while ((input = d.readLine()) != null) {
...
//do something interesting here
}
Scanning
• import java.io.*;
import java.util.*;
}
public class ScanFar {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new BufferedReader(
new FileReader("farrago.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
s.close();
}
Formatting
• public class Root {
r);
public static void main(String[] args) {
int i = 2;
double r = Math.sqrt(i);
System.out.format("The square root of %d is %f.%n", i,
}
}
Here is the output:
The square root of 2 is 1.414214.
Formatting
•
•
•
•
•
•
%d formats an integer value as a decimal value;
%f formats a floating point value as a decimal value;
%n outputs a locale-specific line terminator.
%x formats an integer as a hexadecimal value;
%s formats any value as a string;
%tB formats an integer as a locale-specific month
name.
Object serialization
• Remote Method Invocation (RMI)-communication between objects via sockets
• Lightweight persistence--the archival of an
object for use in a later invocation of the
same program
Serializing objects
• FileOutputStream out = new
FileOutputStream("theTime");
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();
• FileInputStream in = new FileInputStream("theTime");
ObjectInputStream s = new ObjectInputStream(in);
String today = (String) s.readObject();
Date date = (Date) s.readObject();
Serializable objects
• public class MySerializableClass implements
Serializable { ... }
• serialization of instances of this class are handled by
the defaultWriteObject method of
ObjectOutputStream
– Class of the object
– Class signature
– Values of all non-transient and non-static
members, including members that refer to other
objects
• deserialize any instance of the class with the
defaultReadObject method in ObjectInputStream
New I/O package
• some programmers of high-performance
applications will need the java.nio.* packages.
• These packages provide APIs for scalable I/O, fast
buffered byte and character I/O, and character set
conversion
• The New I/O APIs are designed for performance
tuning — not day-to-day I/O programming
Contents
•
•
•
•
•
Handling errors using exceptions
Multi-threading
I/O
Setting program attributes
Accessing system resources
Set program attributes
• Java programs run within an environment that contains
system attributes: a host machine, a user, a current
directory, and an operating system.
• A Java program also can set up its own configurable
attributes, called program attributes.
• Program attributes allow the user to configure various
startup options, preferred window size, and so on for the
program.
• System attributes are maintained by the System class.
Java programs can set their own set of program attributes
through three mechanisms:
– properties,
– command-line arguments, and
– applet parameters
Properties
• A property defines attributes on a persistent basis.
• An attribute has two parts: a name and a value. For
example, “os.name” contains the name of the current
operating system such as “Linux”
• The Properties class in the java.util package manages a set
of key/value pairs. Each Properties key contains the name
of a system attribute, and its corresponding Properties
value is the current value of that attribute
• The System class uses a Properties object for managing
system properties. Any Java program can use a Properties
object to manage its program attributes
Life cycle of a program’s properties
Contents
•
•
•
•
•
Handling errors using exceptions
Multi-threading
I/O
Setting program attributes
Accessing system resources
Access system resources
• The Java platform lets your program access
system resources through a (relatively)
system-independent API implemented by
the System class and through a systemdependent API implemented by the
Runtime class
Use the system class
• System.out
• System.getProperty(argument);
• class UserNameTest {
public static void main(String[] args) {
String name; name =
System.getProperty("user.name");
System.out.println(name);
}
}
The standard I/O streams
• Standard input--referenced by System.in
– Used for program input, typically reads input
entered by the user.
• Standard output--referenced by System.out
– Used for program output, typically displays
information to the user.
• Standard error--referenced by System.err
– Used to display error messages to the user
System properties
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
file.separator
File separator (for example, "/")
java.class.path Java class-path
java.class.version
Java class version number
java.home
Java installation directory
java.vendor
Java vendor-specific string
java.vendor.url Java vendor URL
java.version
Java version number
line.separator
Line separator
os.arch
Operating system architecture
os.name
Operating system name
os.version
Operating system version
path.separator Path separator (for example, ":")
user.dir
User's current working directory
user.home
User home directory
user.name
User account name
Get / set system properties
• System.getProperty("path.separator");
• import java.io.FileInputStream;
import java.util.Properties;
public class PropertiesTest {
public static void main(String[] args) throws Exception {
// set up new properties object
// from file "myProperties.txt"
FileInputStream propFile =
new FileInputStream(
"myProperties.txt");
Properties p = new Properties(System.getProperties());
p.load(propFile); // set the system properties
System.setProperties(p); // display new properties
System.getProperties().list(System.out); }
Forcing finalization and GC
• Before an object is garbage collected, the Java
runtime system gives the object a chance to clean up
after itself. This step is known as finalization and is
achieved through a call to the object's finalize
method. You can force object finalization to occur
by calling System's runFinalization method.
• System.runFinalization(); This method calls the
finalize methods on all objects that are waiting to be
garbage collected.
• You can ask the garbage collector to run at any time
by calling System's gc method: System.gc();
Provide own security manager
• The security manager is an application-wide
object that determines whether potentially
threatening operations should be allowed.
• The classes in the Java packages cooperate
with the security manager by asking the
application's security manager for
permission to perform certain operations
Security manager
• SecurityManager appsm =
System.getSecurityManager();
• SecurityManager security =
System.getSecurityManager();
if (security != null) {
security.checkExit(status);
}
...
// code continues here if checkedExit() returns
Write a security manager
• class PasswordSecurityManager extends SecurityManager
•
•
•
•
{...}
PasswordSecurityManager(String password) {
super();
this.password = password;
}
private boolean accessOK() {
int c;
DataInputStream dis = new DataInputStream(System.in);
String response;
response = dis.readLine();
if (response.equals(password)) return true; else return
false; }
public void checkRead(String filename) {
if (!accessOK()) throw new SecurityException("No Way!"); }
public void checkWrite(String filename) {
if (!accessOK()) throw new SecurityException("Not Even!");
Install a security manager
• try {
System.setSecurityManager(
new PasswordSecurityManager(“some
password"));
} catch (SecurityException se) {
System.out.println("SecurityManager already
set!");
}
Override methods of security manager
• sockets
checkAccept(String host, int port)
checkConnect(String host, int port)
checkListen(int port)
threads checkAccess(Thread thread)
class loader
checkCreateClassLoader()
file system
checkDelete(String filename)
checkLink(String library)
checkRead(String
filename) checkWrite(String filename) system commands
checkExec(String command)
interpreter
checkExit(int status)
package
checkPackageAccess(String packageName)
checkPackageDefinition(String
packageName)
properties
checkPropertiesAccess()
Other system methods
• System.exit(-1);
• System.currentTimeMillis();
• System.arraycopy(
Object source,
int srcIndex,
Object dest,
int destIndex,
int length );
Runtime object
• Runtime objects provide two services.
– First, they communicate with the components of the runtime
environment--getting information and invoking functions.
– Second, Runtime objects are also the interface to systemdependent capabilities