반응형

File locking

File locking, introduced in JDK 1.4, allows you to synchronize access to a file as a shared resource. However, the two threads that contend for the same file may be in different JVMs, or one may be a Java thread and the other some native thread in the operating system. The file locks are visible to other operating system processes because Java file locking maps directly to the native operating system locking facility.

Here is a simple example of file locking.

//: c12:FileLocking.java
// {Clean: file.txt}
import java.io.FileOutputStream;
import java.nio.channels.*;

public class FileLocking {
  public static void main(String[] args) throws Exception {
    FileOutputStream fos= new FileOutputStream("file.txt");
    FileLock fl = fos.getChannel().tryLock();
    if(fl != null) {
      System.out.println("Locked File");
      Thread.sleep(100);
      fl.release();
      System.out.println("Released Lock");
    }
    fos.close();
  }
} ///:~


You get a FileLock on the entire file by calling either tryLock( ) or lock( ) on a FileChannel. (SocketChannel, DatagramChannel, and ServerSocketChannel do not need locking since they are inherently single-process entities; you don’t generally share a network socket between two processes.) tryLock( ) is non-blocking. It tries to grab the lock, but if it cannot (when some other process already holds the same lock and it is not shared), it simply returns from the method call. lock( ) blocks until the lock is acquired, or the thread that invoked lock( ) is interrupted, or the channel on which the lock( ) method is called is closed. A lock is released using FileLock.release( ).

It is also possible to lock a part of the file by using

tryLock(long position, long size, boolean shared)


or

lock(long position, long size, boolean shared)


which locks the region (size - position). The third argument specifies whether this lock is shared.

Although the zero-argument locking methods adapt to changes in the size of a file, locks with a fixed size do not change if the file size changes. If a lock is acquired for a region from position to position+size and the file increases beyond position+size, then the section beyond position+size is not locked. The zero-argument locking methods lock the entire file, even if it grows.

Support for exclusive or shared locks must be provided by the underlying operating system. If the operating system does not support shared locks and a request is made for one, an exclusive lock is used instead. The type of lock (shared or exclusive) can be queried using FileLock.isShared( ).

Locking portions of a mapped file

As mentioned earlier, file mapping is typically used for very large files. One thing that you may need to do with such a large file is to lock portions of it so that other processes may modify unlocked parts of the file. This is something that happens, for example, with a database, so that it can be available to many users at once.

Here’s an example that has two threads, each of which locks a distinct portion of a file:

