GVKun编程网logo

Automatic Reference Counting

14

本文将带您了解关于AutomaticReferenceCounting的新内容,另外,我们还将为您提供关于8PraticalExamplesofLinux“Touch”Command--referen

本文将带您了解关于Automatic Reference Counting的新内容,另外,我们还将为您提供关于8 Pratical Examples of Linux “Touch” Command--reference、asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication、AtomicReference、AtomicStampedReference 和 AtomicMarkableReference、AtomicReference、AtomicStampedReference、AtomicMarkableReference的实用信息。

本文目录一览:

Automatic Reference Counting

Automatic Reference Counting

了解Xcode 4.2中Automatic Reference Counting (ARC)是本文要讲解的内容,Automatic Reference Counting (ARC),自动引用计数,是开发Cocoa程序时的一个编译级别的特性,用于自动内存管理。 在XCode 4.2中,使用模板新建一个工程,该工程将使用ARC特性。 如果你的iOS SDK是iOS5 seed release 2,需要做如下修改,才能避免编译时的错误: 在 System/Library/Frameworks/CoreFoundation.framework /Headers/CFBase.h 中,将: CFTypeRef CFMakeCollectable(CFTypeRef cf) CF_AUTOMATED_REFCOUNT_UNAVAILABLE; 修改成: CFTypeRef CFMakeCollectable(CFTypeRef cf); 在System/Library/Frameworks/Foundation.framework/Hea ders/NSObject.h中,将: return (__bridge_retain CFTypeRef)X; 修改成: return (__bridge_retained CFTypeRef)X; 使用ARC将让你远离烦人且容易遗漏的retain,release和autorelease等操作。 ARC的工作原理是,在你编译程序时,将内存操作的代码(retain,release或autorelease)自动添加到需要的位置。即底层上使用和Manual Reference Counting(手工引用计数)一样的内存管理机制,但由于XCode自动帮你在编译时添加内存操作的代码,从而简化了编程的工作。 启用ARC,编译选项中需加上-fobjc-arc,不过这个由XCode在创建工程模板时帮你完成。 XCode 4.2以前版本都不支持ARC。 对操作系统也有要求:Mac OS X v10.6或v10.7 (64-bit applications),iOS4或iOS5。注意:其中Mac OS X v10.6和iOS4不支持weak references(弱引用,后面会说明什么是weak references)。 Xcode 4.2提供了一个名为“Convert to Objective-C Automatic Reference Counting”的工具,在Edit->Convert menu下,可以帮你自动将使用Manual Reference Counting的老代码转换成使用ARC的新代码(例如去掉对retain和release的调用)。 一个使用ARC的代码例子: @interface Person : NSObject @property (nonatomic,strong) Nsstring *firstName; @property (nonatomic,strong) Nsstring *lastName; @property (nonatomic,strong) NSNumber *yearOfBirth; @property (nonatomic,strong) Person *spouse; @end @implementation Person @synthesize firstName,lastName,yearOfBirth,spouse; @end 注意:不再需要重载dealloc函数,因为没有release操作。(strong的语义后面会介绍。) 例子2: (void)contrived { Person *aPerson = [[Person alloc] init]; [aPerson setFirstName:@"William"]; [aPerson setLastName:@"Dudney"]; [aPerson:setYearOfBirth:[[NSNumber alloc] initWithInteger:2011]]; NSLog(@"aPerson: %@",aPerson); } 注意:没有了release操作。 例子3: (void)takeLastNameFrom:(Person *)person { Nsstring *oldLastname = [self lastName]; [self setLastName:[person lastName]]; NSLog(@"Lastname changed from %@ to %@",oldLastname,[self lastName]); } 注意:ARC会保证oldLastname引用的对象在NSLog执行结束之前,不会被释放掉。 使用ARC的一些规则: 不能直接调用dealloc方法,不能重载或直接调用retain,release,retainCount,或autorelease等方法。 但可以通过@selector(retain),@selector(release)这样的形式调用。 用户自定义的dealloc方法,不能调用[super dealloc],编译器会自动帮你添加这个代码。 对Core Foundation-style的对象,仍可以使用CFRetain,CFRelease等方法。 不能使用NSAllocateObject或NSDeallocateObject去创建对象,请使用alloc方法。 在c语言中的结构体中,不能再使用对象指针。请放弃C结构体,使用Objective-C的类。 id和void*之间没有隐式的类型转换,请使用显式类型转换。 不能使用NSAutoreleasePool,ARC提供了@autoreleasepool语句块。 例如: @autoreleasepool { // Code,such as a loop that creates a large number of temporary objects. } 不能使用NSZone。 方法和变量的命名不能以“new”开头。 关于对象的生命周期: weak引用:设置成weak的属性,不会影响对象的生命周期,如果引用的对象已经被释放,引用会指向nil。 strong引用:设置成strong的属性,会影响对象的生命周期。 例如: @property(strong) MyClass *myObject; 和@property(retain) MyClass *myObject;是等效的。 又例如: @property(weak) MyClass *myObject;和@property(assign) MyClass *myObject; 在多数情况下等效,但当instance被释放时,设置为weak的引用会指向nil。 可用的限定词: __strong, 默认的 __weak __unsafe_unretained,和weak的区别是当对象被释放时,引用不指向nil。 __autoreleasing,当方法的参数是id*,且希望方法返回时对象被autoreleased,可以添加__autoreleasing限定词。 使用__weak时要特别小心,例如 Nsstring __weak *string = [[Nsstring alloc] initWithFormat:@"First Name: %@",[self firstName]]; NSLog(@"string: %@",string); //此时string为空,因为weak类型不影响对象的生命周期,对象刚创建就释放了。 其他特性: 使用strong,weak,autoreleasing限定的变量会被隐式初始化为nil。 例如: - (void)myMethod { Nsstring *name; NSLog(@"name: %@",name); //会输出null }

8 Pratical Examples of Linux “Touch” Command--reference

8 Pratical Examples of Linux “Touch” Command--reference

In Linux every single file is associated with timestamps,and every file stores the information of last access time,last modification time and last change time. So,whenever we create new file,access or modify an existing file,the timestamps of that file automatically updated.

In this article we will cover some useful practical examples of Linux touch command. Thetouch command is a standard program for Unix/Linux operating systems,that is used to create,change and modify timestamps of a file. Before heading up for touch command examples,please check out the following options.

Touch Command Options

  1. -a,change the access time only
  2. -c,if the file does not exist,do not create it
  3. -d,update the access and modification times
  4. -m,change the modification time only
  5. -r,use the access and modification times of file
  6. -t,creates a file using a specified time

1. How to Create an Empty File

The following touch command creates an empty (zero byte) new file called sheena.

# touch sheena

2. How to Create Multiple Files

By using touch command,you can also create more than one single file. For example the following command will create 3 files named, sheenameena and leena.

# touch sheena meena leena

3. Change File’s Access Time using -a

We can change the access time of a file using -a option. By default it will take the current system time and update the atime field.

Before touch command is executed:

$ stat tgs.txt

File: `tgs.txt'
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: 801h/2049d Inode: 394283 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/lakshmanan) Gid: ( 1000/lakshmanan)
Access: 2012-10-18 23:58:21.663514407 +0530
Modify: 2012-10-18 23:58:21.663514407 +0530
Change: 2012-10-18 23:58:21.663514407 +0530

$ touch -a tgs.txt

After the above touch command (Please note that the access time is changed):

$ stat tgs.txt

File: `tgs.txt'
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: 801h/2049d Inode: 394283 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/lakshmanan) Gid: ( 1000/lakshmanan)
Access: 2012-10-19 00:08:23.559514525 +0530
Modify: 2012-10-18 23:58:21.663514407 +0530
Change: 2012-10-19 00:08:23.559514525 +0530

4. How to Avoid Creating New File

Using -c option with touch command avoids creating new files. For example the following command will not create a file called leena if it does not exists.

# touch -c leena

5. How to Change File Modification Time

If you like to change the only modification time of a file called leena,then use the -moption with touch command. Please note it will only updates the last modification times (not the access times) of the file.

# touch -m leena

6. Explicitly Setting Access and Modification time using -t and -d

Instead of taking the current time-stamp,you can explicitly specify the time using -t and -d options.

The format for specifying -t is [[CC]YY]MMDDhhmm[.SS]

$ touch -t [[CC]YY]MMDDhhmm[.SS]

The following explains the above format:

  • CC – Specifies the first two digits of the year
  • YY – Specifies the last two digits of the year. If the value of the YY is between 70 and 99,the value of the CC digits is assumed to be 19. If the value of the YY is between 00 and 37,the value of the CC digits is assumed to be 20. It is not possible to set the date beyond January 18,2038.
  • MM – Specifies the month
  • DD – Specifies the date
  • hh – Specifies the hour
  • mm – Specifies the minute
  • SS – Specifies the seconds

For example:

$ touch -a -m -t 203801181205.09 tgs.txt

Verify the above change using stat command:

$ stat tgs.txt
  File: `tgs.txt'
  Size: 3           Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 394283      Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/lakshmanan)   Gid: ( 1000/lakshmanan)
Access: 2038-01-18 12:05:09.000000000 +0530
Modify: 2038-01-18 12:05:09.000000000 +0530
Change: 2012-10-19 00:40:58.763514502 +0530

You can also use a string to change the time

Another example:

$ touch -d "2012-10-19 12:12:12.000000000 +0530" tgs.txt

For developers,touch command will be really helpful when you are working with 

7. How to Use the time stamp of another File

The following touch command with -r option,will update the time-stamp of file leena with the time-stamp of meena file. So,both the file holds the same time stamp.

# touch -r leena meena

8. Create a File using a specified time

If you would like to create a file with specified time other than the current time,then the format should be.

# touch -t YYMMDDHHMM.SS tecmint

For example the below command touch command with -t option will gives the tecmint file a time stamp of 18:30:55 p.m. on December 102012.

# touch -t 201212101830.55 tecmint

9. 批量创建文件

#!/bin/ name {..

We’ve almost covered all the options available in the touch command for more options use “man touch“. If we’ve still missed any options and you would like to include in this list,please update us via comment Box.

reference :

http://www.tecmint.com/8-pratical-examples-of-linux-touch-command/

http://www.thegeekstuff.com/2012/11/linux-touch-command/

 linux shell 脚本攻略

asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication

asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication

在将代码库从ASP 5 beta 7更新到RC1-final之后,我开始从JwtBearer中间件接收此异常

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.IConvertible'.

到目前为止我可以看到的决定因素似乎是选项的设置.AutomaticAuthenticate.如果这是真的,那么我得到例外,否则,我没有.

什么是AutomaticAuthenticate,为什么我需要启用它?

app.UseJwtBearerAuthentication(options =>
    {
        options.AutomaticAuthenticate = true; 
    }

这是完整的堆栈跟踪:

at System.Convert.ToInt32(Object value,IFormatProvider provider)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.GetIntClaim(String claimType)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.get_Nbf()
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.Validatetoken(String token,TokenValidationParameters validationParameters,SecurityToken& validatedToken)
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptiondispatchInfo.Throw()
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationHandler`1.<InitializeAsync>d__48.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Api.Startup.<<Configure>b__9_0>d.MoveNext() in ...\Startup.cs:line 156