//: c12:LockingMappedFiles.java
// Locking portions of a mapped file.
// {RunByHand}
// {Clean: test.dat}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class LockingMappedFiles {
  static final int LENGTH = 0x8FFFFFF; // 128 Mb
  static FileChannel fc;
  public static void main(String[] args) throws Exception {
    fc = 
      new RandomAccessFile("test.dat", "rw").getChannel();
    MappedByteBuffer out = 
      fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
    for(int i = 0; i < LENGTH; i++)
      out.put((byte)'x');
    new LockAndModify(out, 0, 0 + LENGTH/3);
    new LockAndModify(out, LENGTH/2, LENGTH/2 + LENGTH/4);
  }
  private static class LockAndModify extends Thread {
    private ByteBuffer buff;
    private int start, end;
    LockAndModify(ByteBuffer mbb, int start, int end) {
      this.start = start;
      this.end = end;
      mbb.limit(end);
      mbb.position(start);
      buff = mbb.slice();
      start();
    }    
    public void run() {
      try {
        // Exclusive lock with no overlap:
        FileLock fl = fc.lock(start, end, false);
        System.out.println("Locked: "+ start +" to "+ end);
        // Perform modification:
        while(buff.position() < buff.limit() - 1)
          buff.put((byte)(buff.get() + 1));
        fl.release();
        System.out.println("Released: "+start+" to "+ end);
      } catch(IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
} ///:~


The LockAndModify thread class sets up the buffer region and creates a slice( ) to be modified, and in run( ), the lock is acquired on the file channel (you can’t acquire a lock on the buffer—only the channel). The call to lock( ) is very similar to acquiring a threading lock on an object—you now have a “critical section” with exclusive access to that portion of the file.

The locks are automatically released when the JVM exits, or the channel on which it was acquired is closed, but you can also explicitly call release( ) on the FileLock object, as shown here.

출처 : http://www.linuxtopia.org/

반응형
반응형

Memory-mapped files

Memory-mapped files allow you to create and modify files that are too big to bring into memory. With a memory-mapped file, you can pretend that the entire file is in memory and that you can access it by simply treating it as a very large array. This approach greatly simplifies the code you write in order to modify the file. Here’s a small example:

//: c12:LargeMappedFiles.java
// Creating a very large file using mapping.
// {RunByHand}
// {Clean: test.dat}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class LargeMappedFiles {
  static int length = 0x8FFFFFF; // 128 Mb
  public static void main(String[] args) throws Exception {
    MappedByteBuffer out = 
      new RandomAccessFile("test.dat", "rw").getChannel()
      .map(FileChannel.MapMode.READ_WRITE, 0, length);
    for(int i = 0; i < length; i++)
      out.put((byte)'x');
    System.out.println("Finished writing");
    for(int i = length/2; i < length/2 + 6; i++)
      System.out.print((char)out.get(i));
  }
} ///:~


To do both writing and reading, we start with a RandomAccessFile, get a channel for that file, and then call map( ) to produce a MappedByteBuffer, which is a particular kind of direct buffer. Note that you must specify the starting point and the length of the region that you want to map in the file; this means that you have the option to map smaller regions of a large file.

MappedByteBuffer is inherited from ByteBuffer, so it has all of ByteBuffer’s methods. Only the very simple uses of put( ) and get( ) are shown here, but you can also use things like asCharBuffer( ), etc.

The file created with the preceding program is 128 MB long, which is probably larger than the space your OS will allow. The file appears to be accessible all at once because only portions of it are brought into memory, and other parts are swapped out. This way a very large file (up to 2 GB) can easily be modified. Note that the file-mapping facilities of the underlying operating system are used to maximize performance.

Performance

Although the performance of “old” stream I/O has been improved by implementing it with nio, mapped file access tends to be dramatically faster. This program does a simple performance comparison:

//: c12:MappedIO.java
// {Clean: temp.tmp}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class MappedIO {
  private static int numOfInts = 4000000;
  private static int numOfUbuffInts = 200000;
  private abstract static class Tester {
    private String name;
    public Tester(String name) { this.name = name; }
    public long runTest() {
      System.out.print(name + ": ");
      try {
        long startTime = System.currentTimeMillis();
        test();
        long endTime = System.currentTimeMillis();
        return (endTime - startTime);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    public abstract void test() throws IOException;
  }
  private static Tester[] tests = { 
    new Tester("Stream Write") {
      public void test() throws IOException {
        DataOutputStream dos = new DataOutputStream(
          new BufferedOutputStream(
            new FileOutputStream(new File("temp.tmp"))));
        for(int i = 0; i < numOfInts; i++)
          dos.writeInt(i);
        dos.close();
      }
    }, 
    new Tester("Mapped Write") {
      public void test() throws IOException {
        FileChannel fc = 
          new RandomAccessFile("temp.tmp", "rw")
          .getChannel();
        IntBuffer ib = fc.map(
          FileChannel.MapMode.READ_WRITE, 0, fc.size())
          .asIntBuffer();
        for(int i = 0; i < numOfInts; i++)
          ib.put(i);
        fc.close();
      }
    }, 
    new Tester("Stream Read") {
      public void test() throws IOException {
        DataInputStream dis = new DataInputStream(
          new BufferedInputStream(
            new FileInputStream("temp.tmp")));
        for(int i = 0; i < numOfInts; i++)
          dis.readInt();
        dis.close();
      }
    }, 
    new Tester("Mapped Read") {
      public void test() throws IOException {
        FileChannel fc = new FileInputStream(
          new File("temp.tmp")).getChannel();
        IntBuffer ib = fc.map(
          FileChannel.MapMode.READ_ONLY, 0, fc.size())
          .asIntBuffer();
        while(ib.hasRemaining())
          ib.get();
        fc.close();
      }
    }, 
    new Tester("Stream Read/Write") {
      public void test() throws IOException {
        RandomAccessFile raf = new RandomAccessFile(
          new File("temp.tmp"), "rw");
        raf.writeInt(1);
        for(int i = 0; i < numOfUbuffInts; i++) {
          raf.seek(raf.length() - 4);
          raf.writeInt(raf.readInt());
        }
        raf.close();
      }
    }, 
    new Tester("Mapped Read/Write") {
      public void test() throws IOException {
        FileChannel fc = new RandomAccessFile(
          new File("temp.tmp"), "rw").getChannel();
        IntBuffer ib = fc.map(
          FileChannel.MapMode.READ_WRITE, 0, fc.size())
          .asIntBuffer();
        ib.put(0);
        for(int i = 1; i < numOfUbuffInts; i++)
          ib.put(ib.get(i - 1));
        fc.close();
      }
    }
  };
  public static void main(String[] args) {
    for(int i = 0; i < tests.length; i++)
      System.out.println(tests[i].runTest());
  }
} ///:~


As seen in earlier examples in this book, runTest( ) is the Template Method that provides the testing framework for various implementations of test( ) defined in anonymous inner subclasses. Each of these subclasses perform one kind of test, so the test( ) methods also give you a prototype for performing the various I/O activities.

Although a mapped write would seem to use a FileOutputStream, all output in file mapping must use a RandomAccessFile, just as read/write does in the preceding code.

Here’s the output from one run:

Stream Write: 1719
Mapped Write: 359
Stream Read: 750
Mapped Read: 125
Stream Read/Write: 5188
Mapped Read/Write: 16


Note that the test( ) methods include the time for initialization of the various I/O objects, so even though the setup for mapped files can be expensive, the overall gain compared to stream I/O is significant.

출처 : http://www.linuxtopia.org/

반응형
반응형


자바 스크립트 키 코드 값 구하는 함수.


<script language="JavaScript">
document.onkeydown = checkKeycode





function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
alert("keycode: " + keycode);
}
</script>
 

/*
*
* 한글 입력 체크하기 위한 함수
* ex) <input type="text" name="Name" size="10" maxlength="15" onKeyPress="hangul();" style="ime-mode:active;" >
*
*
*/
function hangul()
{
 if((event.keyCode < 12592) || (event.keyCode > 12687))
  event.returnValue = false;
}
/*
*
* 숫자 입력 체크하기 위한 함수
* ex) <input type="text" name="jumin" size="10" maxlength="13" onKeyPress="only_number();" style="IME-MODE: disabled;" >
*
*
*/
function only_number()
{
 if((event.keyCode < 48) || (event.keyCode > 57))
  event.returnValue = false;
}
 
 

Key Code Reference Table


Key Pressed

Javascript Key Code

backspace

8

tab

9

enter

13

shift

16

ctrl

17

alt

18

pause/break

19

caps lock

20

escape

27

page up

33

page down

34

end

35

home

36

left arrow

37

up arrow

38

right arrow

39

down arrow

40

insert

45

delete

46

0

48

1

49

2

50

3

51

4

52

5

53

6

54

7

55

8

56

9

57

a

65

b

66

c

67

d

68

e

69

f

70

g

71

h

72

i

73

j

74

k

75

l

76

m

77

n

78

o

79

p

80

q

81

r

82

s

83

t

84

u

85

v

86

w

87

x

88

y

89

z

90

left window key

91

right window key

92

select key

93

numpad 0

96

numpad 1

97

numpad 2

98

numpad 3

99

numpad 4

100

numpad 5

101

numpad 6

102

numpad 7

103

numpad 8

104

numpad 9

105

multiply

106

add

107

subtract

109

decimal point

110

divide

111

f1

112

f2

113

f3

114

f4

115

f5

116

f6

117

f7

118

f8

119

f9

120

f10

121

f11

122

f12

123

num lock

144

scroll lock

145

semi-colon

186

equal sign

187

comma

188

dash

189

period

190

forward slash

191

grave accent

192

open bracket

219

back slash

220

close braket

221

single quote

222




반응형
반응형

JAD도 별 불편함 없이 사용하고 있지만 1.4 이후 버전에 대한 지원 소식도 없고 업그레이드도 없는듯 하다.

우선 JD-GUI  윈도우 버전을 다운로드 하여 실행해보았다.

디컴파일 속도도 빠르고 이클립스용 플러그인도 지원하고 있다.

무설치 버전으로 실행하니 일반 에디터와 같은 GUI를 제공하고 있다.

사용하기도 편리하고 무설치에 GUI까지 제공등.. 그리고 지원하는 java 버전등..

이 어찌 매력적이지 않겠는가? 밑에 JD-GUI 사이트 링크를 걸어 놓는다.

http://java.decompiler.free.fr/



GUI 화면 모습이다. 간단히 jar 파일을 실행해 보았다.. 잘 나온다..ㅎㅎ

그리고 디컴파일된 소스는 파일로 저장까지 할수 있다..  꽤 괜찮은것 같다.

이클립스 플러그인 설치는 해당 사이트에 가면 자세히 설명되어 있다.

Eclipse Platform Version: 3.4.1 에서 jD-Eclipse 플러그인 설치 과정이다.

Installation 

Eclipse 3.4 Instructions

우선 Equinox/p2 plug-in 을 설치 하여야 한다.

  1. 이클립스 메뉴에서 Help -> Software Updates...선택하면 아래와 같은 Software Updates and Add-ons 팝업창이 뜬다.

  2. Available Software 탭을 선택한다.
  3. Ganymede tree node 를 확장시킨다.(왼편의 +를 클릭) 
  4. Uncategorized tree node 를 확장시킨다.(왼편의 +를 클릭) 
  5. Equinox p2 Provisioning tree node 에 체크를하고 ,  Install... button 을 클릭한다.



  6. 마지막으로 Finish button 을 클릭하면 된다. 필자의 경우 tjf

Installation of JD-Eclipse plug-in

  1. 이클립스 메뉴에서 Help -> Software Updates...선택하면 아래와 같은 Software Updates and Add-ons 팝업창이 뜬다.
  2. Available Software 탭을 선택한다.
  3. JD-Eclipse plug-in을 new remote site 로 추가:
    1. Add Site... button 을 클릭하면 Add Site 팝업창이 뜬다..
    2. Location 텍스트 박스에 JD-Eclipse update site URL을 타이핑 한다: http://java.decompiler.free.fr/jd-eclipse/update 그리고 OK button 클릭..



  4. Software Updates and Add-ons 창에 추가된 JD-Eclipse Plug-in 을 체크하고, 오른쪽에 있는 Install... button 을 클릭한다.



  5. 다음 화면에서 , Finish button을 클릭
  6. 다음화면에서, Java Decompiler Eclipse Plug-in certificate box 가 나오면 체크를 하고 OK button 을 클릭하면 완료...  

 

출처 : Tong - 굴스님님의 프로그래밍통

반응형

+ Recent posts