更新根本原因

我们的代码库正在为nbf,exp和iat创建重复声明.这就解释了为什么get_Nbf在堆栈跟踪中以及关于“JArray”的抱怨,因为每个值都是数组而不是值.

解决方法

如果设置为true,则中间件将在每个入站请求上运行,查找JWT令牌,如果存在,则将验证它,如果有效则从中创建标识并将其添加到当前用户.

如果它没有发生,那么您需要通过在authorize属性中指定承载的方案来请求中间件设置标识.

[Authorize(AuthenticationSchemes = "YourBearerSchemeName")]

或者你在政策中设置这个;

options.AddPolicy("RequireBearer",policy =>
{
    policy.AuthenticationSchemes.Add("YourBearerSchemeName");
    policy.RequireAuthenticatedUser();

});

因此,通过将其设置为false,您实际上并没有运行持有者的东西,直到您要求它为止,您只是将异常关闭直到稍后.

AtomicReference、AtomicStampedReference 和 AtomicMarkableReference

AtomicReference、AtomicStampedReference 和 AtomicMarkableReference

这三个都是自 JDK1.5 开始加入到 java.util.concurrent.atomic 下面的。他们都可以在 lock-free 的情况下以原子的方式更新对象引用。

 

一、AtomicReference

以原子方式更新对象引用。

static class User {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public User(int age) {
        this.age = age;
    }
}

public static void main(String[] args) {
    User user1 = new User(10);
    User user2 = new User(20);

    AtomicReference<User> atomicReference = new AtomicReference<>(user1);
    System.out.println(atomicReference.get().getAge());

    atomicReference.compareAndSet(user1, user2);
    System.out.println(atomicReference.get().getAge());
}

 

二、AtomicStampedReference

解决了 AtomicReference 中 CAS 操作存在的 ABA 问题。

public static void main(String[] args) {
    User user1 = new User(10);
    User user2 = new User(20);

    AtomicStampedReference<User> stampedReference = new AtomicStampedReference<>(user1, 1);

    int[] stamp = new int[1];
    // 获取引用对象和对应的版本号
    System.out.println(stampedReference.get(stamp).getAge());

    int oldStamp = stamp[0];
    // 预期引用,新引用,预期版本号,新版本号
    stampedReference.compareAndSet(user1, user2, oldStamp, 2);
    
    System.out.println(stampedReference.get(stamp).getAge());
}

內部定义了一个 Pair 对象,相当于给引用加了一个版本号

public class AtomicStampedReference<V> {

    private static class Pair<T> {
        final T reference;
        final int stamp;
        private Pair(T reference, int stamp) {
            this.reference = reference;
            this.stamp = stamp;
        }
        static <T> Pair<T> of(T reference, int stamp) {
            return new Pair<T>(reference, stamp);
        }
    }

    private volatile Pair<V> pair;

    public AtomicStampedReference(V initialRef, int initialStamp) {
        pair = Pair.of(initialRef, initialStamp);
    }

替换时的逻辑,当引用和版本号都相同时才使用 CAS 替换

public boolean compareAndSet(V expectedReference, V newReference, int expectedStamp, int newStamp) {
    Pair<V> current = pair;
    return expectedReference == current.reference &&
                    expectedStamp == current.stamp &&
                    ((newReference == current.reference &&
                            newStamp == current.stamp) ||
                            casPair(current, Pair.of(newReference, newStamp)));
}

private boolean casPair(Pair<V> cmp, Pair<V> val) {
    return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val);
}

 

三、AtomicMarkableReference

相对于 AtomicStampedReference,有时候,我们并不关心引用变量更改了几次,只是单纯的关心是否更改过

public static void main(String[] args) {
    User user1 = new User(10);
    User user2 = new User(20);

    AtomicMarkableReference<User> stampedReference = new AtomicMarkableReference<>(user1, false);

    boolean[] stamp = new boolean[1];
    // 获取引用对象和对应的状态
    System.out.println(stampedReference.get(stamp).getAge());

    boolean oldStamp = stamp[0];
    // 预期引用,新引用,预期状态,新状态
    stampedReference.compareAndSet(user1, user2, oldStamp, false);

    System.out.println(stampedReference.get(stamp).getAge());
}

内部和 AtomicStampedReference 一样

public class AtomicMarkableReference<V> {

    private static class Pair<T> {
        final T reference;
        final boolean mark;
        private Pair(T reference, boolean mark) {
            this.reference = reference;
            this.mark = mark;
        }
        static <T> Pair<T> of(T reference, boolean mark) {
            return new Pair<T>(reference, mark);
        }
    }

    private volatile Pair<V> pair;
    
    public AtomicMarkableReference(V initialRef, boolean initialMark) {
        pair = Pair.of(initialRef, initialMark);
    }

    public boolean compareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark) {
        Pair<V> current = pair;
        return
                expectedReference == current.reference &&
                        expectedMark == current.mark &&
                        ((newReference == current.reference &&
                                newMark == current.mark) ||
                                casPair(current, Pair.of(newReference, newMark)));
    }

    private boolean casPair(Pair<V> cmp, Pair<V> val) {
        return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val);
    }

 


https://segmentfault.com/a/1190000015831791

AtomicReference、AtomicStampedReference、AtomicMarkableReference

AtomicReference、AtomicStampedReference、AtomicMarkableReference

这三个都是自JDK1.5开始加入到java.util.concurrent.atomic下面的。他们都可以在lock-free的情况下以原子的方式更新对象引用。

区别在于:AtomicStampedReference内部维护了一个[reference, integer] pairs的二元组。AtomicMarkableReference 内部维护了一个[reference, boolean] pairs的二元组。

以下部分源码片段摘自JDK1.8(保留了注释):

  • AtomicReference
public class AtomicReference<V> implements java.io.Serializable {
    private static final long serialVersionUID = -1848883965231344442L;

    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    //class初始化时执行
    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicReference.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    //通过volatile关键字保证value值的可见性。
    private volatile V value;
    
    public AtomicReference(V initialValue) {
        value = initialValue;
    }
    
    public AtomicReference() {
    }
    
    //CAS操作
    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
    }
}
  • AtomicStampedReference
public class AtomicStampedReference<V> {
    //内部维护一个静态内部类
    //reference表示引用对象
    //stamp表示时间戳(版本号),int型
    private static class Pair<T> {
        final T reference;
        final int stamp;
        private Pair(T reference, int stamp) {
            this.reference = reference;
            this.stamp = stamp;
        }
        static <T> Pair<T> of(T reference, int stamp) {
            return new Pair<T>(reference, stamp);
        }
    }

    private volatile Pair<V> pair;

    /**
     * Creates a new {@code AtomicStampedReference} with the given
     * initial values.
     *
     * @param initialRef the initial reference
     * @param initialStamp the initial stamp
     */
    public AtomicStampedReference(V initialRef, int initialStamp) {
        pair = Pair.of(initialRef, initialStamp);
    }
    
    /**
     * Atomically sets the value of both the reference and stamp
     * to the given update values if the
     * current reference is {@code ==} to the expected reference
     * and the current stamp is equal to the expected stamp.
     *
     * @param expectedReference the expected value of the reference
     * @param newReference the new value for the reference
     * @param expectedStamp the expected value of the stamp
     * @param newStamp the new value for the stamp
     * @return {@code true} if successful
     */
    public boolean compareAndSet(V   expectedReference,
                                 V   newReference,
                                 int expectedStamp,
                                 int newStamp) {
        Pair<V> current = pair;
        //通过增加了stamp(版本号)的CAS操作,可以避免ABA问题,即更新始终是递增的,不会出现往复。
        return
            expectedReference == current.reference &&
            expectedStamp == current.stamp &&
            ((newReference == current.reference &&
              newStamp == current.stamp) ||
             casPair(current, Pair.of(newReference, newStamp)));
    }
    
    private boolean casPair(Pair<V> cmp, Pair<V> val) {
        return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val);
    }
}
  • AtomicMarkableReference
public class AtomicMarkableReference<V> {
    //这里几乎和AtomicStampedReference相同,只是从 final int stamp 变成了 final boolean mark
    private static class Pair<T> {
        final T reference;
        final boolean mark;
        private Pair(T reference, boolean mark) {
            this.reference = reference;
            this.mark = mark;
        }
        static <T> Pair<T> of(T reference, boolean mark) {
            return new Pair<T>(reference, mark);
        }
    }

    private volatile Pair<V> pair;

    /**
     * Creates a new {@code AtomicMarkableReference} with the given
     * initial values.
     *
     * @param initialRef the initial reference
     * @param initialMark the initial mark
     */
    public AtomicMarkableReference(V initialRef, boolean initialMark) {
        pair = Pair.of(initialRef, initialMark);
    }
}

关于Automatic Reference Counting的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于8 Pratical Examples of Linux “Touch” Command--reference、asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication、AtomicReference、AtomicStampedReference 和 AtomicMarkableReference、AtomicReference、AtomicStampedReference、AtomicMarkableReference的相关信息,请在本站寻找。

本文标签:

上一篇plist文件,Property List 文件(.plist文件)

下一篇Objective-C 征途:String Party(征途java)